From: bors Date: Sun, 10 Feb 2019 01:33:17 +0000 (+0000) Subject: Auto merge of #57770 - Zoxc:no-hash-query, r=michaelwoerister X-Git-Url: https://git.lizzy.rs/?a=commitdiff_plain;h=1bfb44133d1dbabc27acbe63848b072c76f0921f;hp=b4a6f597934f16f89e27058a32a514c9572f148f;p=rust.git Auto merge of #57770 - Zoxc:no-hash-query, r=michaelwoerister Add a query type which is always marked as red if it runs This is useful for queries which produce results which are very likely to change if their inputs do. I also expect this to be useful for end to end queries because 1) we don't need `HashStable` impls and 2) we avoid the overhead of hashing the result of large results like the AST or the HIR map. r? @michaelwoerister --- diff --git a/src/bootstrap/builder.rs b/src/bootstrap/builder.rs index b0d15e6a5df..8540d92f749 100644 --- a/src/bootstrap/builder.rs +++ b/src/bootstrap/builder.rs @@ -1018,8 +1018,7 @@ pub fn cargo( cargo.env("RUSTC_VERBOSE", self.verbosity.to_string()); - // in std, we want to avoid denying warnings for stage 0 as that makes cfg's painful. - if self.config.deny_warnings && !(mode == Mode::Std && stage == 0) { + if self.config.deny_warnings { cargo.env("RUSTC_DENY_WARNINGS", "1"); } diff --git a/src/bootstrap/test.rs b/src/bootstrap/test.rs index 1a46ebfcabb..bb00f6f6251 100644 --- a/src/bootstrap/test.rs +++ b/src/bootstrap/test.rs @@ -1383,6 +1383,7 @@ fn run(self, builder: &Builder) { RustdocBook, "src/doc/rustdoc", "rustdoc", default=true; RustcBook, "src/doc/rustc", "rustc", default=true; RustByExample, "src/doc/rust-by-example", "rust-by-example", default=false; + EmbeddedBook, "src/doc/embedded-book", "embedded-book", default=false; TheBook, "src/doc/book", "book", default=false; UnstableBook, "src/doc/unstable-book", "unstable-book", default=true; ); diff --git a/src/build_helper/Cargo.toml b/src/build_helper/Cargo.toml index 01d704f816b..04c7820b456 100644 --- a/src/build_helper/Cargo.toml +++ b/src/build_helper/Cargo.toml @@ -2,6 +2,7 @@ name = "build_helper" version = "0.1.0" authors = ["The Rust Project Developers"] +edition = "2018" [lib] name = "build_helper" diff --git a/src/build_helper/lib.rs b/src/build_helper/lib.rs index c66c5c92490..93aa9176812 100644 --- a/src/build_helper/lib.rs +++ b/src/build_helper/lib.rs @@ -1,3 +1,5 @@ +#![deny(rust_2018_idioms)] + use std::fs::File; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; diff --git a/src/liballoc/tests/arc.rs b/src/liballoc/tests/arc.rs index 2759b1b1cac..7c5a8926126 100644 --- a/src/liballoc/tests/arc.rs +++ b/src/liballoc/tests/arc.rs @@ -1,3 +1,5 @@ +#![cfg(not(miri))] + use std::any::Any; use std::sync::{Arc, Weak}; use std::cell::RefCell; diff --git a/src/liballoc/tests/binary_heap.rs b/src/liballoc/tests/binary_heap.rs index 94ae43237d1..c1a1c5d8878 100644 --- a/src/liballoc/tests/binary_heap.rs +++ b/src/liballoc/tests/binary_heap.rs @@ -282,6 +282,7 @@ fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> { // // Destructors must be called exactly once per element. #[test] +#[cfg(not(miri))] fn panic_safe() { static DROP_COUNTER: AtomicUsize = AtomicUsize::new(0); diff --git a/src/liballoc/tests/btree/mod.rs b/src/liballoc/tests/btree/mod.rs index 4c704d0f8c2..653b3f5bcb4 100644 --- a/src/liballoc/tests/btree/mod.rs +++ b/src/liballoc/tests/btree/mod.rs @@ -1,3 +1,5 @@ +#![cfg(not(miri))] + mod map; mod set; diff --git a/src/liballoc/tests/heap.rs b/src/liballoc/tests/heap.rs index 24eea1d2949..809d2bc094a 100644 --- a/src/liballoc/tests/heap.rs +++ b/src/liballoc/tests/heap.rs @@ -1,3 +1,5 @@ +#![cfg(not(miri))] + use std::alloc::{Global, Alloc, Layout, System}; /// https://github.com/rust-lang/rust/issues/45955 diff --git a/src/liballoc/tests/rc.rs b/src/liballoc/tests/rc.rs index 18f82e80410..1be01d1a7ce 100644 --- a/src/liballoc/tests/rc.rs +++ b/src/liballoc/tests/rc.rs @@ -1,3 +1,5 @@ +#![cfg(not(miri))] + use std::any::Any; use std::rc::{Rc, Weak}; use std::cell::RefCell; diff --git a/src/liballoc/tests/slice.rs b/src/liballoc/tests/slice.rs index 334466dfb25..2a9fdfa9324 100644 --- a/src/liballoc/tests/slice.rs +++ b/src/liballoc/tests/slice.rs @@ -1,3 +1,5 @@ +#![cfg(not(miri))] + use std::cell::Cell; use std::cmp::Ordering::{self, Equal, Greater, Less}; use std::mem; diff --git a/src/liballoc/tests/str.rs b/src/liballoc/tests/str.rs index 1bc1bd8d78c..f4e6bc9ea31 100644 --- a/src/liballoc/tests/str.rs +++ b/src/liballoc/tests/str.rs @@ -31,6 +31,7 @@ fn test_rfind() { } #[test] +#[cfg(not(miri))] fn test_collect() { let empty = ""; let s: String = empty.chars().collect(); @@ -118,6 +119,7 @@ fn test_concat_for_different_types() { #[test] fn test_concat_for_different_lengths() { let empty: &[&str] = &[]; + #[cfg(not(miri))] test_concat!("", empty); test_concat!("a", ["a"]); test_concat!("ab", ["a", "b"]); @@ -146,6 +148,7 @@ fn test_join_for_different_types() { #[test] fn test_join_for_different_lengths() { let empty: &[&str] = &[]; + #[cfg(not(miri))] test_join!("", empty, "-"); test_join!("a", ["a"], "-"); test_join!("a-b", ["a", "b"], "-"); @@ -159,6 +162,7 @@ fn test_join_for_different_lengths_with_long_separator() { assert_eq!("~~~~~".len(), 15); let empty: &[&str] = &[]; + #[cfg(not(miri))] test_join!("", empty, "~~~~~"); test_join!("a", ["a"], "~~~~~"); test_join!("a~~~~~b", ["a", "b"], "~~~~~"); @@ -166,6 +170,7 @@ fn test_join_for_different_lengths_with_long_separator() { } #[test] +#[cfg(not(miri))] fn test_unsafe_slice() { assert_eq!("ab", unsafe {"abc".get_unchecked(0..2)}); assert_eq!("bc", unsafe {"abc".get_unchecked(1..3)}); @@ -238,6 +243,7 @@ fn test_replacen() { #[test] fn test_replace() { let a = "a"; + #[cfg(not(miri))] assert_eq!("".replace(a, "b"), ""); assert_eq!("a".replace(a, "b"), "b"); assert_eq!("ab".replace(a, "b"), "bb"); @@ -297,6 +303,7 @@ fn test_replace_pattern() { // The current implementation of SliceIndex fails to handle methods // orthogonally from range types; therefore, it is worth testing // all of the indexing operations on each input. +#[cfg(not(miri))] mod slice_index { // Test a slicing operation **that should succeed,** // testing it on all of the indexing methods. @@ -679,6 +686,7 @@ fn test_str_slice_rangetoinclusive_ok() { #[test] #[should_panic] +#[cfg(not(miri))] fn test_str_slice_rangetoinclusive_notok() { let s = "abcαβγ"; &s[..=3]; @@ -694,6 +702,7 @@ fn test_str_slicemut_rangetoinclusive_ok() { #[test] #[should_panic] +#[cfg(not(miri))] fn test_str_slicemut_rangetoinclusive_notok() { let mut s = "abcαβγ".to_owned(); let s: &mut str = &mut s; @@ -883,6 +892,7 @@ fn test_as_bytes() { #[test] #[should_panic] +#[cfg(not(miri))] fn test_as_bytes_fail() { // Don't double free. (I'm not sure if this exercises the // original problem code path anymore.) @@ -972,6 +982,7 @@ fn test_split_at_mut() { #[test] #[should_panic] +#[cfg(not(miri))] fn test_split_at_boundscheck() { let s = "ศไทย中华Việt Nam"; s.split_at(1); @@ -1066,6 +1077,7 @@ fn test_rev_iterator() { } #[test] +#[cfg(not(miri))] fn test_chars_decoding() { let mut bytes = [0; 4]; for c in (0..0x110000).filter_map(std::char::from_u32) { @@ -1077,6 +1089,7 @@ fn test_chars_decoding() { } #[test] +#[cfg(not(miri))] fn test_chars_rev_decoding() { let mut bytes = [0; 4]; for c in (0..0x110000).filter_map(std::char::from_u32) { @@ -1306,6 +1319,7 @@ fn t(s: &str, sep: &str, u: &[&str]) { } #[test] +#[cfg(not(miri))] fn test_str_default() { use std::default::Default; @@ -1365,6 +1379,7 @@ fn test_bool_from_str() { assert_eq!("not even a boolean".parse::().ok(), None); } +#[cfg(not(miri))] fn check_contains_all_substrings(s: &str) { assert!(s.contains("")); for i in 0..s.len() { @@ -1375,6 +1390,7 @@ fn check_contains_all_substrings(s: &str) { } #[test] +#[cfg(not(miri))] fn strslice_issue_16589() { assert!("bananas".contains("nana")); @@ -1384,6 +1400,7 @@ fn strslice_issue_16589() { } #[test] +#[cfg(not(miri))] fn strslice_issue_16878() { assert!(!"1234567ah012345678901ah".contains("hah")); assert!(!"00abc01234567890123456789abc".contains("bcabc")); @@ -1391,6 +1408,7 @@ fn strslice_issue_16878() { #[test] +#[cfg(not(miri))] fn test_strslice_contains() { let x = "There are moments, Jeeves, when one asks oneself, 'Do trousers matter?'"; check_contains_all_substrings(x); @@ -1528,6 +1546,7 @@ fn trim_ws() { #[test] fn to_lowercase() { + #[cfg(not(miri))] assert_eq!("".to_lowercase(), ""); assert_eq!("AÉDžaé ".to_lowercase(), "aédžaé "); @@ -1561,6 +1580,7 @@ fn to_lowercase() { #[test] fn to_uppercase() { + #[cfg(not(miri))] assert_eq!("".to_uppercase(), ""); assert_eq!("aéDžßfiᾀ".to_uppercase(), "AÉDŽSSFIἈΙ"); } @@ -1592,6 +1612,7 @@ fn test_cow_from() { } #[test] +#[cfg(not(miri))] fn test_repeat() { assert_eq!("".repeat(3), ""); assert_eq!("abc".repeat(0), ""); diff --git a/src/liballoc/tests/string.rs b/src/liballoc/tests/string.rs index e5ce51a36ee..e6ca54c4088 100644 --- a/src/liballoc/tests/string.rs +++ b/src/liballoc/tests/string.rs @@ -1,3 +1,5 @@ +#![cfg(not(miri))] + use std::borrow::Cow; use std::collections::CollectionAllocErr::*; use std::mem::size_of; diff --git a/src/liballoc/tests/vec.rs b/src/liballoc/tests/vec.rs index 89f2e0a046d..545332bcd6a 100644 --- a/src/liballoc/tests/vec.rs +++ b/src/liballoc/tests/vec.rs @@ -1,3 +1,5 @@ +#![cfg(not(miri))] + use std::borrow::Cow; use std::mem::size_of; use std::{usize, isize}; diff --git a/src/liballoc/tests/vec_deque.rs b/src/liballoc/tests/vec_deque.rs index aa49bdb0090..b47e7c867e6 100644 --- a/src/liballoc/tests/vec_deque.rs +++ b/src/liballoc/tests/vec_deque.rs @@ -108,6 +108,7 @@ fn test_index() { #[test] #[should_panic] +#[cfg(not(miri))] fn test_index_out_of_bounds() { let mut deq = VecDeque::new(); for i in 1..4 { @@ -906,20 +907,24 @@ fn test_append() { // normal append a.append(&mut b); assert_eq!(a.iter().cloned().collect::>(), [1, 2, 3, 4, 5, 6]); + #[cfg(not(miri))] assert_eq!(b.iter().cloned().collect::>(), []); // append nothing to something a.append(&mut b); assert_eq!(a.iter().cloned().collect::>(), [1, 2, 3, 4, 5, 6]); + #[cfg(not(miri))] assert_eq!(b.iter().cloned().collect::>(), []); // append something to nothing b.append(&mut a); assert_eq!(b.iter().cloned().collect::>(), [1, 2, 3, 4, 5, 6]); + #[cfg(not(miri))] assert_eq!(a.iter().cloned().collect::>(), []); } #[test] +#[cfg(not(miri))] fn test_append_permutations() { fn construct_vec_deque( push_back: usize, @@ -1120,6 +1125,7 @@ fn test_reserve_exact_2() { } #[test] +#[cfg(not(miri))] fn test_try_reserve() { // These are the interesting cases: @@ -1221,6 +1227,7 @@ fn test_try_reserve() { } #[test] +#[cfg(not(miri))] fn test_try_reserve_exact() { // This is exactly the same as test_try_reserve with the method changed. diff --git a/src/libcore/tests/cell.rs b/src/libcore/tests/cell.rs index 56f295dff8e..73bdaab5861 100644 --- a/src/libcore/tests/cell.rs +++ b/src/libcore/tests/cell.rs @@ -1,3 +1,5 @@ +#![cfg(not(miri))] + use core::cell::*; use core::default::Default; use std::mem::drop; diff --git a/src/libcore/tests/fmt/mod.rs b/src/libcore/tests/fmt/mod.rs index d86e21cf40b..b10b63fc484 100644 --- a/src/libcore/tests/fmt/mod.rs +++ b/src/libcore/tests/fmt/mod.rs @@ -1,3 +1,5 @@ +#![cfg(not(miri))] + mod builders; mod float; mod num; diff --git a/src/libcore/tests/hash/mod.rs b/src/libcore/tests/hash/mod.rs index 135f4dfcac7..bf3039a7e51 100644 --- a/src/libcore/tests/hash/mod.rs +++ b/src/libcore/tests/hash/mod.rs @@ -1,3 +1,5 @@ +#![cfg(not(miri))] + mod sip; use std::hash::{Hash, Hasher}; diff --git a/src/libcore/tests/iter.rs b/src/libcore/tests/iter.rs index 0fa99745d90..9b4c78f8d3b 100644 --- a/src/libcore/tests/iter.rs +++ b/src/libcore/tests/iter.rs @@ -190,6 +190,7 @@ fn test_iterator_step_by() { } #[test] +#[cfg(not(miri))] fn test_iterator_step_by_nth() { let mut it = (0..16).step_by(5); assert_eq!(it.nth(0), Some(0)); @@ -208,6 +209,7 @@ fn test_iterator_step_by_nth() { } #[test] +#[cfg(not(miri))] fn test_iterator_step_by_nth_overflow() { #[cfg(target_pointer_width = "8")] type Bigger = u16; @@ -253,12 +255,14 @@ fn nth(&mut self, n: usize) -> Option { #[test] #[should_panic] +#[cfg(not(miri))] fn test_iterator_step_by_zero() { let mut it = (0..).step_by(0); it.next(); } #[test] +#[cfg(not(miri))] fn test_iterator_step_by_size_hint() { struct StubSizeHint(usize, Option); impl Iterator for StubSizeHint { @@ -1413,6 +1417,7 @@ fn test_rposition() { #[test] #[should_panic] +#[cfg(not(miri))] fn test_rposition_panic() { let v: [(Box<_>, Box<_>); 4] = [(box 0, box 0), (box 0, box 0), @@ -1652,6 +1657,7 @@ fn test_range_inclusive_nth() { } #[test] +#[cfg(not(miri))] fn test_range_step() { #![allow(deprecated)] @@ -1675,6 +1681,7 @@ fn test_range_step() { } #[test] +#[cfg(not(miri))] fn test_step_by_skip() { assert_eq!((0..640).step_by(128).skip(1).collect::>(), [128, 256, 384, 512]); assert_eq!((0..=50).step_by(10).nth(3), Some(30)); @@ -1682,6 +1689,7 @@ fn test_step_by_skip() { } #[test] +#[cfg(not(miri))] fn test_range_inclusive_step() { assert_eq!((0..=50).step_by(10).collect::>(), [0, 10, 20, 30, 40, 50]); assert_eq!((0..=5).step_by(1).collect::>(), [0, 1, 2, 3, 4, 5]); diff --git a/src/libcore/tests/num/mod.rs b/src/libcore/tests/num/mod.rs index a17c094679e..ab638e06cc1 100644 --- a/src/libcore/tests/num/mod.rs +++ b/src/libcore/tests/num/mod.rs @@ -1,3 +1,5 @@ +#![cfg(not(miri))] + use core::convert::{TryFrom, TryInto}; use core::cmp::PartialEq; use core::fmt::Debug; diff --git a/src/libcore/tests/option.rs b/src/libcore/tests/option.rs index b059b134868..1ba886ce037 100644 --- a/src/libcore/tests/option.rs +++ b/src/libcore/tests/option.rs @@ -69,6 +69,7 @@ fn test_option_dance() { } #[test] #[should_panic] +#[cfg(not(miri))] fn test_option_too_much_dance() { struct A; let mut y = Some(A); @@ -129,6 +130,7 @@ fn test_unwrap() { #[test] #[should_panic] +#[cfg(not(miri))] fn test_unwrap_panic1() { let x: Option = None; x.unwrap(); @@ -136,6 +138,7 @@ fn test_unwrap_panic1() { #[test] #[should_panic] +#[cfg(not(miri))] fn test_unwrap_panic2() { let x: Option = None; x.unwrap(); diff --git a/src/libcore/tests/ptr.rs b/src/libcore/tests/ptr.rs index 65c1a3e0254..57845590822 100644 --- a/src/libcore/tests/ptr.rs +++ b/src/libcore/tests/ptr.rs @@ -1,3 +1,5 @@ +#![cfg(not(miri))] + use core::ptr::*; use core::cell::RefCell; diff --git a/src/libcore/tests/result.rs b/src/libcore/tests/result.rs index 1fab07526a0..7bfd396f68d 100644 --- a/src/libcore/tests/result.rs +++ b/src/libcore/tests/result.rs @@ -117,6 +117,7 @@ fn handler(msg: &'static str) -> isize { #[test] #[should_panic] +#[cfg(not(miri))] pub fn test_unwrap_or_else_panic() { fn handler(msg: &'static str) -> isize { if msg == "I got this." { @@ -138,6 +139,7 @@ pub fn test_expect_ok() { } #[test] #[should_panic(expected="Got expected error: \"All good\"")] +#[cfg(not(miri))] pub fn test_expect_err() { let err: Result = Err("All good"); err.expect("Got expected error"); @@ -151,6 +153,7 @@ pub fn test_expect_err_err() { } #[test] #[should_panic(expected="Got expected ok: \"All good\"")] +#[cfg(not(miri))] pub fn test_expect_err_ok() { let err: Result<&'static str, isize> = Ok("All good"); err.expect_err("Got expected ok"); diff --git a/src/libcore/tests/slice.rs b/src/libcore/tests/slice.rs index e210e83122c..04d646ea01d 100644 --- a/src/libcore/tests/slice.rs +++ b/src/libcore/tests/slice.rs @@ -782,6 +782,7 @@ macro_rules! assert_range_eq { // to be used in `should_panic`) #[test] #[should_panic(expected = "out of range")] + #[cfg(not(miri))] fn assert_range_eq_can_fail_by_panic() { assert_range_eq!([0, 1, 2], 0..5, [0, 1, 2]); } @@ -791,6 +792,7 @@ fn assert_range_eq_can_fail_by_panic() { // to be used in `should_panic`) #[test] #[should_panic(expected = "==")] + #[cfg(not(miri))] fn assert_range_eq_can_fail_by_inequality() { assert_range_eq!([0, 1, 2], 0..2, [0, 1, 2]); } @@ -840,6 +842,7 @@ fn pass() { #[test] #[should_panic(expected = $expect_msg)] + #[cfg(not(miri))] fn index_fail() { let v = $data; let v: &[_] = &v; @@ -848,6 +851,7 @@ fn index_fail() { #[test] #[should_panic(expected = $expect_msg)] + #[cfg(not(miri))] fn index_mut_fail() { let mut v = $data; let v: &mut [_] = &mut v; @@ -1011,6 +1015,7 @@ fn test_rotate_right() { #[test] #[cfg(not(target_arch = "wasm32"))] +#[cfg(not(miri))] fn sort_unstable() { use core::cmp::Ordering::{Equal, Greater, Less}; use core::slice::heapsort; @@ -1166,6 +1171,7 @@ fn each_alignment_reversed() { } #[test] +#[cfg(not(miri))] fn test_align_to_simple() { let bytes = [1u8, 2, 3, 4, 5, 6, 7]; let (prefix, aligned, suffix) = unsafe { bytes.align_to::() }; @@ -1181,6 +1187,7 @@ fn test_align_to_simple() { } #[test] +#[cfg(not(miri))] fn test_align_to_zst() { let bytes = [1, 2, 3, 4, 5, 6, 7]; let (prefix, aligned, suffix) = unsafe { bytes.align_to::<()>() }; @@ -1189,6 +1196,7 @@ fn test_align_to_zst() { } #[test] +#[cfg(not(miri))] fn test_align_to_non_trivial() { #[repr(align(8))] struct U64(u64, u64); #[repr(align(8))] struct U64U64U32(u64, u64, u32); @@ -1200,6 +1208,7 @@ fn test_align_to_non_trivial() { } #[test] +#[cfg(not(miri))] fn test_align_to_empty_mid() { use core::mem; @@ -1297,6 +1306,7 @@ fn test_copy_within() { #[test] #[should_panic(expected = "src is out of bounds")] +#[cfg(not(miri))] fn test_copy_within_panics_src_too_long() { let mut bytes = *b"Hello, World!"; // The length is only 13, so 14 is out of bounds. @@ -1305,6 +1315,7 @@ fn test_copy_within_panics_src_too_long() { #[test] #[should_panic(expected = "dest is out of bounds")] +#[cfg(not(miri))] fn test_copy_within_panics_dest_too_long() { let mut bytes = *b"Hello, World!"; // The length is only 13, so a slice of length 4 starting at index 10 is out of bounds. @@ -1312,6 +1323,7 @@ fn test_copy_within_panics_dest_too_long() { } #[test] #[should_panic(expected = "src end is before src start")] +#[cfg(not(miri))] fn test_copy_within_panics_src_inverted() { let mut bytes = *b"Hello, World!"; // 2 is greater than 1, so this range is invalid. diff --git a/src/libcore/tests/time.rs b/src/libcore/tests/time.rs index 6efd22572dc..d39bd06930a 100644 --- a/src/libcore/tests/time.rs +++ b/src/libcore/tests/time.rs @@ -1,3 +1,5 @@ +#![cfg(not(miri))] + use core::time::Duration; #[test] diff --git a/src/librustc/hir/def.rs b/src/librustc/hir/def.rs index 6566c6041b6..15efa765029 100644 --- a/src/librustc/hir/def.rs +++ b/src/librustc/hir/def.rs @@ -52,6 +52,7 @@ pub enum Def { AssociatedExistential(DefId), PrimTy(hir::PrimTy), TyParam(DefId), + ConstParam(DefId), SelfTy(Option /* trait */, Option /* impl */), ToolMod, // e.g., `rustfmt` in `#[rustfmt::skip]` @@ -265,7 +266,8 @@ pub fn opt_def_id(&self) -> Option { Def::Fn(id) | Def::Mod(id) | Def::Static(id, _) | Def::Variant(id) | Def::VariantCtor(id, ..) | Def::Enum(id) | Def::TyAlias(id) | Def::TraitAlias(id) | - Def::AssociatedTy(id) | Def::TyParam(id) | Def::Struct(id) | Def::StructCtor(id, ..) | + Def::AssociatedTy(id) | Def::TyParam(id) | Def::ConstParam(id) | Def::Struct(id) | + Def::StructCtor(id, ..) | Def::Union(id) | Def::Trait(id) | Def::Method(id) | Def::Const(id) | Def::AssociatedConst(id) | Def::Macro(id, ..) | Def::Existential(id) | Def::AssociatedExistential(id) | Def::ForeignTy(id) => { @@ -322,6 +324,7 @@ pub fn kind_name(&self) -> &'static str { Def::Const(..) => "constant", Def::AssociatedConst(..) => "associated constant", Def::TyParam(..) => "type parameter", + Def::ConstParam(..) => "const parameter", Def::PrimTy(..) => "builtin type", Def::Local(..) => "local variable", Def::Upvar(..) => "closure capture", diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index d0fd5bd6844..3de41b1665d 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -1157,6 +1157,15 @@ fn lower_generic_arg(&mut self, match arg { ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)), ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)), + ast::GenericArg::Const(ct) => { + // FIXME(const_generics): const generics are not yet defined in the HIR. + self.sess.struct_span_err( + ct.value.span, + "const generics in any position are currently unsupported", + ).emit(); + self.sess.abort_if_errors(); + bug!(); + } } } @@ -2441,7 +2450,7 @@ fn lower_generic_param(&mut self, |this| this.lower_param_bounds(¶m.bounds, itctx.reborrow()), ); - match param.kind { + let (name, kind) = match param.kind { GenericParamKind::Lifetime => { let was_collecting_in_band = self.is_collecting_in_band_lifetimes; self.is_collecting_in_band_lifetimes = false; @@ -2457,22 +2466,14 @@ fn lower_generic_param(&mut self, | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()), hir::LifetimeName::Error => ParamName::Error, }; - let param = hir::GenericParam { - id: lt.id, - hir_id: lt.hir_id, - name: param_name, - span: lt.span, - pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"), - attrs: self.lower_attrs(¶m.attrs), - bounds, - kind: hir::GenericParamKind::Lifetime { - kind: hir::LifetimeParamKind::Explicit, - } + + let kind = hir::GenericParamKind::Lifetime { + kind: hir::LifetimeParamKind::Explicit }; self.is_collecting_in_band_lifetimes = was_collecting_in_band; - param + (param_name, kind) } GenericParamKind::Type { ref default, .. } => { // Don't expose `Self` (recovered "keyword used as ident" parse error). @@ -2491,27 +2492,41 @@ fn lower_generic_param(&mut self, .chain(params) .collect(); } - let LoweredNodeId { node_id, hir_id } = self.lower_node_id(param.id); - hir::GenericParam { - id: node_id, - hir_id, - name: hir::ParamName::Plain(ident), - pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"), - attrs: self.lower_attrs(¶m.attrs), - bounds, - span: ident.span, - kind: hir::GenericParamKind::Type { - default: default.as_ref().map(|x| { - self.lower_ty(x, ImplTraitContext::disallowed()) - }), - synthetic: param.attrs.iter() - .filter(|attr| attr.check_name("rustc_synthetic")) - .map(|_| hir::SyntheticTyParamKind::ImplTrait) - .next(), - } - } + let kind = hir::GenericParamKind::Type { + default: default.as_ref().map(|x| { + self.lower_ty(x, ImplTraitContext::disallowed()) + }), + synthetic: param.attrs.iter() + .filter(|attr| attr.check_name("rustc_synthetic")) + .map(|_| hir::SyntheticTyParamKind::ImplTrait) + .next(), + }; + + (hir::ParamName::Plain(ident), kind) } + GenericParamKind::Const { .. } => { + // FIXME(const_generics): const generics are not yet defined in the HIR. + self.sess.struct_span_err( + param.ident.span, + "const generics in any position are currently unsupported", + ).emit(); + self.sess.abort_if_errors(); + bug!(); + } + }; + + let LoweredNodeId { node_id, hir_id } = self.lower_node_id(param.id); + + hir::GenericParam { + id: node_id, + hir_id, + name, + span: param.ident.span, + pure_wrt_drop: attr::contains_name(¶m.attrs, "may_dangle"), + attrs: self.lower_attrs(¶m.attrs), + bounds, + kind, } } diff --git a/src/librustc/hir/map/def_collector.rs b/src/librustc/hir/map/def_collector.rs index 710170674f7..02fb503e752 100644 --- a/src/librustc/hir/map/def_collector.rs +++ b/src/librustc/hir/map/def_collector.rs @@ -218,6 +218,7 @@ fn visit_generic_param(&mut self, param: &'a GenericParam) { let def_path_data = match param.kind { GenericParamKind::Lifetime { .. } => DefPathData::LifetimeParam(name), GenericParamKind::Type { .. } => DefPathData::TypeParam(name), + GenericParamKind::Const { .. } => DefPathData::ConstParam(name), }; self.create_def(param.id, def_path_data, REGULAR_SPACE, param.ident.span); diff --git a/src/librustc/hir/map/definitions.rs b/src/librustc/hir/map/definitions.rs index a8193e1d348..84e9cde6df1 100644 --- a/src/librustc/hir/map/definitions.rs +++ b/src/librustc/hir/map/definitions.rs @@ -356,10 +356,12 @@ pub enum DefPathData { /// A closure expression ClosureExpr, // Subportions of items - /// A type parameter (generic parameter) + /// A type (generic) parameter TypeParam(InternedString), - /// A lifetime definition + /// A lifetime (generic) parameter LifetimeParam(InternedString), + /// A const (generic) parameter + ConstParam(InternedString), /// A variant of a enum EnumVariant(InternedString), /// A struct field @@ -641,6 +643,7 @@ pub fn get_opt_name(&self) -> Option { MacroDef(name) | TypeParam(name) | LifetimeParam(name) | + ConstParam(name) | EnumVariant(name) | Field(name) | GlobalMetaData(name) => Some(name), @@ -669,6 +672,7 @@ pub fn as_interned_str(&self) -> InternedString { MacroDef(name) | TypeParam(name) | LifetimeParam(name) | + ConstParam(name) | EnumVariant(name) | Field(name) | GlobalMetaData(name) => { diff --git a/src/librustc/ich/impls_hir.rs b/src/librustc/ich/impls_hir.rs index 2b359428b1f..712fd360fbb 100644 --- a/src/librustc/ich/impls_hir.rs +++ b/src/librustc/ich/impls_hir.rs @@ -1046,6 +1046,7 @@ fn to_stable_hash_key(&self, AssociatedExistential(def_id), PrimTy(prim_ty), TyParam(def_id), + ConstParam(def_id), SelfTy(trait_def_id, impl_def_id), ForeignTy(def_id), Fn(def_id), diff --git a/src/librustc/lint/builtin.rs b/src/librustc/lint/builtin.rs index 6ae7448645a..3ff76e98d7b 100644 --- a/src/librustc/lint/builtin.rs +++ b/src/librustc/lint/builtin.rs @@ -352,6 +352,12 @@ "outlives requirements can be inferred" } +declare_lint! { + pub DUPLICATE_MATCHER_BINDING_NAME, + Warn, + "duplicate macro matcher binding name" +} + /// Some lints that are buffered from `libsyntax`. See `syntax::early_buffered_lints`. pub mod parser { declare_lint! { diff --git a/src/librustc/lint/mod.rs b/src/librustc/lint/mod.rs index 4e6bf753b01..8952ae98e59 100644 --- a/src/librustc/lint/mod.rs +++ b/src/librustc/lint/mod.rs @@ -27,7 +27,7 @@ use crate::hir::def_id::{CrateNum, LOCAL_CRATE}; use crate::hir::intravisit; use crate::hir; -use crate::lint::builtin::BuiltinLintDiagnostics; +use crate::lint::builtin::{BuiltinLintDiagnostics, DUPLICATE_MATCHER_BINDING_NAME}; use crate::lint::builtin::parser::{QUESTION_MARK_MACRO_SEP, ILL_FORMED_ATTRIBUTE_INPUT}; use crate::session::{Session, DiagnosticMessageId}; use std::{hash, ptr}; @@ -82,6 +82,7 @@ pub fn from_parser_lint_id(lint_id: BufferedEarlyLintId) -> &'static Self { match lint_id { BufferedEarlyLintId::QuestionMarkMacroSep => QUESTION_MARK_MACRO_SEP, BufferedEarlyLintId::IllFormedAttributeInput => ILL_FORMED_ATTRIBUTE_INPUT, + BufferedEarlyLintId::DuplicateMacroMatcherBindingName => DUPLICATE_MATCHER_BINDING_NAME, } } diff --git a/src/librustc/mir/mod.rs b/src/librustc/mir/mod.rs index 009997bfcf2..a0f16ae2715 100644 --- a/src/librustc/mir/mod.rs +++ b/src/librustc/mir/mod.rs @@ -2154,7 +2154,7 @@ pub fn function_handle<'a>( span, ty, user_ty: None, - literal: tcx.intern_lazy_const( + literal: tcx.mk_lazy_const( ty::LazyConst::Evaluated(ty::Const::zero_sized(ty)), ), }) diff --git a/src/librustc/traits/project.rs b/src/librustc/traits/project.rs index 99107a1a6d4..562a29f53f8 100644 --- a/src/librustc/traits/project.rs +++ b/src/librustc/traits/project.rs @@ -408,7 +408,7 @@ fn fold_const(&mut self, constant: &'tcx ty::LazyConst<'tcx>) -> &'tcx ty::LazyC if let Ok(evaluated) = tcx.const_eval(param_env.and(cid)) { let substs = tcx.lift_to_global(&substs).unwrap(); let evaluated = evaluated.subst(tcx, substs); - return tcx.intern_lazy_const(ty::LazyConst::Evaluated(evaluated)); + return tcx.mk_lazy_const(ty::LazyConst::Evaluated(evaluated)); } } } else { @@ -420,7 +420,7 @@ fn fold_const(&mut self, constant: &'tcx ty::LazyConst<'tcx>) -> &'tcx ty::LazyC promoted: None }; if let Ok(evaluated) = tcx.const_eval(param_env.and(cid)) { - return tcx.intern_lazy_const(ty::LazyConst::Evaluated(evaluated)); + return tcx.mk_lazy_const(ty::LazyConst::Evaluated(evaluated)); } } } diff --git a/src/librustc/traits/query/normalize.rs b/src/librustc/traits/query/normalize.rs index f477f161bbb..bcd11194b57 100644 --- a/src/librustc/traits/query/normalize.rs +++ b/src/librustc/traits/query/normalize.rs @@ -203,7 +203,7 @@ fn fold_const(&mut self, constant: &'tcx ty::LazyConst<'tcx>) -> &'tcx ty::LazyC if let Ok(evaluated) = tcx.const_eval(param_env.and(cid)) { let substs = tcx.lift_to_global(&substs).unwrap(); let evaluated = evaluated.subst(tcx, substs); - return tcx.intern_lazy_const(ty::LazyConst::Evaluated(evaluated)); + return tcx.mk_lazy_const(ty::LazyConst::Evaluated(evaluated)); } } } else { @@ -215,7 +215,7 @@ fn fold_const(&mut self, constant: &'tcx ty::LazyConst<'tcx>) -> &'tcx ty::LazyC promoted: None, }; if let Ok(evaluated) = tcx.const_eval(param_env.and(cid)) { - return tcx.intern_lazy_const(ty::LazyConst::Evaluated(evaluated)); + return tcx.mk_lazy_const(ty::LazyConst::Evaluated(evaluated)); } } } diff --git a/src/librustc/ty/codec.rs b/src/librustc/ty/codec.rs index c9775b10293..e93de32f725 100644 --- a/src/librustc/ty/codec.rs +++ b/src/librustc/ty/codec.rs @@ -252,7 +252,7 @@ pub fn decode_lazy_const<'a, 'tcx, D>(decoder: &mut D) where D: TyDecoder<'a, 'tcx>, 'tcx: 'a, { - Ok(decoder.tcx().intern_lazy_const(Decodable::decode(decoder)?)) + Ok(decoder.tcx().mk_lazy_const(Decodable::decode(decoder)?)) } #[inline] diff --git a/src/librustc/ty/context.rs b/src/librustc/ty/context.rs index 795853a37c7..11211c91c54 100644 --- a/src/librustc/ty/context.rs +++ b/src/librustc/ty/context.rs @@ -127,6 +127,7 @@ pub struct CtxtInterners<'tcx> { goal: InternedSet<'tcx, GoalKind<'tcx>>, goal_list: InternedSet<'tcx, List>>, projs: InternedSet<'tcx, List>>, + lazy_const: InternedSet<'tcx, LazyConst<'tcx>>, } impl<'gcx: 'tcx, 'tcx> CtxtInterners<'tcx> { @@ -144,6 +145,7 @@ fn new(arena: &'tcx SyncDroplessArena) -> CtxtInterners<'tcx> { goal: Default::default(), goal_list: Default::default(), projs: Default::default(), + lazy_const: Default::default(), } } @@ -1096,10 +1098,7 @@ pub fn alloc_adt_def(self, self.global_arenas.adt_def.alloc(def) } - pub fn intern_const_alloc( - self, - alloc: Allocation, - ) -> &'gcx Allocation { + pub fn intern_const_alloc(self, alloc: Allocation) -> &'gcx Allocation { self.allocation_interner.borrow_mut().intern(alloc, |alloc| { self.global_arenas.const_allocs.alloc(alloc) }) @@ -1119,10 +1118,6 @@ pub fn intern_stability(self, stab: attr::Stability) -> &'gcx attr::Stability { }) } - pub fn intern_lazy_const(self, c: ty::LazyConst<'tcx>) -> &'tcx ty::LazyConst<'tcx> { - self.global_interners.arena.alloc(c) - } - pub fn intern_layout(self, layout: LayoutDetails) -> &'gcx LayoutDetails { self.layout_interner.borrow_mut().intern(layout, |layout| { self.global_arenas.layout.alloc(layout) @@ -2272,6 +2267,12 @@ fn borrow<'a>(&'a self) -> &'a GoalKind<'lcx> { } } +impl<'tcx: 'lcx, 'lcx> Borrow> for Interned<'tcx, LazyConst<'tcx>> { + fn borrow<'a>(&'a self) -> &'a LazyConst<'lcx> { + &self.0 + } +} + impl<'tcx: 'lcx, 'lcx> Borrow<[ExistentialPredicate<'lcx>]> for Interned<'tcx, List>> { fn borrow<'a>(&'a self) -> &'a [ExistentialPredicate<'lcx>] { @@ -2378,7 +2379,8 @@ pub fn keep_local<'tcx, T: ty::TypeFoldable<'tcx>>(x: &T) -> bool { direct_interners!('tcx, region: mk_region(|r: &RegionKind| r.keep_in_local_tcx()) -> RegionKind, - goal: mk_goal(|c: &GoalKind<'_>| keep_local(c)) -> GoalKind<'tcx> + goal: mk_goal(|c: &GoalKind<'_>| keep_local(c)) -> GoalKind<'tcx>, + lazy_const: mk_lazy_const(|c: &LazyConst<'_>| keep_local(&c)) -> LazyConst<'tcx> ); macro_rules! slice_interners { @@ -2563,7 +2565,7 @@ pub fn mk_nil_ptr(self) -> Ty<'tcx> { #[inline] pub fn mk_array(self, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> { - self.mk_ty(Array(ty, self.intern_lazy_const( + self.mk_ty(Array(ty, self.mk_lazy_const( ty::LazyConst::Evaluated(ty::Const::from_usize(self.global_tcx(), n)) ))) } diff --git a/src/librustc/ty/item_path.rs b/src/librustc/ty/item_path.rs index f89e50d6969..8214c8bacc7 100644 --- a/src/librustc/ty/item_path.rs +++ b/src/librustc/ty/item_path.rs @@ -325,6 +325,7 @@ pub fn push_item_path(self, buffer: &mut T, def_id: DefId, pushed_prelude_cra data @ DefPathData::Module(..) | data @ DefPathData::TypeParam(..) | data @ DefPathData::LifetimeParam(..) | + data @ DefPathData::ConstParam(..) | data @ DefPathData::EnumVariant(..) | data @ DefPathData::Field(..) | data @ DefPathData::AnonConst | diff --git a/src/librustc/ty/structural_impls.rs b/src/librustc/ty/structural_impls.rs index 62a49238ebf..d09cfa84a16 100644 --- a/src/librustc/ty/structural_impls.rs +++ b/src/librustc/ty/structural_impls.rs @@ -1042,7 +1042,7 @@ fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) ty::LazyConst::Unevaluated(*def_id, substs.fold_with(folder)) } }; - folder.tcx().intern_lazy_const(new) + folder.tcx().mk_lazy_const(new) } fn fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self { diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index 2cd82d44af3..a12ec3471a9 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -426,6 +426,7 @@ fn parameterized(&mut self, DefPathData::ClosureExpr | DefPathData::TypeParam(_) | DefPathData::LifetimeParam(_) | + DefPathData::ConstParam(_) | DefPathData::Field(_) | DefPathData::StructCtor | DefPathData::AnonConst | diff --git a/src/librustc_allocator/Cargo.toml b/src/librustc_allocator/Cargo.toml index 03d33f413c8..cf6c598bfb1 100644 --- a/src/librustc_allocator/Cargo.toml +++ b/src/librustc_allocator/Cargo.toml @@ -2,6 +2,7 @@ authors = ["The Rust Project Developers"] name = "rustc_allocator" version = "0.0.0" +edition = "2018" [lib] path = "lib.rs" diff --git a/src/librustc_allocator/expand.rs b/src/librustc_allocator/expand.rs index 1fb1794d514..d302e7646d1 100644 --- a/src/librustc_allocator/expand.rs +++ b/src/librustc_allocator/expand.rs @@ -1,6 +1,6 @@ +use log::debug; use rustc::middle::allocator::AllocatorKind; -use rustc_errors; -use smallvec::SmallVec; +use smallvec::{smallvec, SmallVec}; use syntax::{ ast::{ self, Arg, Attribute, Crate, Expr, FnHeader, Generics, Ident, Item, ItemKind, @@ -23,7 +23,7 @@ }; use syntax_pos::Span; -use {AllocatorMethod, AllocatorTy, ALLOCATOR_METHODS}; +use crate::{AllocatorMethod, AllocatorTy, ALLOCATOR_METHODS}; pub fn modify( sess: &ParseSess, @@ -54,7 +54,7 @@ struct ExpandAllocatorDirectives<'a> { in_submod: isize, } -impl<'a> MutVisitor for ExpandAllocatorDirectives<'a> { +impl MutVisitor for ExpandAllocatorDirectives<'_> { fn flat_map_item(&mut self, item: P) -> SmallVec<[P; 1]> { debug!("in submodule {}", self.in_submod); @@ -168,7 +168,7 @@ struct AllocFnFactory<'a> { cx: ExtCtxt<'a>, } -impl<'a> AllocFnFactory<'a> { +impl AllocFnFactory<'_> { fn allocator_fn(&self, method: &AllocatorMethod) -> P { let mut abi_args = Vec::new(); let mut i = 0; diff --git a/src/librustc_allocator/lib.rs b/src/librustc_allocator/lib.rs index 41c0be61595..16b9ccfda80 100644 --- a/src/librustc_allocator/lib.rs +++ b/src/librustc_allocator/lib.rs @@ -1,15 +1,6 @@ -#![feature(nll)] #![feature(rustc_private)] -#[macro_use] extern crate log; -extern crate rustc; -extern crate rustc_data_structures; -extern crate rustc_errors; -extern crate rustc_target; -extern crate syntax; -extern crate syntax_pos; -#[macro_use] -extern crate smallvec; +#![deny(rust_2018_idioms)] pub mod expand; diff --git a/src/librustc_borrowck/Cargo.toml b/src/librustc_borrowck/Cargo.toml index 3368bbf3855..f293739dec7 100644 --- a/src/librustc_borrowck/Cargo.toml +++ b/src/librustc_borrowck/Cargo.toml @@ -2,6 +2,7 @@ authors = ["The Rust Project Developers"] name = "rustc_borrowck" version = "0.0.0" +edition = "2018" [lib] name = "rustc_borrowck" @@ -13,8 +14,10 @@ test = false log = "0.4" syntax = { path = "../libsyntax" } syntax_pos = { path = "../libsyntax_pos" } -graphviz = { path = "../libgraphviz" } +# for "clarity", rename the graphviz crate to dot; graphviz within `borrowck` +# refers to the borrowck-specific graphviz adapter traits. +dot = { path = "../libgraphviz", package = "graphviz" } rustc = { path = "../librustc" } rustc_mir = { path = "../librustc_mir" } -rustc_errors = { path = "../librustc_errors" } -rustc_data_structures = { path = "../librustc_data_structures" } \ No newline at end of file +errors = { path = "../librustc_errors", package = "rustc_errors" } +rustc_data_structures = { path = "../librustc_data_structures" } diff --git a/src/librustc_borrowck/borrowck/check_loans.rs b/src/librustc_borrowck/borrowck/check_loans.rs index cafb29ed99a..f675c8d38a6 100644 --- a/src/librustc_borrowck/borrowck/check_loans.rs +++ b/src/librustc_borrowck/borrowck/check_loans.rs @@ -7,10 +7,10 @@ // 3. assignments do not affect things loaned out as immutable // 4. moves do not affect things loaned out in any way -use self::UseError::*; +use UseError::*; -use borrowck::*; -use borrowck::InteriorKind::{InteriorElement, InteriorField}; +use crate::borrowck::*; +use crate::borrowck::InteriorKind::{InteriorElement, InteriorField}; use rustc::middle::expr_use_visitor as euv; use rustc::middle::expr_use_visitor::MutateMode; use rustc::middle::mem_categorization as mc; @@ -22,6 +22,7 @@ use rustc::hir; use rustc::hir::Node; use rustc_mir::util::borrowck_errors::{BorrowckErrors, Origin}; +use log::debug; use std::rc::Rc; @@ -101,7 +102,7 @@ fn consume(&mut self, fn matched_pat(&mut self, _matched_pat: &hir::Pat, - _cmt: &mc::cmt_, + _cmt: &mc::cmt_<'_>, _mode: euv::MatchMode) { } fn consume_pat(&mut self, @@ -910,7 +911,7 @@ fn check_assignment(&self, pub fn report_illegal_mutation(&self, span: Span, loan_path: &LoanPath<'tcx>, - loan: &Loan) { + loan: &Loan<'_>) { self.bccx.cannot_assign_to_borrowed( span, loan.span, &self.bccx.loan_path_to_string(loan_path), Origin::Ast) .emit(); diff --git a/src/librustc_borrowck/borrowck/gather_loans/gather_moves.rs b/src/librustc_borrowck/borrowck/gather_loans/gather_moves.rs index f5e27a953c2..6b050fd9ba2 100644 --- a/src/librustc_borrowck/borrowck/gather_loans/gather_moves.rs +++ b/src/librustc_borrowck/borrowck/gather_loans/gather_moves.rs @@ -1,9 +1,9 @@ //! Computes moves. -use borrowck::*; -use borrowck::gather_loans::move_error::MovePlace; -use borrowck::gather_loans::move_error::{MoveError, MoveErrorCollector}; -use borrowck::move_data::*; +use crate::borrowck::*; +use crate::borrowck::gather_loans::move_error::MovePlace; +use crate::borrowck::gather_loans::move_error::{MoveError, MoveErrorCollector}; +use crate::borrowck::move_data::*; use rustc::middle::expr_use_visitor as euv; use rustc::middle::mem_categorization as mc; use rustc::middle::mem_categorization::Categorization; @@ -15,6 +15,7 @@ use syntax_pos::Span; use rustc::hir::*; use rustc::hir::Node; +use log::debug; struct GatherMoveInfo<'c, 'tcx: 'c> { id: hir::ItemLocalId, diff --git a/src/librustc_borrowck/borrowck/gather_loans/lifetime.rs b/src/librustc_borrowck/borrowck/gather_loans/lifetime.rs index 8fc0a3d6338..11597455bca 100644 --- a/src/librustc_borrowck/borrowck/gather_loans/lifetime.rs +++ b/src/librustc_borrowck/borrowck/gather_loans/lifetime.rs @@ -1,7 +1,7 @@ //! This module implements the check that the lifetime of a borrow //! does not exceed the lifetime of the value being borrowed. -use borrowck::*; +use crate::borrowck::*; use rustc::middle::expr_use_visitor as euv; use rustc::middle::mem_categorization as mc; use rustc::middle::mem_categorization::Categorization; @@ -10,6 +10,7 @@ use syntax::ast; use syntax_pos::Span; +use log::debug; type R = Result<(),()>; diff --git a/src/librustc_borrowck/borrowck/gather_loans/mod.rs b/src/librustc_borrowck/borrowck/gather_loans/mod.rs index d681c771d2f..c21a43bc683 100644 --- a/src/librustc_borrowck/borrowck/gather_loans/mod.rs +++ b/src/librustc_borrowck/borrowck/gather_loans/mod.rs @@ -6,8 +6,8 @@ // their associated scopes. In phase two, checking loans, we will then make // sure that all of these loans are honored. -use borrowck::*; -use borrowck::move_data::MoveData; +use crate::borrowck::*; +use crate::borrowck::move_data::MoveData; use rustc::middle::expr_use_visitor as euv; use rustc::middle::mem_categorization as mc; use rustc::middle::mem_categorization::Categorization; @@ -17,8 +17,9 @@ use syntax::ast; use syntax_pos::Span; use rustc::hir; +use log::debug; -use self::restrictions::RestrictionResult; +use restrictions::RestrictionResult; mod lifetime; mod restrictions; @@ -427,7 +428,7 @@ fn guarantee_valid(&mut self, // } } - pub fn mark_loan_path_as_mutated(&self, loan_path: &LoanPath) { + pub fn mark_loan_path_as_mutated(&self, loan_path: &LoanPath<'_>) { //! For mutable loans of content whose mutability derives //! from a local variable, mark the mutability decl as necessary. diff --git a/src/librustc_borrowck/borrowck/gather_loans/move_error.rs b/src/librustc_borrowck/borrowck/gather_loans/move_error.rs index 00cbc250bd6..622dd8e891a 100644 --- a/src/librustc_borrowck/borrowck/gather_loans/move_error.rs +++ b/src/librustc_borrowck/borrowck/gather_loans/move_error.rs @@ -1,4 +1,4 @@ -use borrowck::BorrowckCtxt; +use crate::borrowck::BorrowckCtxt; use rustc::middle::mem_categorization as mc; use rustc::middle::mem_categorization::Categorization; use rustc::middle::mem_categorization::NoteClosureEnv; @@ -8,7 +8,8 @@ use syntax::ast; use syntax_pos; use errors::{DiagnosticBuilder, Applicability}; -use borrowck::gather_loans::gather_moves::PatternSource; +use crate::borrowck::gather_loans::gather_moves::PatternSource; +use log::debug; pub struct MoveErrorCollector<'tcx> { errors: Vec> @@ -167,10 +168,10 @@ fn report_cannot_move_out_of<'a, 'tcx>(bccx: &'a BorrowckCtxt<'a, 'tcx>, } } -fn note_move_destination(mut err: DiagnosticBuilder, +fn note_move_destination(mut err: DiagnosticBuilder<'_>, move_to_span: syntax_pos::Span, pat_name: ast::Name, - is_first_note: bool) -> DiagnosticBuilder { + is_first_note: bool) -> DiagnosticBuilder<'_> { if is_first_note { err.span_label( move_to_span, diff --git a/src/librustc_borrowck/borrowck/gather_loans/restrictions.rs b/src/librustc_borrowck/borrowck/gather_loans/restrictions.rs index a43a7f1e09a..9f4c05a6b25 100644 --- a/src/librustc_borrowck/borrowck/gather_loans/restrictions.rs +++ b/src/librustc_borrowck/borrowck/gather_loans/restrictions.rs @@ -1,13 +1,14 @@ //! Computes the restrictions that result from a borrow. -use borrowck::*; +use crate::borrowck::*; use rustc::middle::expr_use_visitor as euv; use rustc::middle::mem_categorization as mc; use rustc::middle::mem_categorization::Categorization; use rustc::ty; use syntax_pos::Span; +use log::debug; -use borrowck::ToInteriorKind; +use crate::borrowck::ToInteriorKind; use std::rc::Rc; diff --git a/src/librustc_borrowck/borrowck/mod.rs b/src/librustc_borrowck/borrowck/mod.rs index e40c2b45089..4ced72cd279 100644 --- a/src/librustc_borrowck/borrowck/mod.rs +++ b/src/librustc_borrowck/borrowck/mod.rs @@ -2,13 +2,13 @@ #![allow(non_camel_case_types)] -pub use self::LoanPathKind::*; -pub use self::LoanPathElem::*; -pub use self::bckerr_code::*; -pub use self::AliasableViolationKind::*; -pub use self::MovedValueUseKind::*; +pub use LoanPathKind::*; +pub use LoanPathElem::*; +pub use bckerr_code::*; +pub use AliasableViolationKind::*; +pub use MovedValueUseKind::*; -use self::InteriorKind::*; +use InteriorKind::*; use rustc::hir::HirId; use rustc::hir::Node; @@ -37,10 +37,11 @@ use syntax::ast; use syntax_pos::{MultiSpan, Span}; use errors::{Applicability, DiagnosticBuilder, DiagnosticId}; +use log::debug; use rustc::hir; -use dataflow::{DataFlowContext, BitwiseOperator, DataFlowOperator, KillFrom}; +use crate::dataflow::{DataFlowContext, BitwiseOperator, DataFlowOperator, KillFrom}; pub mod check_loans; @@ -61,7 +62,7 @@ pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { }); } -pub fn provide(providers: &mut Providers) { +pub fn provide(providers: &mut Providers<'_>) { *providers = Providers { borrowck, ..*providers @@ -398,7 +399,7 @@ pub enum LoanPathElem<'tcx> { } fn closure_to_block(closure_id: LocalDefId, - tcx: TyCtxt) -> ast::NodeId { + tcx: TyCtxt<'_, '_, '_>) -> ast::NodeId { let closure_id = tcx.hir().local_def_id_to_node_id(closure_id); match tcx.hir().get(closure_id) { Node::Expr(expr) => match expr.node { @@ -1214,8 +1215,8 @@ fn local_ty(&self, node_id: ast::NodeId) -> (Option<&hir::Ty>, bool) { } fn note_immutability_blame(&self, - db: &mut DiagnosticBuilder, - blame: Option, + db: &mut DiagnosticBuilder<'_>, + blame: Option>, error_node_id: ast::NodeId) { match blame { None => {} @@ -1271,7 +1272,7 @@ fn note_immutability_blame(&self, // binding: either to make the binding mutable (if its type is // not a mutable reference) or to avoid borrowing altogether fn note_immutable_local(&self, - db: &mut DiagnosticBuilder, + db: &mut DiagnosticBuilder<'_>, borrowed_node_id: ast::NodeId, binding_node_id: ast::NodeId) { let let_span = self.tcx.hir().span(binding_node_id); @@ -1349,7 +1350,7 @@ fn region_end_span(&self, region: ty::Region<'tcx>) -> Option { } } - fn note_and_explain_mutbl_error(&self, db: &mut DiagnosticBuilder, err: &BckError<'a, 'tcx>, + fn note_and_explain_mutbl_error(&self, db: &mut DiagnosticBuilder<'_>, err: &BckError<'a, 'tcx>, error_span: &Span) { match err.cmt.note { mc::NoteClosureEnv(upvar_id) | mc::NoteUpvarRef(upvar_id) => { @@ -1487,7 +1488,7 @@ fn initial_value(&self) -> bool { } impl<'tcx> fmt::Debug for InteriorKind { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { InteriorField(mc::FieldIndex(_, info)) => write!(f, "{}", info), InteriorElement => write!(f, "[]"), @@ -1496,7 +1497,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } impl<'tcx> fmt::Debug for Loan<'tcx> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Loan_{}({:?}, {:?}, {:?}-{:?}, {:?})", self.index, self.loan_path, @@ -1508,7 +1509,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } impl<'tcx> fmt::Debug for LoanPath<'tcx> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.kind { LpVar(id) => { write!(f, "$({})", ty::tls::with(|tcx| tcx.hir().node_to_string(id))) @@ -1543,7 +1544,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } impl<'tcx> fmt::Display for LoanPath<'tcx> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.kind { LpVar(id) => { write!(f, "$({})", ty::tls::with(|tcx| tcx.hir().node_to_user_string(id))) diff --git a/src/librustc_borrowck/borrowck/move_data.rs b/src/librustc_borrowck/borrowck/move_data.rs index 56c9f928eb0..a206c37e97b 100644 --- a/src/librustc_borrowck/borrowck/move_data.rs +++ b/src/librustc_borrowck/borrowck/move_data.rs @@ -1,11 +1,11 @@ //! Data structures used for tracking moves. Please see the extensive //! comments in the section "Moves and initialization" in `README.md`. -pub use self::MoveKind::*; +pub use MoveKind::*; -use dataflow::{DataFlowContext, BitwiseOperator, DataFlowOperator, KillFrom}; +use crate::dataflow::{DataFlowContext, BitwiseOperator, DataFlowOperator, KillFrom}; -use borrowck::*; +use crate::borrowck::*; use rustc::cfg; use rustc::ty::{self, TyCtxt}; use rustc::util::nodemap::FxHashMap; @@ -15,6 +15,7 @@ use std::usize; use syntax_pos::Span; use rustc::hir; +use log::debug; #[derive(Default)] pub struct MoveData<'tcx> { @@ -145,7 +146,7 @@ pub struct Assignment { pub type AssignDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, AssignDataFlowOperator>; -fn loan_path_is_precise(loan_path: &LoanPath) -> bool { +fn loan_path_is_precise(loan_path: &LoanPath<'_>) -> bool { match loan_path.kind { LpVar(_) | LpUpvar(_) => { true @@ -428,8 +429,8 @@ fn add_assignment_helper(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, /// killed by scoping. See `README.md` for more details. fn add_gen_kills(&self, bccx: &BorrowckCtxt<'a, 'tcx>, - dfcx_moves: &mut MoveDataFlow, - dfcx_assign: &mut AssignDataFlow) { + dfcx_moves: &mut MoveDataFlow<'_, '_>, + dfcx_assign: &mut AssignDataFlow<'_, '_>) { for (i, the_move) in self.moves.borrow().iter().enumerate() { dfcx_moves.add_gen(the_move.id, i); } @@ -537,7 +538,7 @@ fn kill_moves(&self, path: MovePathIndex, kill_id: hir::ItemLocalId, kill_kind: KillFrom, - dfcx_moves: &mut MoveDataFlow) { + dfcx_moves: &mut MoveDataFlow<'_, '_>) { // We can only perform kills for paths that refer to a unique location, // since otherwise we may kill a move from one location with an // assignment referring to another location. diff --git a/src/librustc_borrowck/borrowck/unused.rs b/src/librustc_borrowck/borrowck/unused.rs index 5db98f0e223..60a9c18e95e 100644 --- a/src/librustc_borrowck/borrowck/unused.rs +++ b/src/librustc_borrowck/borrowck/unused.rs @@ -7,7 +7,7 @@ use std::slice; use syntax::ptr::P; -use borrowck::BorrowckCtxt; +use crate::borrowck::BorrowckCtxt; pub fn check<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, body: &'tcx hir::Body) { let mut used_mut = bccx.used_mut_nodes.borrow().clone(); diff --git a/src/librustc_borrowck/dataflow.rs b/src/librustc_borrowck/dataflow.rs index 8cf62056740..90f33ede62c 100644 --- a/src/librustc_borrowck/dataflow.rs +++ b/src/librustc_borrowck/dataflow.rs @@ -10,6 +10,7 @@ use std::mem; use std::usize; use syntax::print::pprust::PrintState; +use log::debug; use rustc_data_structures::graph::implementation::OUTGOING; @@ -80,7 +81,7 @@ pub trait DataFlowOperator : BitwiseOperator { fn initial_value(&self) -> bool; } -struct PropagationContext<'a, 'b: 'a, 'tcx: 'b, O: 'a> { +struct PropagationContext<'a, 'b: 'a, 'tcx: 'b, O> { dfcx: &'a mut DataFlowContext<'b, 'tcx, O>, changed: bool } @@ -99,12 +100,12 @@ fn has_bitset_for_local_id(&self, n: hir::ItemLocalId) -> bool { } impl<'a, 'tcx, O:DataFlowOperator> pprust::PpAnn for DataFlowContext<'a, 'tcx, O> { - fn nested(&self, state: &mut pprust::State, nested: pprust::Nested) -> io::Result<()> { + fn nested(&self, state: &mut pprust::State<'_>, nested: pprust::Nested) -> io::Result<()> { pprust::PpAnn::nested(self.tcx.hir(), state, nested) } fn pre(&self, - ps: &mut pprust::State, - node: pprust::AnnNode) -> io::Result<()> { + ps: &mut pprust::State<'_>, + node: pprust::AnnNode<'_>) -> io::Result<()> { let id = match node { pprust::AnnNode::Name(_) => return Ok(()), pprust::AnnNode::Expr(expr) => expr.hir_id.local_id, diff --git a/src/librustc_borrowck/graphviz.rs b/src/librustc_borrowck/graphviz.rs index adad8c55f21..77056d4d3eb 100644 --- a/src/librustc_borrowck/graphviz.rs +++ b/src/librustc_borrowck/graphviz.rs @@ -2,16 +2,15 @@ //! libgraphviz traits, specialized to attaching borrowck analysis //! data to rendered labels. -pub use self::Variant::*; +pub use Variant::*; pub use rustc::cfg::graphviz::{Node, Edge}; use rustc::cfg::graphviz as cfg_dot; -use borrowck; -use borrowck::{BorrowckCtxt, LoanPath}; -use dot; +use crate::borrowck::{self, BorrowckCtxt, LoanPath}; +use crate::dataflow::{DataFlowOperator, DataFlowContext, EntryOrExit}; +use log::debug; use rustc::cfg::CFGIndex; -use dataflow::{DataFlowOperator, DataFlowContext, EntryOrExit}; use std::rc::Rc; #[derive(Debug, Copy, Clone)] @@ -53,7 +52,7 @@ fn dataflow_for(&self, e: EntryOrExit, n: &Node<'a>) -> String { sets } - fn dataflow_for_variant(&self, e: EntryOrExit, n: &Node, v: Variant) -> String { + fn dataflow_for_variant(&self, e: EntryOrExit, n: &Node<'_>, v: Variant) -> String { let cfgidx = n.0; match v { Loans => self.dataflow_loans_for(e, cfgidx), @@ -89,7 +88,7 @@ fn dataflow_loans_for(&self, e: EntryOrExit, cfgidx: CFGIndex) -> String { let dfcx = &self.analysis_data.loans; let loan_index_to_path = |loan_index| { let all_loans = &self.analysis_data.all_loans; - let l: &borrowck::Loan = &all_loans[loan_index]; + let l: &borrowck::Loan<'_> = &all_loans[loan_index]; l.loan_path() }; self.build_set(e, cfgidx, dfcx, loan_index_to_path) diff --git a/src/librustc_borrowck/lib.rs b/src/librustc_borrowck/lib.rs index 49890330a4e..cf4669db87e 100644 --- a/src/librustc_borrowck/lib.rs +++ b/src/librustc_borrowck/lib.rs @@ -1,23 +1,14 @@ #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")] #![allow(non_camel_case_types)] +#![deny(rust_2018_idioms)] #![feature(nll)] #![recursion_limit="256"] -#[macro_use] extern crate log; -extern crate syntax; -extern crate syntax_pos; -extern crate rustc_errors as errors; -extern crate rustc_data_structures; - -// for "clarity", rename the graphviz crate to dot; graphviz within `borrowck` -// refers to the borrowck-specific graphviz adapter traits. -extern crate graphviz as dot; #[macro_use] extern crate rustc; -extern crate rustc_mir; pub use borrowck::check_crate; pub use borrowck::build_borrowck_dataflow_data_for_fn; diff --git a/src/librustc_codegen_utils/Cargo.toml b/src/librustc_codegen_utils/Cargo.toml index 34a09f30b64..5f241eb20fb 100644 --- a/src/librustc_codegen_utils/Cargo.toml +++ b/src/librustc_codegen_utils/Cargo.toml @@ -2,6 +2,7 @@ authors = ["The Rust Project Developers"] name = "rustc_codegen_utils" version = "0.0.0" +edition = "2018" [lib] name = "rustc_codegen_utils" diff --git a/src/librustc_codegen_utils/codegen_backend.rs b/src/librustc_codegen_utils/codegen_backend.rs index a87b02d33de..28d7d184228 100644 --- a/src/librustc_codegen_utils/codegen_backend.rs +++ b/src/librustc_codegen_utils/codegen_backend.rs @@ -29,7 +29,7 @@ use rustc::middle::cstore::MetadataLoader; use rustc::dep_graph::DepGraph; use rustc_target::spec::Target; -use link::out_filename; +use crate::link::out_filename; pub use rustc_data_structures::sync::MetadataRef; @@ -42,8 +42,8 @@ fn print_version(&self) {} fn diagnostics(&self) -> &[(&'static str, &'static str)] { &[] } fn metadata_loader(&self) -> Box; - fn provide(&self, _providers: &mut Providers); - fn provide_extern(&self, _providers: &mut Providers); + fn provide(&self, _providers: &mut Providers<'_>); + fn provide_extern(&self, _providers: &mut Providers<'_>); fn codegen_crate<'a, 'tcx>( &self, tcx: TyCtxt<'a, 'tcx, 'tcx>, @@ -109,8 +109,8 @@ fn metadata_loader(&self) -> Box { box NoLlvmMetadataLoader } - fn provide(&self, providers: &mut Providers) { - ::symbol_names::provide(providers); + fn provide(&self, providers: &mut Providers<'_>) { + crate::symbol_names::provide(providers); providers.target_features_whitelist = |_tcx, _cnum| { Default::default() // Just a dummy @@ -118,7 +118,7 @@ fn provide(&self, providers: &mut Providers) { providers.is_reachable_non_generic = |_tcx, _defid| true; providers.exported_symbols = |_tcx, _crate| Arc::new(Vec::new()); } - fn provide_extern(&self, providers: &mut Providers) { + fn provide_extern(&self, providers: &mut Providers<'_>) { providers.is_reachable_non_generic = |_tcx, _defid| true; } @@ -129,12 +129,12 @@ fn codegen_crate<'a, 'tcx>( ) -> Box { use rustc_mir::monomorphize::item::MonoItem; - ::check_for_rustc_errors_attr(tcx); - ::symbol_names_test::report_symbol_names(tcx); - ::rustc_incremental::assert_dep_graph(tcx); - ::rustc_incremental::assert_module_sources::assert_module_sources(tcx); + crate::check_for_rustc_errors_attr(tcx); + crate::symbol_names_test::report_symbol_names(tcx); + rustc_incremental::assert_dep_graph(tcx); + rustc_incremental::assert_module_sources::assert_module_sources(tcx); // FIXME: Fix this - // ::rustc::middle::dependency_format::calculate(tcx); + // rustc::middle::dependency_format::calculate(tcx); let _ = tcx.link_args(LOCAL_CRATE); let _ = tcx.native_libraries(LOCAL_CRATE); let (_, cgus) = tcx.collect_and_partition_mono_items(LOCAL_CRATE); diff --git a/src/librustc_codegen_utils/lib.rs b/src/librustc_codegen_utils/lib.rs index d6ef555144d..2b70141894b 100644 --- a/src/librustc_codegen_utils/lib.rs +++ b/src/librustc_codegen_utils/lib.rs @@ -14,18 +14,10 @@ #![recursion_limit="256"] -extern crate flate2; -#[macro_use] -extern crate log; +#![deny(rust_2018_idioms)] #[macro_use] extern crate rustc; -extern crate rustc_target; -extern crate rustc_metadata; -extern crate rustc_mir; -extern crate rustc_incremental; -extern crate syntax; -extern crate syntax_pos; #[macro_use] extern crate rustc_data_structures; use rustc::ty::TyCtxt; @@ -40,7 +32,7 @@ /// error in codegen. This is used to write compile-fail tests /// that actually test that compilation succeeds without /// reporting an error. -pub fn check_for_rustc_errors_attr(tcx: TyCtxt) { +pub fn check_for_rustc_errors_attr(tcx: TyCtxt<'_, '_, '_>) { if let Some((def_id, _)) = tcx.entry_fn(LOCAL_CRATE) { if tcx.has_attr(def_id, "rustc_error") { tcx.sess.span_fatal(tcx.def_span(def_id), "compilation successful"); diff --git a/src/librustc_codegen_utils/link.rs b/src/librustc_codegen_utils/link.rs index 09e22bd2c91..f3a1b219f8a 100644 --- a/src/librustc_codegen_utils/link.rs +++ b/src/librustc_codegen_utils/link.rs @@ -41,7 +41,7 @@ pub fn find_crate_name(sess: Option<&Session>, attrs: &[ast::Attribute], input: &Input) -> String { let validate = |s: String, span: Option| { - ::rustc_metadata::validate_crate_name(sess, &s, span); + rustc_metadata::validate_crate_name(sess, &s, span); s }; diff --git a/src/librustc_codegen_utils/symbol_names.rs b/src/librustc_codegen_utils/symbol_names.rs index 3238a0b10bf..8d105853d92 100644 --- a/src/librustc_codegen_utils/symbol_names.rs +++ b/src/librustc_codegen_utils/symbol_names.rs @@ -103,10 +103,12 @@ use syntax_pos::symbol::Symbol; +use log::debug; + use std::fmt::Write; use std::mem::discriminant; -pub fn provide(providers: &mut Providers) { +pub fn provide(providers: &mut Providers<'_>) { *providers = Providers { def_symbol_name, symbol_name, diff --git a/src/librustc_cratesio_shim/Cargo.toml b/src/librustc_cratesio_shim/Cargo.toml index b8e494e4040..6bdfbe09354 100644 --- a/src/librustc_cratesio_shim/Cargo.toml +++ b/src/librustc_cratesio_shim/Cargo.toml @@ -15,6 +15,7 @@ authors = ["The Rust Project Developers"] name = "rustc_cratesio_shim" version = "0.0.0" +edition = "2018" [lib] crate-type = ["dylib"] diff --git a/src/librustc_cratesio_shim/src/lib.rs b/src/librustc_cratesio_shim/src/lib.rs index 4024087f4d3..4c170f4f5f6 100644 --- a/src/librustc_cratesio_shim/src/lib.rs +++ b/src/librustc_cratesio_shim/src/lib.rs @@ -1,3 +1,5 @@ +#![deny(rust_2018_idioms)] + // See Cargo.toml for a comment explaining this crate. #![allow(unused_extern_crates)] diff --git a/src/librustc_data_structures/Cargo.toml b/src/librustc_data_structures/Cargo.toml index 1754376a5d7..f781952d417 100644 --- a/src/librustc_data_structures/Cargo.toml +++ b/src/librustc_data_structures/Cargo.toml @@ -2,6 +2,7 @@ authors = ["The Rust Project Developers"] name = "rustc_data_structures" version = "0.0.0" +edition = "2018" [lib] name = "rustc_data_structures" @@ -16,8 +17,8 @@ serialize = { path = "../libserialize" } graphviz = { path = "../libgraphviz" } cfg-if = "0.1.2" stable_deref_trait = "1.0.0" -rustc-rayon = "0.1.1" -rustc-rayon-core = "0.1.1" +rayon = { version = "0.1.1", package = "rustc-rayon" } +rayon-core = { version = "0.1.1", package = "rustc-rayon-core" } rustc-hash = "1.0.1" smallvec = { version = "0.6.7", features = ["union", "may_dangle"] } diff --git a/src/librustc_data_structures/bit_set.rs b/src/librustc_data_structures/bit_set.rs index 8adfe3749af..05d2185ae69 100644 --- a/src/librustc_data_structures/bit_set.rs +++ b/src/librustc_data_structures/bit_set.rs @@ -1,4 +1,4 @@ -use indexed_vec::{Idx, IndexVec}; +use crate::indexed_vec::{Idx, IndexVec}; use smallvec::SmallVec; use std::fmt; use std::iter; @@ -208,7 +208,7 @@ fn subtract_from(&self, other: &mut BitSet) -> bool { } impl fmt::Debug for BitSet { - fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result { w.debug_list() .entries(self.iter()) .finish() @@ -366,7 +366,7 @@ fn to_dense(&self) -> BitSet { dense } - fn iter(&self) -> slice::Iter { + fn iter(&self) -> slice::Iter<'_, T> { self.elems.iter() } } @@ -536,7 +536,7 @@ pub fn to_dense(self) -> BitSet { } } - pub fn iter(&self) -> HybridIter { + pub fn iter(&self) -> HybridIter<'_, T> { match self { HybridBitSet::Sparse(sparse) => HybridIter::Sparse(sparse.iter()), HybridBitSet::Dense(dense) => HybridIter::Dense(dense.iter()), diff --git a/src/librustc_data_structures/fingerprint.rs b/src/librustc_data_structures/fingerprint.rs index 2e596ca3e44..c4c0db58012 100644 --- a/src/librustc_data_structures/fingerprint.rs +++ b/src/librustc_data_structures/fingerprint.rs @@ -1,5 +1,5 @@ +use crate::stable_hasher; use std::mem; -use stable_hasher; use serialize; use serialize::opaque::{EncodeResult, Encoder, Decoder}; @@ -70,7 +70,7 @@ pub fn decode_opaque<'a>(decoder: &mut Decoder<'a>) -> Result ::std::fmt::Result { + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { write!(formatter, "{:x}-{:x}", self.0, self.1) } } diff --git a/src/librustc_data_structures/flock.rs b/src/librustc_data_structures/flock.rs index 2dea249f1c0..255c5fd7fe7 100644 --- a/src/librustc_data_structures/flock.rs +++ b/src/librustc_data_structures/flock.rs @@ -14,12 +14,9 @@ if #[cfg(unix)] { use std::ffi::{CString, OsStr}; use std::os::unix::prelude::*; - use libc; #[cfg(any(target_os = "linux", target_os = "android"))] mod os { - use libc; - #[repr(C)] pub struct flock { pub l_type: libc::c_short, @@ -35,8 +32,6 @@ pub struct flock { #[cfg(target_os = "freebsd")] mod os { - use libc; - #[repr(C)] pub struct flock { pub l_start: libc::off_t, @@ -53,8 +48,6 @@ pub struct flock { target_os = "netbsd", target_os = "openbsd"))] mod os { - use libc; - #[repr(C)] pub struct flock { pub l_start: libc::off_t, @@ -70,8 +63,6 @@ pub struct flock { #[cfg(target_os = "haiku")] mod os { - use libc; - #[repr(C)] pub struct flock { pub l_type: libc::c_short, @@ -87,8 +78,6 @@ pub struct flock { #[cfg(any(target_os = "macos", target_os = "ios"))] mod os { - use libc; - #[repr(C)] pub struct flock { pub l_start: libc::off_t, @@ -104,8 +93,6 @@ pub struct flock { #[cfg(target_os = "solaris")] mod os { - use libc; - #[repr(C)] pub struct flock { pub l_type: libc::c_short, diff --git a/src/librustc_data_structures/graph/dominators/mod.rs b/src/librustc_data_structures/graph/dominators/mod.rs index 536efffbb22..aaed41d9fa3 100644 --- a/src/librustc_data_structures/graph/dominators/mod.rs +++ b/src/librustc_data_structures/graph/dominators/mod.rs @@ -117,7 +117,7 @@ pub fn immediate_dominator(&self, node: Node) -> Node { self.immediate_dominators[node].unwrap() } - pub fn dominators(&self, node: Node) -> Iter { + pub fn dominators(&self, node: Node) -> Iter<'_, Node> { assert!(self.is_reachable(node), "node {:?} is not reachable", node); Iter { dominators: self, @@ -136,7 +136,7 @@ fn all_immediate_dominators(&self) -> &IndexVec> { } } -pub struct Iter<'dom, Node: Idx + 'dom> { +pub struct Iter<'dom, Node: Idx> { dominators: &'dom Dominators, node: Option, } @@ -171,7 +171,7 @@ pub fn children(&self, node: Node) -> &[Node] { } impl fmt::Debug for DominatorTree { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt( &DominatorTreeNode { tree: self, @@ -188,7 +188,7 @@ struct DominatorTreeNode<'tree, Node: Idx> { } impl<'tree, Node: Idx> fmt::Debug for DominatorTreeNode<'tree, Node> { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let subtrees: Vec<_> = self.tree .children(self.node) .iter() diff --git a/src/librustc_data_structures/graph/implementation/mod.rs b/src/librustc_data_structures/graph/implementation/mod.rs index 0768873f836..a8b73409406 100644 --- a/src/librustc_data_structures/graph/implementation/mod.rs +++ b/src/librustc_data_structures/graph/implementation/mod.rs @@ -20,10 +20,10 @@ //! the field `next_edge`). Each of those fields is an array that should //! be indexed by the direction (see the type `Direction`). -use bit_set::BitSet; +use crate::bit_set::BitSet; +use crate::snapshot_vec::{SnapshotVec, SnapshotVecDelegate}; use std::fmt::Debug; use std::usize; -use snapshot_vec::{SnapshotVec, SnapshotVecDelegate}; #[cfg(test)] mod tests; @@ -212,15 +212,19 @@ pub fn each_edge<'a>(&'a self, mut f: impl FnMut(EdgeIndex, &'a Edge) -> bool .all(|(edge_idx, edge)| f(edge_idx, edge)) } - pub fn outgoing_edges(&self, source: NodeIndex) -> AdjacentEdges { + pub fn outgoing_edges(&self, source: NodeIndex) -> AdjacentEdges<'_, N, E> { self.adjacent_edges(source, OUTGOING) } - pub fn incoming_edges(&self, source: NodeIndex) -> AdjacentEdges { + pub fn incoming_edges(&self, source: NodeIndex) -> AdjacentEdges<'_, N, E> { self.adjacent_edges(source, INCOMING) } - pub fn adjacent_edges(&self, source: NodeIndex, direction: Direction) -> AdjacentEdges { + pub fn adjacent_edges( + &self, + source: NodeIndex, + direction: Direction + ) -> AdjacentEdges<'_, N, E> { let first_edge = self.node(source).first_edge[direction.repr]; AdjacentEdges { graph: self, @@ -291,11 +295,7 @@ pub fn nodes_in_postorder( // # Iterators -pub struct AdjacentEdges<'g, N, E> -where - N: 'g, - E: 'g, -{ +pub struct AdjacentEdges<'g, N, E> { graph: &'g Graph, direction: Direction, next: EdgeIndex, @@ -331,11 +331,7 @@ fn size_hint(&self) -> (usize, Option) { } } -pub struct DepthFirstTraversal<'g, N, E> -where - N: 'g, - E: 'g, -{ +pub struct DepthFirstTraversal<'g, N, E> { graph: &'g Graph, stack: Vec, visited: BitSet, diff --git a/src/librustc_data_structures/graph/implementation/tests.rs b/src/librustc_data_structures/graph/implementation/tests.rs index a7a25042396..82c6da3f427 100644 --- a/src/librustc_data_structures/graph/implementation/tests.rs +++ b/src/librustc_data_structures/graph/implementation/tests.rs @@ -1,4 +1,4 @@ -use graph::implementation::*; +use crate::graph::implementation::*; use std::fmt::Debug; type TestGraph = Graph<&'static str, &'static str>; diff --git a/src/librustc_data_structures/graph/scc/mod.rs b/src/librustc_data_structures/graph/scc/mod.rs index baab377ef12..e3264fda262 100644 --- a/src/librustc_data_structures/graph/scc/mod.rs +++ b/src/librustc_data_structures/graph/scc/mod.rs @@ -3,9 +3,9 @@ //! node in the graph. This uses Tarjan's algorithm that completes in //! O(n) time. -use fx::FxHashSet; -use graph::{DirectedGraph, WithNumNodes, WithSuccessors}; -use indexed_vec::{Idx, IndexVec}; +use crate::fx::FxHashSet; +use crate::graph::{DirectedGraph, WithNumNodes, WithSuccessors}; +use crate::indexed_vec::{Idx, IndexVec}; use std::ops::Range; mod test; @@ -93,7 +93,7 @@ fn create_scc(&mut self, successors: impl IntoIterator) -> S { } } -struct SccsConstruction<'c, G: DirectedGraph + WithNumNodes + WithSuccessors + 'c, S: Idx> { +struct SccsConstruction<'c, G: DirectedGraph + WithNumNodes + WithSuccessors, S: Idx> { graph: &'c G, /// The state of each node; used during walk to record the stack diff --git a/src/librustc_data_structures/graph/scc/test.rs b/src/librustc_data_structures/graph/scc/test.rs index e23cb1348b0..da3a1ceefe9 100644 --- a/src/librustc_data_structures/graph/scc/test.rs +++ b/src/librustc_data_structures/graph/scc/test.rs @@ -1,6 +1,6 @@ #![cfg(test)] -use graph::test::TestGraph; +use crate::graph::test::TestGraph; use super::*; #[test] diff --git a/src/librustc_data_structures/graph/test.rs b/src/librustc_data_structures/graph/test.rs index 3d482e448bd..b390c419572 100644 --- a/src/librustc_data_structures/graph/test.rs +++ b/src/librustc_data_structures/graph/test.rs @@ -1,4 +1,4 @@ -use fx::FxHashMap; +use crate::fx::FxHashMap; use std::cmp::max; use std::slice; use std::iter; diff --git a/src/librustc_data_structures/indexed_vec.rs b/src/librustc_data_structures/indexed_vec.rs index 8d8fbe588a0..516ea7fb7d9 100644 --- a/src/librustc_data_structures/indexed_vec.rs +++ b/src/librustc_data_structures/indexed_vec.rs @@ -257,7 +257,7 @@ fn from(value: u32) -> Self { @type [$type:ident] @debug_format [$debug_format:tt]) => ( impl ::std::fmt::Debug for $type { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { write!(fmt, $debug_format, self.as_u32()) } } @@ -495,7 +495,7 @@ fn decode(d: &mut D) -> Result { } impl fmt::Debug for IndexVec { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&self.raw, fmt) } } @@ -573,7 +573,7 @@ pub fn into_iter_enumerated(self) -> Enumerated> } #[inline] - pub fn iter(&self) -> slice::Iter { + pub fn iter(&self) -> slice::Iter<'_, T> { self.raw.iter() } @@ -589,7 +589,7 @@ pub fn indices(&self) -> iter::Map, IntoIdx> { } #[inline] - pub fn iter_mut(&mut self) -> slice::IterMut { + pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> { self.raw.iter_mut() } diff --git a/src/librustc_data_structures/lib.rs b/src/librustc_data_structures/lib.rs index a46f8aed324..08b453cf493 100644 --- a/src/librustc_data_structures/lib.rs +++ b/src/librustc_data_structures/lib.rs @@ -24,23 +24,16 @@ #![cfg_attr(unix, feature(libc))] #![cfg_attr(test, feature(test))] -extern crate core; -extern crate ena; +#![deny(rust_2018_idioms)] + #[macro_use] extern crate log; +#[allow(unused_extern_crates)] extern crate serialize as rustc_serialize; // used by deriving #[cfg(unix)] extern crate libc; -extern crate parking_lot; #[macro_use] extern crate cfg_if; -extern crate stable_deref_trait; -extern crate rustc_rayon as rayon; -extern crate rustc_rayon_core as rayon_core; -extern crate rustc_hash; -extern crate serialize; -extern crate graphviz; -extern crate smallvec; // See librustc_cratesio_shim/Cargo.toml for a comment explaining this. #[allow(unused_extern_crates)] diff --git a/src/librustc_data_structures/obligation_forest/graphviz.rs b/src/librustc_data_structures/obligation_forest/graphviz.rs index c2e3938b305..72551b42324 100644 --- a/src/librustc_data_structures/obligation_forest/graphviz.rs +++ b/src/librustc_data_structures/obligation_forest/graphviz.rs @@ -1,5 +1,5 @@ +use crate::obligation_forest::{ForestObligation, ObligationForest}; use graphviz as dot; -use obligation_forest::{ForestObligation, ObligationForest}; use std::env::var_os; use std::fs::File; use std::path::Path; @@ -41,22 +41,22 @@ impl<'a, O: ForestObligation + 'a> dot::Labeller<'a> for &'a ObligationForest type Node = usize; type Edge = (usize, usize); - fn graph_id(&self) -> dot::Id { + fn graph_id(&self) -> dot::Id<'_> { dot::Id::new("trait_obligation_forest").unwrap() } - fn node_id(&self, index: &Self::Node) -> dot::Id { + fn node_id(&self, index: &Self::Node) -> dot::Id<'_> { dot::Id::new(format!("obligation_{}", index)).unwrap() } - fn node_label(&self, index: &Self::Node) -> dot::LabelText { + fn node_label(&self, index: &Self::Node) -> dot::LabelText<'_> { let node = &self.nodes[*index]; let label = format!("{:?} ({:?})", node.obligation.as_predicate(), node.state.get()); dot::LabelText::LabelStr(label.into()) } - fn edge_label(&self, (_index_source, _index_target): &Self::Edge) -> dot::LabelText { + fn edge_label(&self, (_index_source, _index_target): &Self::Edge) -> dot::LabelText<'_> { dot::LabelText::LabelStr("".into()) } } @@ -65,11 +65,11 @@ impl<'a, O: ForestObligation + 'a> dot::GraphWalk<'a> for &'a ObligationForest dot::Nodes { + fn nodes(&self) -> dot::Nodes<'_, Self::Node> { (0..self.nodes.len()).collect() } - fn edges(&self) -> dot::Edges { + fn edges(&self) -> dot::Edges<'_, Self::Edge> { (0..self.nodes.len()) .flat_map(|i| { let node = &self.nodes[i]; diff --git a/src/librustc_data_structures/obligation_forest/mod.rs b/src/librustc_data_structures/obligation_forest/mod.rs index 9dd7d204f03..546bb64168e 100644 --- a/src/librustc_data_structures/obligation_forest/mod.rs +++ b/src/librustc_data_structures/obligation_forest/mod.rs @@ -80,7 +80,7 @@ //! processing step, we compress the vector to remove completed and error //! nodes, which aren't needed anymore. -use fx::{FxHashMap, FxHashSet}; +use crate::fx::{FxHashMap, FxHashSet}; use std::cell::Cell; use std::collections::hash_map::Entry; @@ -733,7 +733,7 @@ fn new( // I need a Clone closure #[derive(Clone)] -struct GetObligation<'a, O: 'a>(&'a [Node]); +struct GetObligation<'a, O>(&'a [Node]); impl<'a, 'b, O> FnOnce<(&'b usize,)> for GetObligation<'a, O> { type Output = &'a O; diff --git a/src/librustc_data_structures/owning_ref/mod.rs b/src/librustc_data_structures/owning_ref/mod.rs index 0b126e5c572..30e510cc5b0 100644 --- a/src/librustc_data_structures/owning_ref/mod.rs +++ b/src/librustc_data_structures/owning_ref/mod.rs @@ -1002,7 +1002,7 @@ impl Debug for OwningRef where O: Debug, T: Debug, { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "OwningRef {{ owner: {:?}, reference: {:?} }}", self.owner(), @@ -1014,7 +1014,7 @@ impl Debug for OwningRefMut where O: Debug, T: Debug, { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "OwningRefMut {{ owner: {:?}, reference: {:?} }}", self.owner(), @@ -1047,7 +1047,7 @@ unsafe impl Sync for OwningRefMut where O: Sync, for<'a> (&'a mut T): Sync {} impl Debug for dyn Erased { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "",) } } diff --git a/src/librustc_data_structures/ptr_key.rs b/src/librustc_data_structures/ptr_key.rs index 322dcbe8f08..bf3ae2d7af5 100644 --- a/src/librustc_data_structures/ptr_key.rs +++ b/src/librustc_data_structures/ptr_key.rs @@ -4,7 +4,7 @@ /// A wrapper around reference that compares and hashes like a pointer. /// Can be used as a key in sets/maps indexed by pointers to avoid `unsafe`. #[derive(Debug)] -pub struct PtrKey<'a, T: 'a>(pub &'a T); +pub struct PtrKey<'a, T>(pub &'a T); impl<'a, T> Clone for PtrKey<'a, T> { fn clone(&self) -> Self { *self } diff --git a/src/librustc_data_structures/snapshot_map/mod.rs b/src/librustc_data_structures/snapshot_map/mod.rs index d408727aea5..91d6e292370 100644 --- a/src/librustc_data_structures/snapshot_map/mod.rs +++ b/src/librustc_data_structures/snapshot_map/mod.rs @@ -1,4 +1,4 @@ -use fx::FxHashMap; +use crate::fx::FxHashMap; use std::hash::Hash; use std::ops; use std::mem; diff --git a/src/librustc_data_structures/sorted_map.rs b/src/librustc_data_structures/sorted_map.rs index 64bbb8d7c08..1f674c1c664 100644 --- a/src/librustc_data_structures/sorted_map.rs +++ b/src/librustc_data_structures/sorted_map.rs @@ -111,7 +111,7 @@ pub fn clear(&mut self) { /// Iterate over elements, sorted by key #[inline] - pub fn iter(&self) -> ::std::slice::Iter<(K, V)> { + pub fn iter(&self) -> ::std::slice::Iter<'_, (K, V)> { self.data.iter() } diff --git a/src/librustc_data_structures/stable_hasher.rs b/src/librustc_data_structures/stable_hasher.rs index 4583f12ec8c..19343a9250d 100644 --- a/src/librustc_data_structures/stable_hasher.rs +++ b/src/librustc_data_structures/stable_hasher.rs @@ -1,7 +1,9 @@ use std::hash::{Hash, Hasher, BuildHasher}; use std::marker::PhantomData; use std::mem; -use sip128::SipHasher128; +use crate::sip128::SipHasher128; +use crate::indexed_vec; +use crate::bit_set; /// When hashing something that ends up affecting properties like symbol names, /// we want these symbol names to be calculated independently of other factors @@ -17,7 +19,7 @@ pub struct StableHasher { } impl ::std::fmt::Debug for StableHasher { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { write!(f, "{:?}", self.state) } } @@ -433,7 +435,7 @@ fn hash_stable(&self, } } -impl HashStable for ::indexed_vec::IndexVec +impl HashStable for indexed_vec::IndexVec where T: HashStable, { fn hash_stable(&self, @@ -447,7 +449,7 @@ fn hash_stable(&self, } -impl HashStable for ::bit_set::BitSet +impl HashStable for bit_set::BitSet { fn hash_stable(&self, ctx: &mut CTX, diff --git a/src/librustc_data_structures/svh.rs b/src/librustc_data_structures/svh.rs index 74947953497..3757f921098 100644 --- a/src/librustc_data_structures/svh.rs +++ b/src/librustc_data_structures/svh.rs @@ -9,7 +9,7 @@ use std::hash::{Hash, Hasher}; use serialize::{Encodable, Decodable, Encoder, Decoder}; -use stable_hasher; +use crate::stable_hasher; #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct Svh { @@ -40,7 +40,7 @@ fn hash(&self, state: &mut H) where H: Hasher { } impl fmt::Display for Svh { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.pad(&self.to_string()) } } diff --git a/src/librustc_data_structures/sync.rs b/src/librustc_data_structures/sync.rs index 7fef1f374d6..ba1f6eb56fe 100644 --- a/src/librustc_data_structures/sync.rs +++ b/src/librustc_data_structures/sync.rs @@ -21,7 +21,7 @@ use std::hash::{Hash, BuildHasher}; use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; -use owning_ref::{Erased, OwningRef}; +use crate::owning_ref::{Erased, OwningRef}; pub fn serial_join(oper_a: A, oper_b: B) -> (RA, RB) where A: FnOnce() -> RA, @@ -261,12 +261,12 @@ pub fn get_mut(&mut self) -> &mut T { } #[inline(always)] - pub fn lock(&self) -> LockGuard { + pub fn lock(&self) -> LockGuard<'_, T> { self.0.lock() } #[inline(always)] - pub fn lock_mut(&self) -> LockGuard { + pub fn lock_mut(&self) -> LockGuard<'_, T> { self.lock() } } @@ -490,19 +490,19 @@ pub fn get_mut(&mut self) -> &mut T { #[cfg(parallel_compiler)] #[inline(always)] - pub fn try_lock(&self) -> Option> { + pub fn try_lock(&self) -> Option> { self.0.try_lock() } #[cfg(not(parallel_compiler))] #[inline(always)] - pub fn try_lock(&self) -> Option> { + pub fn try_lock(&self) -> Option> { self.0.try_borrow_mut().ok() } #[cfg(parallel_compiler)] #[inline(always)] - pub fn lock(&self) -> LockGuard { + pub fn lock(&self) -> LockGuard<'_, T> { if ERROR_CHECKING { self.0.try_lock().expect("lock was already held") } else { @@ -512,7 +512,7 @@ pub fn lock(&self) -> LockGuard { #[cfg(not(parallel_compiler))] #[inline(always)] - pub fn lock(&self) -> LockGuard { + pub fn lock(&self) -> LockGuard<'_, T> { self.0.borrow_mut() } @@ -522,12 +522,12 @@ pub fn with_lock R, R>(&self, f: F) -> R { } #[inline(always)] - pub fn borrow(&self) -> LockGuard { + pub fn borrow(&self) -> LockGuard<'_, T> { self.lock() } #[inline(always)] - pub fn borrow_mut(&self) -> LockGuard { + pub fn borrow_mut(&self) -> LockGuard<'_, T> { self.lock() } } @@ -568,13 +568,13 @@ pub fn get_mut(&mut self) -> &mut T { #[cfg(not(parallel_compiler))] #[inline(always)] - pub fn read(&self) -> ReadGuard { + pub fn read(&self) -> ReadGuard<'_, T> { self.0.borrow() } #[cfg(parallel_compiler)] #[inline(always)] - pub fn read(&self) -> ReadGuard { + pub fn read(&self) -> ReadGuard<'_, T> { if ERROR_CHECKING { self.0.try_read().expect("lock was already held") } else { @@ -589,25 +589,25 @@ pub fn with_read_lock R, R>(&self, f: F) -> R { #[cfg(not(parallel_compiler))] #[inline(always)] - pub fn try_write(&self) -> Result, ()> { + pub fn try_write(&self) -> Result, ()> { self.0.try_borrow_mut().map_err(|_| ()) } #[cfg(parallel_compiler)] #[inline(always)] - pub fn try_write(&self) -> Result, ()> { + pub fn try_write(&self) -> Result, ()> { self.0.try_write().ok_or(()) } #[cfg(not(parallel_compiler))] #[inline(always)] - pub fn write(&self) -> WriteGuard { + pub fn write(&self) -> WriteGuard<'_, T> { self.0.borrow_mut() } #[cfg(parallel_compiler)] #[inline(always)] - pub fn write(&self) -> WriteGuard { + pub fn write(&self) -> WriteGuard<'_, T> { if ERROR_CHECKING { self.0.try_write().expect("lock was already held") } else { @@ -621,12 +621,12 @@ pub fn with_write_lock R, R>(&self, f: F) -> R { } #[inline(always)] - pub fn borrow(&self) -> ReadGuard { + pub fn borrow(&self) -> ReadGuard<'_, T> { self.read() } #[inline(always)] - pub fn borrow_mut(&self) -> WriteGuard { + pub fn borrow_mut(&self) -> WriteGuard<'_, T> { self.write() } } diff --git a/src/librustc_data_structures/tiny_list.rs b/src/librustc_data_structures/tiny_list.rs index d660486d584..3d74516d9c3 100644 --- a/src/librustc_data_structures/tiny_list.rs +++ b/src/librustc_data_structures/tiny_list.rs @@ -123,7 +123,7 @@ fn contains(&self, data: &T) -> bool { mod test { use super::*; extern crate test; - use self::test::Bencher; + use test::Bencher; #[test] fn test_contains_and_insert() { diff --git a/src/librustc_data_structures/transitive_relation.rs b/src/librustc_data_structures/transitive_relation.rs index 9d675ed3096..39aed983360 100644 --- a/src/librustc_data_structures/transitive_relation.rs +++ b/src/librustc_data_structures/transitive_relation.rs @@ -1,8 +1,8 @@ -use bit_set::BitMatrix; -use fx::FxHashMap; -use sync::Lock; +use crate::bit_set::BitMatrix; +use crate::fx::FxHashMap; +use crate::stable_hasher::{HashStable, StableHasher, StableHasherResult}; +use crate::sync::Lock; use rustc_serialize::{Encodable, Encoder, Decodable, Decoder}; -use stable_hasher::{HashStable, StableHasher, StableHasherResult}; use std::fmt::Debug; use std::hash::Hash; use std::mem; diff --git a/src/librustc_data_structures/vec_linked_list.rs b/src/librustc_data_structures/vec_linked_list.rs index 3b6984dd075..c00c707a435 100644 --- a/src/librustc_data_structures/vec_linked_list.rs +++ b/src/librustc_data_structures/vec_linked_list.rs @@ -1,4 +1,4 @@ -use indexed_vec::{Idx, IndexVec}; +use crate::indexed_vec::{Idx, IndexVec}; pub fn iter( first: Option, diff --git a/src/librustc_data_structures/work_queue.rs b/src/librustc_data_structures/work_queue.rs index 0a928de7961..06418b1051a 100644 --- a/src/librustc_data_structures/work_queue.rs +++ b/src/librustc_data_structures/work_queue.rs @@ -1,5 +1,5 @@ -use bit_set::BitSet; -use indexed_vec::Idx; +use crate::bit_set::BitSet; +use crate::indexed_vec::Idx; use std::collections::VecDeque; /// A work queue is a handy data structure for tracking work left to diff --git a/src/librustc_errors/emitter.rs b/src/librustc_errors/emitter.rs index 061d23697fa..2821201173e 100644 --- a/src/librustc_errors/emitter.rs +++ b/src/librustc_errors/emitter.rs @@ -672,8 +672,8 @@ fn render_source_line(&self, // | | something about `foo` // | something about `fn foo()` annotations_position.sort_by(|a, b| { - // Decreasing order - a.1.len().cmp(&b.1.len()).reverse() + // Decreasing order. When `a` and `b` are the same length, prefer `Primary`. + (a.1.len(), !a.1.is_primary).cmp(&(b.1.len(), !b.1.is_primary)).reverse() }); // Write the underlines. diff --git a/src/librustc_incremental/Cargo.toml b/src/librustc_incremental/Cargo.toml index b8519ee1ab1..10b448b7fec 100644 --- a/src/librustc_incremental/Cargo.toml +++ b/src/librustc_incremental/Cargo.toml @@ -2,6 +2,7 @@ authors = ["The Rust Project Developers"] name = "rustc_incremental" version = "0.0.0" +edition = "2018" [lib] name = "rustc_incremental" diff --git a/src/librustc_incremental/assert_dep_graph.rs b/src/librustc_incremental/assert_dep_graph.rs index 57ab48493fa..b715a32cb05 100644 --- a/src/librustc_incremental/assert_dep_graph.rs +++ b/src/librustc_incremental/assert_dep_graph.rs @@ -217,7 +217,7 @@ fn check_paths<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } } -fn dump_graph(tcx: TyCtxt) { +fn dump_graph(tcx: TyCtxt<'_, '_, '_>) { let path: String = env::var("RUST_DEP_GRAPH").unwrap_or_else(|_| "dep_graph".to_string()); let query = tcx.dep_graph.query(); @@ -261,11 +261,11 @@ pub struct GraphvizDepGraph<'q>(FxHashSet<&'q DepNode>, impl<'a, 'tcx, 'q> dot::GraphWalk<'a> for GraphvizDepGraph<'q> { type Node = &'q DepNode; type Edge = (&'q DepNode, &'q DepNode); - fn nodes(&self) -> dot::Nodes<&'q DepNode> { + fn nodes(&self) -> dot::Nodes<'_, &'q DepNode> { let nodes: Vec<_> = self.0.iter().cloned().collect(); nodes.into() } - fn edges(&self) -> dot::Edges<(&'q DepNode, &'q DepNode)> { + fn edges(&self) -> dot::Edges<'_, (&'q DepNode, &'q DepNode)> { self.1[..].into() } fn source(&self, edge: &(&'q DepNode, &'q DepNode)) -> &'q DepNode { @@ -279,10 +279,10 @@ fn target(&self, edge: &(&'q DepNode, &'q DepNode)) -> &'q DepNode { impl<'a, 'tcx, 'q> dot::Labeller<'a> for GraphvizDepGraph<'q> { type Node = &'q DepNode; type Edge = (&'q DepNode, &'q DepNode); - fn graph_id(&self) -> dot::Id { + fn graph_id(&self) -> dot::Id<'_> { dot::Id::new("DependencyGraph").unwrap() } - fn node_id(&self, n: &&'q DepNode) -> dot::Id { + fn node_id(&self, n: &&'q DepNode) -> dot::Id<'_> { let s: String = format!("{:?}", n).chars() .map(|c| if c == '_' || c.is_alphanumeric() { c } else { '_' }) @@ -290,7 +290,7 @@ fn node_id(&self, n: &&'q DepNode) -> dot::Id { debug!("n={:?} s={:?}", n, s); dot::Id::new(s).unwrap() } - fn node_label(&self, n: &&'q DepNode) -> dot::LabelText { + fn node_label(&self, n: &&'q DepNode) -> dot::LabelText<'_> { dot::LabelText::label(format!("{:?}", n)) } } diff --git a/src/librustc_incremental/lib.rs b/src/librustc_incremental/lib.rs index f69a1cfa3a9..346ddaa4858 100644 --- a/src/librustc_incremental/lib.rs +++ b/src/librustc_incremental/lib.rs @@ -7,16 +7,13 @@ #![recursion_limit="256"] -extern crate graphviz; +#![deny(rust_2018_idioms)] + #[macro_use] extern crate rustc; -extern crate rustc_data_structures; -extern crate serialize as rustc_serialize; -extern crate rand; -extern crate rustc_fs_util; +#[allow(unused_extern_crates)] +extern crate serialize as rustc_serialize; // used by deriving #[macro_use] extern crate log; -extern crate syntax; -extern crate syntax_pos; mod assert_dep_graph; pub mod assert_module_sources; diff --git a/src/librustc_incremental/persist/dirty_clean.rs b/src/librustc_incremental/persist/dirty_clean.rs index 105623e5e4e..51f3bcdf7a5 100644 --- a/src/librustc_incremental/persist/dirty_clean.rs +++ b/src/librustc_incremental/persist/dirty_clean.rs @@ -538,7 +538,7 @@ fn visit_impl_item(&mut self, item: &hir::ImplItem) { /// /// Also make sure that the `label` and `except` fields do not /// both exist. -fn check_config(tcx: TyCtxt, attr: &Attribute) -> bool { +fn check_config(tcx: TyCtxt<'_, '_, '_>, attr: &Attribute) -> bool { debug!("check_config(attr={:?})", attr); let config = &tcx.sess.parse_sess.config; debug!("check_config: config={:?}", config); @@ -573,7 +573,7 @@ fn check_config(tcx: TyCtxt, attr: &Attribute) -> bool { } } -fn expect_associated_value(tcx: TyCtxt, item: &NestedMetaItem) -> ast::Name { +fn expect_associated_value(tcx: TyCtxt<'_, '_, '_>, item: &NestedMetaItem) -> ast::Name { if let Some(value) = item.value_str() { value } else { diff --git a/src/librustc_incremental/persist/load.rs b/src/librustc_incremental/persist/load.rs index f330de71918..ecf8bc4a880 100644 --- a/src/librustc_incremental/persist/load.rs +++ b/src/librustc_incremental/persist/load.rs @@ -9,7 +9,6 @@ use rustc_serialize::Decodable as RustcDecodable; use rustc_serialize::opaque::Decoder; use std::path::Path; -use std; use super::data::*; use super::fs::*; diff --git a/src/librustc_incremental/persist/mod.rs b/src/librustc_incremental/persist/mod.rs index bd59f24d04e..3aad4f5abb8 100644 --- a/src/librustc_incremental/persist/mod.rs +++ b/src/librustc_incremental/persist/mod.rs @@ -10,16 +10,16 @@ mod work_product; mod file_format; -pub use self::fs::finalize_session_directory; -pub use self::fs::garbage_collect_session_directories; -pub use self::fs::in_incr_comp_dir; -pub use self::fs::in_incr_comp_dir_sess; -pub use self::fs::prepare_session_directory; -pub use self::load::dep_graph_tcx_init; -pub use self::load::load_dep_graph; -pub use self::load::load_query_result_cache; -pub use self::load::LoadResult; -pub use self::save::save_dep_graph; -pub use self::save::save_work_product_index; -pub use self::work_product::copy_cgu_workproducts_to_incr_comp_cache_dir; -pub use self::work_product::delete_workproduct_files; +pub use fs::finalize_session_directory; +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_dep_graph; +pub use load::load_query_result_cache; +pub use load::LoadResult; +pub use save::save_dep_graph; +pub use save::save_work_product_index; +pub use work_product::copy_cgu_workproducts_to_incr_comp_cache_dir; +pub use work_product::delete_workproduct_files; diff --git a/src/librustc_incremental/persist/save.rs b/src/librustc_incremental/persist/save.rs index 6a7553b3882..34fe2f1c25d 100644 --- a/src/librustc_incremental/persist/save.rs +++ b/src/librustc_incremental/persist/save.rs @@ -129,7 +129,7 @@ fn save_in(sess: &Session, path_buf: PathBuf, encode: F) } } -fn encode_dep_graph(tcx: TyCtxt, +fn encode_dep_graph(tcx: TyCtxt<'_, '_, '_>, encoder: &mut Encoder) { // First encode the commandline arguments hash tcx.sess.opts.dep_tracking_hash().encode(encoder).unwrap(); @@ -234,7 +234,7 @@ fn encode_work_product_index(work_products: &FxHashMap, encoder: &mut Encoder) { time(tcx.sess, "serialize query result cache", || { tcx.serialize_query_result_cache(encoder).unwrap(); diff --git a/src/librustc_incremental/persist/work_product.rs b/src/librustc_incremental/persist/work_product.rs index 535f6930aa3..3495b27c5eb 100644 --- a/src/librustc_incremental/persist/work_product.rs +++ b/src/librustc_incremental/persist/work_product.rs @@ -1,6 +1,6 @@ //! This module contains files for saving intermediate work-products. -use persist::fs::*; +use crate::persist::fs::*; use rustc::dep_graph::{WorkProduct, WorkProductId, WorkProductFileKind}; use rustc::session::Session; use rustc_fs_util::link_or_copy; diff --git a/src/librustc_lint/Cargo.toml b/src/librustc_lint/Cargo.toml index 7fb7a06ea1a..82f7118df2d 100644 --- a/src/librustc_lint/Cargo.toml +++ b/src/librustc_lint/Cargo.toml @@ -2,6 +2,7 @@ authors = ["The Rust Project Developers"] name = "rustc_lint" version = "0.0.0" +edition = "2018" [lib] name = "rustc_lint" diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs index 7c25d8d8b79..cbcc7f3574d 100644 --- a/src/librustc_lint/builtin.rs +++ b/src/librustc_lint/builtin.rs @@ -21,6 +21,7 @@ use rustc::hir::def::Def; use rustc::hir::def_id::{DefId, LOCAL_CRATE}; use rustc::ty::{self, Ty}; +use rustc::{lint, util}; use hir::Node; use util::nodemap::NodeSet; use lint::{LateContext, LintContext, LintArray}; @@ -42,10 +43,13 @@ use syntax::errors::{Applicability, DiagnosticBuilder}; use syntax::print::pprust::expr_to_string; use syntax::visit::FnKind; +use syntax::struct_span_err; use rustc::hir::{self, GenericParamKind, PatKind}; -use nonstandard_style::{MethodLateContext, method_context}; +use crate::nonstandard_style::{MethodLateContext, method_context}; + +use log::debug; // hardwired lints from librustc pub use lint::builtin::*; @@ -70,7 +74,7 @@ fn get_lints(&self) -> LintArray { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for WhileTrue { - fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) { + fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) { if let hir::ExprKind::While(ref cond, ..) = e.node { if let hir::ExprKind::Lit(ref lit) = cond.node { if let ast::LitKind::Bool(true) = lit.node { @@ -102,7 +106,7 @@ fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) { pub struct BoxPointers; impl BoxPointers { - fn check_heap_type<'a, 'tcx>(&self, cx: &LateContext, span: Span, ty: Ty) { + fn check_heap_type<'a, 'tcx>(&self, cx: &LateContext<'_, '_>, span: Span, ty: Ty<'_>) { for leaf_ty in ty.walk() { if leaf_ty.is_box() { let m = format!("type uses owned (Box type) pointers: {}", ty); @@ -123,7 +127,7 @@ fn get_lints(&self) -> LintArray { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers { - fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) { match it.node { hir::ItemKind::Fn(..) | hir::ItemKind::Ty(..) | @@ -150,7 +154,7 @@ fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { } } - fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) { + fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) { let ty = cx.tables.node_id_to_type(e.hir_id); self.check_heap_type(cx, e.span, ty); } @@ -176,7 +180,7 @@ fn get_lints(&self) -> LintArray { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns { - fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) { + fn check_pat(&mut self, cx: &LateContext<'_, '_>, pat: &hir::Pat) { if let PatKind::Struct(ref qpath, ref field_pats, _) = pat.node { let variant = cx.tables.pat_ty(pat).ty_adt_def() .expect("struct pattern type is not an ADT") @@ -233,7 +237,7 @@ fn get_lints(&self) -> LintArray { } impl UnsafeCode { - fn report_unsafe(&self, cx: &EarlyContext, span: Span, desc: &'static str) { + fn report_unsafe(&self, cx: &EarlyContext<'_>, span: Span, desc: &'static str) { // This comes from a macro that has #[allow_internal_unsafe]. if span.allows_unsafe() { return; @@ -244,7 +248,7 @@ fn report_unsafe(&self, cx: &EarlyContext, span: Span, desc: &'static str) { } impl EarlyLintPass for UnsafeCode { - fn check_attribute(&mut self, cx: &EarlyContext, attr: &ast::Attribute) { + fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) { if attr.check_name("allow_internal_unsafe") { self.report_unsafe(cx, attr.span, "`allow_internal_unsafe` allows defining \ macros using unsafe without triggering \ @@ -252,7 +256,7 @@ fn check_attribute(&mut self, cx: &EarlyContext, attr: &ast::Attribute) { } } - fn check_expr(&mut self, cx: &EarlyContext, e: &ast::Expr) { + fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) { if let ast::ExprKind::Block(ref blk, _) = e.node { // Don't warn about generated blocks, that'll just pollute the output. if blk.rules == ast::BlockCheckMode::Unsafe(ast::UserProvided) { @@ -261,7 +265,7 @@ fn check_expr(&mut self, cx: &EarlyContext, e: &ast::Expr) { } } - fn check_item(&mut self, cx: &EarlyContext, it: &ast::Item) { + fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) { match it.node { ast::ItemKind::Trait(_, ast::Unsafety::Unsafe, ..) => { self.report_unsafe(cx, it.span, "declaration of an `unsafe` trait") @@ -276,8 +280,8 @@ fn check_item(&mut self, cx: &EarlyContext, it: &ast::Item) { } fn check_fn(&mut self, - cx: &EarlyContext, - fk: FnKind, + cx: &EarlyContext<'_>, + fk: FnKind<'_>, _: &ast::FnDecl, span: Span, _: ast::NodeId) { @@ -296,7 +300,7 @@ fn check_fn(&mut self, } } - fn check_trait_item(&mut self, cx: &EarlyContext, item: &ast::TraitItem) { + fn check_trait_item(&mut self, cx: &EarlyContext<'_>, item: &ast::TraitItem) { if let ast::TraitItemKind::Method(ref sig, None) = item.node { if sig.header.unsafety == ast::Unsafety::Unsafe { self.report_unsafe(cx, item.span, "declaration of an `unsafe` method") @@ -354,7 +358,7 @@ fn doc_hidden(&self) -> bool { } fn check_missing_docs_attrs(&self, - cx: &LateContext, + cx: &LateContext<'_, '_>, id: Option, attrs: &[ast::Attribute], sp: Span, @@ -399,7 +403,7 @@ fn get_lints(&self) -> LintArray { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc { - fn enter_lint_attrs(&mut self, _: &LateContext, attrs: &[ast::Attribute]) { + fn enter_lint_attrs(&mut self, _: &LateContext<'_, '_>, attrs: &[ast::Attribute]) { let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| { attr.check_name("doc") && @@ -411,11 +415,11 @@ fn enter_lint_attrs(&mut self, _: &LateContext, attrs: &[ast::Attribute]) { self.doc_hidden_stack.push(doc_hidden); } - fn exit_lint_attrs(&mut self, _: &LateContext, _attrs: &[ast::Attribute]) { + fn exit_lint_attrs(&mut self, _: &LateContext<'_, '_>, _attrs: &[ast::Attribute]) { self.doc_hidden_stack.pop().expect("empty doc_hidden_stack"); } - fn check_crate(&mut self, cx: &LateContext, krate: &hir::Crate) { + fn check_crate(&mut self, cx: &LateContext<'_, '_>, krate: &hir::Crate) { self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate"); for macro_def in &krate.exported_macros { @@ -428,7 +432,7 @@ fn check_crate(&mut self, cx: &LateContext, krate: &hir::Crate) { } } - fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) { let desc = match it.node { hir::ItemKind::Fn(..) => "a function", hir::ItemKind::Mod(..) => "a module", @@ -473,7 +477,7 @@ fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc); } - fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) { + fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, trait_item: &hir::TraitItem) { if self.private_traits.contains(&trait_item.id) { return; } @@ -491,7 +495,7 @@ fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) { desc); } - fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) { + fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem) { // If the method is an impl for a trait, don't doc. if method_context(cx, impl_item.id) == MethodLateContext::TraitImpl { return; @@ -510,7 +514,7 @@ fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) { desc); } - fn check_struct_field(&mut self, cx: &LateContext, sf: &hir::StructField) { + fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, sf: &hir::StructField) { if !sf.is_positional() { self.check_missing_docs_attrs(cx, Some(sf.id), @@ -520,7 +524,7 @@ fn check_struct_field(&mut self, cx: &LateContext, sf: &hir::StructField) { } } - fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) { + fn check_variant(&mut self, cx: &LateContext<'_, '_>, v: &hir::Variant, _: &hir::Generics) { self.check_missing_docs_attrs(cx, Some(v.node.data.id()), &v.node.attrs, @@ -549,7 +553,7 @@ fn get_lints(&self) -> LintArray { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations { - fn check_item(&mut self, cx: &LateContext, item: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) { if !cx.access_levels.is_reachable(item.id) { return; } @@ -620,7 +624,7 @@ fn get_lints(&self) -> LintArray { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations { - fn check_item(&mut self, cx: &LateContext, item: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) { if !cx.access_levels.is_reachable(item.id) { return; } @@ -681,7 +685,7 @@ fn get_lints(&self) -> LintArray { } impl EarlyLintPass for AnonymousParameters { - fn check_trait_item(&mut self, cx: &EarlyContext, it: &ast::TraitItem) { + fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::TraitItem) { match it.node { ast::TraitItemKind::Method(ref sig, _) => { for arg in sig.decl.inputs.iter() { @@ -749,7 +753,7 @@ fn get_lints(&self) -> LintArray { } impl EarlyLintPass for DeprecatedAttr { - fn check_attribute(&mut self, cx: &EarlyContext, attr: &ast::Attribute) { + fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) { for &&(n, _, _, ref g) in &self.depr_attrs { if attr.name() == n { if let &AttributeGate::Gated(Stability::Deprecated(link, suggestion), @@ -804,15 +808,15 @@ fn warn_if_doc<'a, 'tcx, } impl EarlyLintPass for UnusedDocComment { - fn check_local(&mut self, cx: &EarlyContext, decl: &ast::Local) { + fn check_local(&mut self, cx: &EarlyContext<'_>, decl: &ast::Local) { self.warn_if_doc(decl.attrs.iter(), cx); } - fn check_arm(&mut self, cx: &EarlyContext, arm: &ast::Arm) { + fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) { self.warn_if_doc(arm.attrs.iter(), cx); } - fn check_expr(&mut self, cx: &EarlyContext, expr: &ast::Expr) { + fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) { self.warn_if_doc(expr.attrs.iter(), cx); } } @@ -837,7 +841,7 @@ fn get_lints(&self) -> LintArray { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary { - fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) { if cx.tcx.plugin_registrar_fn(LOCAL_CRATE).is_some() { // We're compiling a plugin; it's fine to link other plugins. return; @@ -894,7 +898,7 @@ fn get_lints(&self) -> LintArray { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems { - fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) { match it.node { hir::ItemKind::Fn(.., ref generics, _) => { if let Some(no_mangle_attr) = attr::find_by_name(&it.attrs, "no_mangle") { @@ -968,7 +972,7 @@ fn get_lints(&self) -> LintArray { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes { - fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) { + fn check_expr(&mut self, cx: &LateContext<'_, '_>, expr: &hir::Expr) { use rustc_target::spec::abi::Abi::RustIntrinsic; let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \ @@ -1004,7 +1008,7 @@ fn get_transmute_from_to<'a, 'tcx> None } - fn def_id_is_transmute(cx: &LateContext, def_id: DefId) -> bool { + fn def_id_is_transmute(cx: &LateContext<'_, '_>, def_id: DefId) -> bool { cx.tcx.fn_sig(def_id).abi() == RustIntrinsic && cx.tcx.item_name(def_id) == "transmute" } @@ -1032,7 +1036,7 @@ fn get_lints(&self) -> LintArray { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures { - fn check_attribute(&mut self, ctx: &LateContext, attr: &ast::Attribute) { + fn check_attribute(&mut self, ctx: &LateContext<'_, '_>, attr: &ast::Attribute) { if attr.check_name("feature") { if let Some(items) = attr.meta_item_list() { for item in items { @@ -1063,7 +1067,7 @@ fn get_lints(&self) -> LintArray { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields { - fn check_item(&mut self, ctx: &LateContext, item: &hir::Item) { + fn check_item(&mut self, ctx: &LateContext<'_, '_>, item: &hir::Item) { if let hir::ItemKind::Union(ref vdata, _) = item.node { for field in vdata.fields() { let field_ty = ctx.tcx.type_of(ctx.tcx.hir().local_def_id(field.id)); @@ -1099,7 +1103,7 @@ fn get_lints(&self) -> LintArray { } impl UnreachablePub { - fn perform_lint(&self, cx: &LateContext, what: &str, id: ast::NodeId, + fn perform_lint(&self, cx: &LateContext<'_, '_>, what: &str, id: ast::NodeId, vis: &hir::Visibility, span: Span, exportable: bool) { let mut applicability = Applicability::MachineApplicable; match vis.node { @@ -1134,20 +1138,20 @@ fn perform_lint(&self, cx: &LateContext, what: &str, id: ast::NodeId, impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnreachablePub { - fn check_item(&mut self, cx: &LateContext, item: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) { self.perform_lint(cx, "item", item.id, &item.vis, item.span, true); } - fn check_foreign_item(&mut self, cx: &LateContext, foreign_item: &hir::ForeignItem) { + fn check_foreign_item(&mut self, cx: &LateContext<'_, '_>, foreign_item: &hir::ForeignItem) { self.perform_lint(cx, "item", foreign_item.id, &foreign_item.vis, foreign_item.span, true); } - fn check_struct_field(&mut self, cx: &LateContext, field: &hir::StructField) { + fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, field: &hir::StructField) { self.perform_lint(cx, "field", field.id, &field.vis, field.span, false); } - fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) { + fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem) { self.perform_lint(cx, "item", impl_item.id, &impl_item.vis, impl_item.span, false); } } @@ -1193,7 +1197,7 @@ fn is_type_variable_assoc(qpath: &hir::QPath) -> bool { } } - fn suggest_changing_assoc_types(ty: &hir::Ty, err: &mut DiagnosticBuilder) { + fn suggest_changing_assoc_types(ty: &hir::Ty, err: &mut DiagnosticBuilder<'_>) { // Access to associates types should use `::Assoc`, which does not need a // bound. Let's see if this type does that. @@ -1225,7 +1229,7 @@ fn visit_qpath(&mut self, qpath: &'v hir::QPath, id: hir::HirId, span: Span) { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeAliasBounds { - fn check_item(&mut self, cx: &LateContext, item: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) { let (ty, type_alias_generics) = match item.node { hir::ItemKind::Ty(ref ty, ref generics) => (&*ty, generics), _ => return, @@ -1281,7 +1285,7 @@ fn get_lints(&self) -> LintArray { lint_array!() } } -fn check_const(cx: &LateContext, body_id: hir::BodyId) { +fn check_const(cx: &LateContext<'_, '_>, body_id: hir::BodyId) { let def_id = cx.tcx.hir().body_owner_def_id(body_id); let is_static = cx.tcx.is_static(def_id).is_some(); let param_env = if is_static { @@ -1299,7 +1303,7 @@ fn check_const(cx: &LateContext, body_id: hir::BodyId) { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedBrokenConst { - fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) { match it.node { hir::ItemKind::Const(_, body_id) => { check_const(cx, body_id); @@ -1429,7 +1433,7 @@ fn get_lints(&self) -> LintArray { } impl EarlyLintPass for EllipsisInclusiveRangePatterns { - fn check_pat(&mut self, cx: &EarlyContext, pat: &ast::Pat, visit_subpats: &mut bool) { + fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat, visit_subpats: &mut bool) { use self::ast::{PatKind, RangeEnd, RangeSyntax::DotDotDot}; /// If `pat` is a `...` pattern, return the start and end of the range, as well as the span @@ -1507,7 +1511,7 @@ fn get_lints(&self) -> LintArray { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnnameableTestItems { - fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) { if self.items_nameable { if let hir::ItemKind::Mod(..) = it.node {} else { @@ -1526,7 +1530,7 @@ fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { } } - fn check_item_post(&mut self, _cx: &LateContext, it: &hir::Item) { + fn check_item_post(&mut self, _cx: &LateContext<'_, '_>, it: &hir::Item) { if !self.items_nameable && self.boundary == it.id { self.items_nameable = true; } @@ -1554,7 +1558,7 @@ fn get_lints(&self) -> LintArray { } impl KeywordIdents { - fn check_tokens(&mut self, cx: &EarlyContext, tokens: TokenStream) { + fn check_tokens(&mut self, cx: &EarlyContext<'_>, tokens: TokenStream) { for tt in tokens.into_trees() { match tt { TokenTree::Token(span, tok) => match tok.ident() { @@ -1576,13 +1580,13 @@ fn check_tokens(&mut self, cx: &EarlyContext, tokens: TokenStream) { } impl EarlyLintPass for KeywordIdents { - fn check_mac_def(&mut self, cx: &EarlyContext, mac_def: &ast::MacroDef, _id: ast::NodeId) { + fn check_mac_def(&mut self, cx: &EarlyContext<'_>, mac_def: &ast::MacroDef, _id: ast::NodeId) { self.check_tokens(cx, mac_def.stream()); } - fn check_mac(&mut self, cx: &EarlyContext, mac: &ast::Mac) { + fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::Mac) { self.check_tokens(cx, mac.node.tts.clone().into()); } - fn check_ident(&mut self, cx: &EarlyContext, ident: ast::Ident) { + fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: ast::Ident) { let ident_str = &ident.as_str()[..]; let cur_edition = cx.sess.edition(); let is_raw_ident = |ident: ast::Ident| { @@ -1665,7 +1669,7 @@ fn get_lints(&self) -> LintArray { impl ExplicitOutlivesRequirements { fn collect_outlives_bound_spans( &self, - cx: &LateContext, + cx: &LateContext<'_, '_>, item_def_id: DefId, param_name: &str, bounds: &hir::GenericBounds, diff --git a/src/librustc_lint/diagnostics.rs b/src/librustc_lint/diagnostics.rs index 9a608e4fef0..3165673111c 100644 --- a/src/librustc_lint/diagnostics.rs +++ b/src/librustc_lint/diagnostics.rs @@ -1,3 +1,5 @@ +use syntax::{register_diagnostic, register_diagnostics}; + register_diagnostics! { E0721, // `await` keyword } diff --git a/src/librustc_lint/lib.rs b/src/librustc_lint/lib.rs index fd5e68d5ae6..5c243e13890 100644 --- a/src/librustc_lint/lib.rs +++ b/src/librustc_lint/lib.rs @@ -19,15 +19,10 @@ #![recursion_limit="256"] -#[macro_use] -extern crate syntax; +#![deny(rust_2018_idioms)] + #[macro_use] extern crate rustc; -#[macro_use] -extern crate log; -extern crate rustc_target; -extern crate syntax_pos; -extern crate rustc_data_structures; mod diagnostics; mod nonstandard_style; @@ -49,7 +44,6 @@ parser::ILL_FORMED_ATTRIBUTE_INPUT, }; use rustc::session; -use rustc::util; use rustc::hir; use syntax::ast; @@ -354,6 +348,11 @@ macro_rules! register_passes { reference: "issue #57644 ", edition: None, }, + FutureIncompatibleInfo { + id: LintId::of(DUPLICATE_MATCHER_BINDING_NAME), + reference: "issue #57593 ", + edition: None, + }, ]); // Register renamed and removed lints. diff --git a/src/librustc_lint/nonstandard_style.rs b/src/librustc_lint/nonstandard_style.rs index ae2ed28104e..2dbafc7ede2 100644 --- a/src/librustc_lint/nonstandard_style.rs +++ b/src/librustc_lint/nonstandard_style.rs @@ -1,6 +1,7 @@ use rustc::hir::{self, GenericParamKind, PatKind}; use rustc::hir::def::Def; use rustc::hir::intravisit::FnKind; +use rustc::lint; use rustc::ty; use rustc_target::spec::abi::Abi; use lint::{EarlyContext, LateContext, LintContext, LintArray}; @@ -17,7 +18,7 @@ pub enum MethodLateContext { PlainImpl, } -pub fn method_context(cx: &LateContext, id: ast::NodeId) -> MethodLateContext { +pub fn method_context(cx: &LateContext<'_, '_>, id: ast::NodeId) -> MethodLateContext { let def_id = cx.tcx.hir().local_def_id(id); let item = cx.tcx.associated_item(def_id); match item.container { @@ -41,7 +42,7 @@ pub fn method_context(cx: &LateContext, id: ast::NodeId) -> MethodLateContext { pub struct NonCamelCaseTypes; impl NonCamelCaseTypes { - fn check_case(&self, cx: &EarlyContext, sort: &str, ident: &Ident) { + fn check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident) { fn char_has_case(c: char) -> bool { c.is_lowercase() || c.is_uppercase() } @@ -115,7 +116,7 @@ fn get_lints(&self) -> LintArray { } impl EarlyLintPass for NonCamelCaseTypes { - fn check_item(&mut self, cx: &EarlyContext, it: &ast::Item) { + fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) { let has_repr_c = it.attrs .iter() .any(|attr| { @@ -138,11 +139,11 @@ fn check_item(&mut self, cx: &EarlyContext, it: &ast::Item) { } } - fn check_variant(&mut self, cx: &EarlyContext, v: &ast::Variant, _: &ast::Generics) { + fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant, _: &ast::Generics) { self.check_case(cx, "variant", &v.node.ident); } - fn check_generic_param(&mut self, cx: &EarlyContext, param: &ast::GenericParam) { + fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) { if let ast::GenericParamKind::Type { .. } = param.kind { self.check_case(cx, "type parameter", ¶m.ident); } @@ -190,7 +191,7 @@ fn to_snake_case(mut str: &str) -> String { } /// Checks if a given identifier is snake case, and reports a diagnostic if not. - fn check_snake_case(&self, cx: &LateContext, sort: &str, ident: &Ident) { + fn check_snake_case(&self, cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) { fn is_snake_case(ident: &str) -> bool { if ident.is_empty() { return true; @@ -249,7 +250,7 @@ fn get_lints(&self) -> LintArray { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase { - fn check_crate(&mut self, cx: &LateContext, cr: &hir::Crate) { + fn check_crate(&mut self, cx: &LateContext<'_, '_>, cr: &hir::Crate) { let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name { Some(Ident::from_str(name)) } else { @@ -286,7 +287,7 @@ fn check_crate(&mut self, cx: &LateContext, cr: &hir::Crate) { } } - fn check_generic_param(&mut self, cx: &LateContext, param: &hir::GenericParam) { + fn check_generic_param(&mut self, cx: &LateContext<'_, '_>, param: &hir::GenericParam) { if let GenericParamKind::Lifetime { .. } = param.kind { self.check_snake_case(cx, "lifetime", ¶m.name.ident()); } @@ -294,8 +295,8 @@ fn check_generic_param(&mut self, cx: &LateContext, param: &hir::GenericParam) { fn check_fn( &mut self, - cx: &LateContext, - fk: FnKind, + cx: &LateContext<'_, '_>, + fk: FnKind<'_>, _: &hir::FnDecl, _: &hir::Body, _: Span, @@ -324,13 +325,13 @@ fn check_fn( } } - fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) { if let hir::ItemKind::Mod(_) = it.node { self.check_snake_case(cx, "module", &it.ident); } } - fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) { + fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::TraitItem) { if let hir::TraitItemKind::Method(_, hir::TraitMethod::Required(pnames)) = &item.node { self.check_snake_case(cx, "trait method", &item.ident); for param_name in pnames { @@ -339,7 +340,7 @@ fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) { } } - fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) { + fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat) { if let &PatKind::Binding(_, _, _, ident, _) = &p.node { self.check_snake_case(cx, "variable", &ident); } @@ -347,7 +348,7 @@ fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) { fn check_struct_def( &mut self, - cx: &LateContext, + cx: &LateContext<'_, '_>, s: &hir::VariantData, _: ast::Name, _: &hir::Generics, @@ -369,7 +370,7 @@ fn check_struct_def( pub struct NonUpperCaseGlobals; impl NonUpperCaseGlobals { - fn check_upper_case(cx: &LateContext, sort: &str, ident: &Ident) { + fn check_upper_case(cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) { let name = &ident.name.as_str(); if name.chars().any(|c| c.is_lowercase()) { @@ -399,7 +400,7 @@ fn get_lints(&self) -> LintArray { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals { - fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) { match it.node { hir::ItemKind::Static(..) if !attr::contains_name(&it.attrs, "no_mangle") => { NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident); @@ -411,19 +412,19 @@ fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { } } - fn check_trait_item(&mut self, cx: &LateContext, ti: &hir::TraitItem) { + fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, ti: &hir::TraitItem) { if let hir::TraitItemKind::Const(..) = ti.node { NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident); } } - fn check_impl_item(&mut self, cx: &LateContext, ii: &hir::ImplItem) { + fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, ii: &hir::ImplItem) { if let hir::ImplItemKind::Const(..) = ii.node { NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident); } } - fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) { + fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat) { // Lint for constants that look like binding identifiers (#7526) if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.node { if let Def::Const(..) = path.def { diff --git a/src/librustc_lint/types.rs b/src/librustc_lint/types.rs index 4abd55b7e31..f6b7ccfe2ec 100644 --- a/src/librustc_lint/types.rs +++ b/src/librustc_lint/types.rs @@ -4,6 +4,7 @@ use rustc::ty::subst::Substs; use rustc::ty::{self, AdtKind, ParamEnv, Ty, TyCtxt}; use rustc::ty::layout::{self, IntegerExt, LayoutOf, VariantIdx}; +use rustc::{lint, util}; use rustc_data_structures::indexed_vec::Idx; use util::nodemap::FxHashSet; use lint::{LateContext, LintContext, LintArray}; @@ -23,6 +24,8 @@ use rustc::mir::interpret::{sign_extend, truncate}; +use log::debug; + declare_lint! { UNUSED_COMPARISONS, Warn, @@ -241,7 +244,7 @@ fn uint_ty_range(uint_ty: ast::UintTy) -> (u128, u128) { } } - fn check_limits(cx: &LateContext, + fn check_limits(cx: &LateContext<'_, '_>, binop: hir::BinOp, l: &hir::Expr, r: &hir::Expr) @@ -298,7 +301,7 @@ fn is_comparison(binop: hir::BinOp) -> bool { } } - fn get_bin_hex_repr(cx: &LateContext, lit: &ast::Lit) -> Option { + fn get_bin_hex_repr(cx: &LateContext<'_, '_>, lit: &ast::Lit) -> Option { let src = cx.sess().source_map().span_to_snippet(lit.span).ok()?; let firstch = src.chars().next()?; @@ -320,7 +323,7 @@ fn get_bin_hex_repr(cx: &LateContext, lit: &ast::Lit) -> Option { // // No suggestion for: `isize`, `usize`. fn get_type_suggestion<'a>( - t: &ty::TyKind, + t: &ty::TyKind<'_>, val: u128, negative: bool, ) -> Option { @@ -364,9 +367,9 @@ macro_rules! find_fit { } fn report_bin_hex_error( - cx: &LateContext, + cx: &LateContext<'_, '_>, expr: &hir::Expr, - ty: ty::TyKind, + ty: ty::TyKind<'_>, repr_str: String, val: u128, negative: bool, @@ -481,7 +484,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { fn check_type_for_ffi(&self, cache: &mut FxHashSet>, ty: Ty<'tcx>) -> FfiResult<'tcx> { - use self::FfiResult::*; + use FfiResult::*; let cx = self.cx.tcx; @@ -799,7 +802,7 @@ fn get_lints(&self) -> LintArray { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImproperCTypes { - fn check_foreign_item(&mut self, cx: &LateContext, it: &hir::ForeignItem) { + fn check_foreign_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::ForeignItem) { let mut vis = ImproperCTypesVisitor { cx }; let abi = cx.tcx.hir().get_foreign_abi(it.id); if abi != Abi::RustIntrinsic && abi != Abi::PlatformIntrinsic { @@ -829,7 +832,7 @@ fn get_lints(&self) -> LintArray { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for VariantSizeDifferences { - fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) { if let hir::ItemKind::Enum(ref enum_definition, _) = it.node { let item_def_id = cx.tcx.hir().local_def_id(it.id); let t = cx.tcx.type_of(item_def_id); diff --git a/src/librustc_lint/unused.rs b/src/librustc_lint/unused.rs index acf5da1e188..407e6842935 100644 --- a/src/librustc_lint/unused.rs +++ b/src/librustc_lint/unused.rs @@ -1,5 +1,6 @@ use rustc::hir::def::Def; use rustc::hir::def_id::DefId; +use rustc::lint; use rustc::ty; use rustc::ty::adjustment; use lint::{LateContext, EarlyContext, LintContext, LintArray}; @@ -16,6 +17,8 @@ use rustc::hir; +use log::debug; + declare_lint! { pub UNUSED_MUST_USE, Warn, @@ -43,7 +46,7 @@ fn get_lints(&self) -> LintArray { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedResults { - fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) { + fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt) { let expr = match s.node { hir::StmtKind::Semi(ref expr) => &**expr, _ => return, @@ -168,7 +171,7 @@ fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) { } fn check_must_use( - cx: &LateContext, + cx: &LateContext<'_, '_>, def_id: DefId, sp: Span, descr_pre_path: &str, @@ -212,7 +215,7 @@ fn get_lints(&self) -> LintArray { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PathStatements { - fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) { + fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt) { if let hir::StmtKind::Semi(ref expr) = s.node { if let hir::ExprKind::Path(_) = expr.node { cx.span_lint(PATH_STATEMENTS, s.span, "path statement with no effect"); @@ -241,7 +244,7 @@ fn get_lints(&self) -> LintArray { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAttributes { - fn check_attribute(&mut self, cx: &LateContext, attr: &ast::Attribute) { + fn check_attribute(&mut self, cx: &LateContext<'_, '_>, attr: &ast::Attribute) { debug!("checking attribute: {:?}", attr); // Note that check_name() marks the attribute as used if it matches. for &(name, ty, ..) in BUILTIN_ATTRIBUTES { @@ -303,7 +306,7 @@ fn check_attribute(&mut self, cx: &LateContext, attr: &ast::Attribute) { impl UnusedParens { fn check_unused_parens_expr(&self, - cx: &EarlyContext, + cx: &EarlyContext<'_>, value: &ast::Expr, msg: &str, followed_by_block: bool) { @@ -325,7 +328,7 @@ fn check_unused_parens_expr(&self, } fn check_unused_parens_pat(&self, - cx: &EarlyContext, + cx: &EarlyContext<'_>, value: &ast::Pat, msg: &str) { if let ast::PatKind::Paren(_) = value.node { @@ -339,7 +342,7 @@ fn check_unused_parens_pat(&self, } } - fn remove_outer_parens(cx: &EarlyContext, span: Span, pattern: &str, msg: &str) { + fn remove_outer_parens(cx: &EarlyContext<'_>, span: Span, pattern: &str, msg: &str) { let span_msg = format!("unnecessary parentheses around {}", msg); let mut err = cx.struct_span_lint(UNUSED_PARENS, span, &span_msg); let mut ate_left_paren = false; @@ -387,7 +390,7 @@ fn get_lints(&self) -> LintArray { } impl EarlyLintPass for UnusedParens { - fn check_expr(&mut self, cx: &EarlyContext, e: &ast::Expr) { + fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) { use syntax::ast::ExprKind::*; let (value, msg, followed_by_block) = match e.node { If(ref cond, ..) => (cond, "`if` condition", true), @@ -429,7 +432,7 @@ fn check_expr(&mut self, cx: &EarlyContext, e: &ast::Expr) { self.check_unused_parens_expr(cx, &value, msg, followed_by_block); } - fn check_pat(&mut self, cx: &EarlyContext, p: &ast::Pat, _: &mut bool) { + fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat, _: &mut bool) { use ast::PatKind::{Paren, Range}; // The lint visitor will visit each subpattern of `p`. We do not want to lint any range // pattern no matter where it occurs in the pattern. For something like `&(a..=b)`, there @@ -443,7 +446,7 @@ fn check_pat(&mut self, cx: &EarlyContext, p: &ast::Pat, _: &mut bool) { } } - fn check_stmt(&mut self, cx: &EarlyContext, s: &ast::Stmt) { + fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) { if let ast::StmtKind::Local(ref local) = s.node { if let Some(ref value) = local.init { self.check_unused_parens_expr(cx, &value, "assigned value", false); @@ -462,7 +465,7 @@ fn check_stmt(&mut self, cx: &EarlyContext, s: &ast::Stmt) { pub struct UnusedImportBraces; impl UnusedImportBraces { - fn check_use_tree(&self, cx: &EarlyContext, use_tree: &ast::UseTree, item: &ast::Item) { + fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) { if let ast::UseTreeKind::Nested(ref items) = use_tree.kind { // Recursively check nested UseTrees for &(ref tree, _) in items { @@ -509,7 +512,7 @@ fn get_lints(&self) -> LintArray { } impl EarlyLintPass for UnusedImportBraces { - fn check_item(&mut self, cx: &EarlyContext, item: &ast::Item) { + fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) { if let ast::ItemKind::Use(ref use_tree) = item.node { self.check_use_tree(cx, use_tree, item); } @@ -536,7 +539,7 @@ fn get_lints(&self) -> LintArray { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation { - fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) { + fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) { match e.node { hir::ExprKind::Box(_) => {} _ => return, diff --git a/src/librustc_metadata/Cargo.toml b/src/librustc_metadata/Cargo.toml index 337c87c24ba..e234f4f8807 100644 --- a/src/librustc_metadata/Cargo.toml +++ b/src/librustc_metadata/Cargo.toml @@ -2,6 +2,7 @@ authors = ["The Rust Project Developers"] name = "rustc_metadata" version = "0.0.0" +edition = "2018" [lib] name = "rustc_metadata" @@ -14,7 +15,7 @@ log = "0.4" memmap = "0.6" rustc = { path = "../librustc" } rustc_data_structures = { path = "../librustc_data_structures" } -rustc_errors = { path = "../librustc_errors" } +errors = { path = "../librustc_errors", package = "rustc_errors" } rustc_target = { path = "../librustc_target" } serialize = { path = "../libserialize" } stable_deref_trait = "1.0.0" diff --git a/src/librustc_metadata/creader.rs b/src/librustc_metadata/creader.rs index e9785e7c88d..0b4c8a5367c 100644 --- a/src/librustc_metadata/creader.rs +++ b/src/librustc_metadata/creader.rs @@ -1,9 +1,9 @@ //! Validates all used crates and extern libraries and loads their metadata -use cstore::{self, CStore, CrateSource, MetadataBlob}; -use locator::{self, CratePaths}; -use decoder::proc_macro_def_path_table; -use schema::CrateRoot; +use crate::cstore::{self, CStore, CrateSource, MetadataBlob}; +use crate::locator::{self, CratePaths}; +use crate::decoder::proc_macro_def_path_table; +use crate::schema::CrateRoot; use rustc_data_structures::sync::{Lrc, RwLock, Lock}; use rustc::hir::def_id::CrateNum; @@ -29,8 +29,9 @@ use syntax::ext::base::SyntaxExtension; use syntax::symbol::Symbol; use syntax::visit; +use syntax::{span_err, span_fatal}; use syntax_pos::{Span, DUMMY_SP}; -use log; +use log::{debug, info, log_enabled}; pub struct Library { pub dylib: Option<(PathBuf, PathKind)>, @@ -342,7 +343,7 @@ fn resolve_crate<'b>( } } - fn load(&mut self, locate_ctxt: &mut locator::Context) -> Option { + fn load(&mut self, locate_ctxt: &mut locator::Context<'_>) -> Option { let library = locate_ctxt.maybe_load_library_crate()?; // In the case that we're loading a crate, but not matching @@ -427,7 +428,7 @@ fn resolve_crate_deps(&mut self, // The map from crate numbers in the crate we're resolving to local crate numbers. // We map 0 and all other holes in the map to our parent crate. The "additional" // self-dependencies should be harmless. - ::std::iter::once(krate).chain(crate_root.crate_deps + std::iter::once(krate).chain(crate_root.crate_deps .decode(metadata) .map(|dep| { info!("resolving dep crate {} hash: `{}` extra filename: `{}`", dep.name, dep.hash, @@ -522,7 +523,7 @@ fn read_extension_crate(&mut self, span: Span, orig_name: Symbol, rename: Symbol fn load_derive_macros(&mut self, root: &CrateRoot, dylib: Option, span: Span) -> Vec<(ast::Name, Lrc)> { use std::{env, mem}; - use dynamic_lib::DynamicLibrary; + use crate::dynamic_lib::DynamicLibrary; use proc_macro::bridge::client::ProcMacro; use syntax_ext::deriving::custom::ProcMacroDerive; use syntax_ext::proc_macro_impl::{AttrProcMacro, BangProcMacro}; @@ -996,7 +997,7 @@ pub fn process_extern_crate( item.ident, orig_name); let orig_name = match orig_name { Some(orig_name) => { - ::validate_crate_name(Some(self.sess), &orig_name.as_str(), + crate::validate_crate_name(Some(self.sess), &orig_name.as_str(), Some(item.span)); orig_name } diff --git a/src/librustc_metadata/cstore.rs b/src/librustc_metadata/cstore.rs index 543fb5d5df5..a2f69bc4563 100644 --- a/src/librustc_metadata/cstore.rs +++ b/src/librustc_metadata/cstore.rs @@ -1,7 +1,7 @@ // The crate store - a central repo for information collected about external // crates and libraries -use schema; +use crate::schema; use rustc::hir::def_id::{CrateNum, DefIndex}; use rustc::hir::map::definitions::DefPathTable; use rustc::middle::cstore::{DepKind, ExternCrate, MetadataLoader}; @@ -19,7 +19,7 @@ pub use rustc::middle::cstore::NativeLibraryKind::*; pub use rustc::middle::cstore::{CrateSource, LibSource, ForeignModule}; -pub use cstore_impl::{provide, provide_extern}; +pub use crate::cstore_impl::{provide, provide_extern}; // A map from external crate numbers (as decoded from some crate file) to // local crate numbers (as generated during this session). Each external diff --git a/src/librustc_metadata/cstore_impl.rs b/src/librustc_metadata/cstore_impl.rs index e61229db86d..b248c6bf656 100644 --- a/src/librustc_metadata/cstore_impl.rs +++ b/src/librustc_metadata/cstore_impl.rs @@ -1,9 +1,9 @@ -use cstore::{self, LoadedMacro}; -use encoder; -use link_args; -use native_libs; -use foreign_modules; -use schema; +use crate::cstore::{self, LoadedMacro}; +use crate::encoder; +use crate::link_args; +use crate::native_libs; +use crate::foreign_modules; +use crate::schema; use rustc::ty::query::QueryConfig; use rustc::middle::cstore::{CrateStore, DepKind, @@ -29,6 +29,7 @@ use syntax::source_map; use syntax::edition::Edition; use syntax::parse::source_file_to_stream; +use syntax::parse::parser::emit_unclosed_delims; use syntax::symbol::Symbol; use syntax_pos::{Span, NO_EXPANSION, FileName}; use rustc_data_structures::bit_set::BitSet; @@ -51,7 +52,7 @@ pub fn provide_extern<$lt>(providers: &mut Providers<$lt>) { index: CRATE_DEF_INDEX }); let dep_node = def_path_hash - .to_dep_node(::rustc::dep_graph::DepKind::CrateMetadata); + .to_dep_node(rustc::dep_graph::DepKind::CrateMetadata); // The DepNodeIndex of the DepNode::CrateMetadata should be // cached somewhere, so that we can use read_index(). $tcx.dep_graph.read(dep_node); @@ -421,7 +422,7 @@ pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro { use syntax::ext::base::SyntaxExtension; use syntax_ext::proc_macro_impl::BangProcMacro; - let client = ::proc_macro::bridge::client::Client::expand1(::proc_macro::quote); + let client = proc_macro::bridge::client::Client::expand1(proc_macro::quote); let ext = SyntaxExtension::ProcMacro { expander: Box::new(BangProcMacro { client }), allow_internal_unstable: true, @@ -436,7 +437,8 @@ pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro { let source_file = sess.parse_sess.source_map().new_source_file(source_name, def.body); let local_span = Span::new(source_file.start_pos, source_file.end_pos, NO_EXPANSION); - let body = source_file_to_stream(&sess.parse_sess, source_file, None); + let (body, errors) = source_file_to_stream(&sess.parse_sess, source_file, None); + emit_unclosed_delims(&errors, &sess.diagnostic()); // Mark the attrs as used let attrs = data.get_item_attrs(id.index, sess); diff --git a/src/librustc_metadata/decoder.rs b/src/librustc_metadata/decoder.rs index ad6296e1a3b..6d7907b096a 100644 --- a/src/librustc_metadata/decoder.rs +++ b/src/librustc_metadata/decoder.rs @@ -1,7 +1,7 @@ // Decoding metadata from a single crate's metadata -use cstore::{self, CrateMetadata, MetadataBlob, NativeLibrary, ForeignModule}; -use schema::*; +use crate::cstore::{self, CrateMetadata, MetadataBlob, NativeLibrary, ForeignModule}; +use crate::schema::*; use rustc_data_structures::sync::{Lrc, ReadGuard}; use rustc::hir::map::{DefKey, DefPath, DefPathData, DefPathHash, Definitions}; @@ -34,6 +34,7 @@ use syntax::ext::base::{MacroKind, SyntaxExtension}; use syntax::ext::hygiene::Mark; use syntax_pos::{self, Span, BytePos, Pos, DUMMY_SP, NO_EXPANSION}; +use log::debug; pub struct DecodeContext<'a, 'tcx: 'a> { opaque: opaque::Decoder<'a>, @@ -545,7 +546,7 @@ pub fn get_trait_def(&self, item_id: DefIndex, sess: &Session) -> ty::TraitDef { fn get_variant(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, - item: &Entry, + item: &Entry<'_>, index: DefIndex, adt_kind: ty::AdtKind) -> ty::VariantDef diff --git a/src/librustc_metadata/diagnostics.rs b/src/librustc_metadata/diagnostics.rs index 1b185243474..c27d13be493 100644 --- a/src/librustc_metadata/diagnostics.rs +++ b/src/librustc_metadata/diagnostics.rs @@ -1,5 +1,7 @@ #![allow(non_snake_case)] +use syntax::{register_diagnostic, register_diagnostics, register_long_diagnostics}; + register_long_diagnostics! { E0454: r##" A link name was given with an empty name. Erroneous code example: diff --git a/src/librustc_metadata/dynamic_lib.rs b/src/librustc_metadata/dynamic_lib.rs index 7d1c3c09d33..b9dc4195cb2 100644 --- a/src/librustc_metadata/dynamic_lib.rs +++ b/src/librustc_metadata/dynamic_lib.rs @@ -76,7 +76,6 @@ pub unsafe fn symbol(&self, symbol: &str) -> Result<*mut T, String> { #[cfg(test)] mod tests { use super::*; - use libc; use std::mem; #[test] @@ -127,7 +126,6 @@ fn test_errors_do_not_crash() { #[cfg(unix)] mod dl { - use libc; use std::ffi::{CStr, OsStr, CString}; use std::os::unix::prelude::*; use std::ptr; diff --git a/src/librustc_metadata/encoder.rs b/src/librustc_metadata/encoder.rs index 3b212f3b747..d68ab9750b9 100644 --- a/src/librustc_metadata/encoder.rs +++ b/src/librustc_metadata/encoder.rs @@ -1,7 +1,7 @@ -use index::Index; -use index_builder::{FromId, IndexBuilder, Untracked}; -use isolated_encoder::IsolatedEncoder; -use schema::*; +use crate::index::Index; +use crate::index_builder::{FromId, IndexBuilder, Untracked}; +use crate::isolated_encoder::IsolatedEncoder; +use crate::schema::*; use rustc::middle::cstore::{LinkagePreference, NativeLibrary, EncodedMetadata, ForeignModule}; @@ -34,6 +34,7 @@ use syntax::source_map::Spanned; use syntax::symbol::keywords; use syntax_pos::{self, hygiene, FileName, SourceFile, Span}; +use log::{debug, trace}; use rustc::hir::{self, PatKind}; use rustc::hir::itemlikevisit::ItemLikeVisitor; @@ -1521,7 +1522,7 @@ fn encode_impls(&mut self, _: ()) -> LazySeq { // symbol associated with them (they weren't translated) or if they're an FFI // definition (as that's not defined in this crate). fn encode_exported_symbols(&mut self, - exported_symbols: &[(ExportedSymbol, SymbolExportLevel)]) + exported_symbols: &[(ExportedSymbol<'_>, SymbolExportLevel)]) -> EncodedExportedSymbols { // The metadata symbol name is special. It should not show up in // downstream crates. diff --git a/src/librustc_metadata/index.rs b/src/librustc_metadata/index.rs index ccf398241b1..18f30383090 100644 --- a/src/librustc_metadata/index.rs +++ b/src/librustc_metadata/index.rs @@ -1,9 +1,10 @@ -use schema::*; +use crate::schema::*; use rustc::hir::def_id::{DefId, DefIndex, DefIndexAddressSpace}; use rustc_serialize::opaque::Encoder; use std::slice; use std::u32; +use log::debug; /// While we are generating the metadata, we also track the position /// of each DefIndex. It is not required that all definitions appear @@ -24,12 +25,12 @@ pub fn new((max_index_lo, max_index_hi): (usize, usize)) -> Index { } } - pub fn record(&mut self, def_id: DefId, entry: Lazy) { + pub fn record(&mut self, def_id: DefId, entry: Lazy>) { assert!(def_id.is_local()); self.record_index(def_id.index, entry); } - pub fn record_index(&mut self, item: DefIndex, entry: Lazy) { + pub fn record_index(&mut self, item: DefIndex, entry: Lazy>) { assert!(entry.position < (u32::MAX as usize)); let position = entry.position as u32; let space_index = item.address_space().index(); diff --git a/src/librustc_metadata/index_builder.rs b/src/librustc_metadata/index_builder.rs index 3608b12aea9..4175f7acd06 100644 --- a/src/librustc_metadata/index_builder.rs +++ b/src/librustc_metadata/index_builder.rs @@ -45,10 +45,10 @@ //! give a callback fn, rather than taking a closure: it allows us to //! easily control precisely what data is given to that fn. -use encoder::EncodeContext; -use index::Index; -use schema::*; -use isolated_encoder::IsolatedEncoder; +use crate::encoder::EncodeContext; +use crate::index::Index; +use crate::schema::*; +use crate::isolated_encoder::IsolatedEncoder; use rustc::hir; use rustc::hir::def_id::DefId; @@ -133,21 +133,21 @@ pub fn into_items(self) -> Index { /// `DefId` index, or implement the `read` method so that it can add /// a read of whatever dep-graph nodes are appropriate. pub trait DepGraphRead { - fn read(&self, tcx: TyCtxt); + fn read(&self, tcx: TyCtxt<'_, '_, '_>); } impl DepGraphRead for DefId { - fn read(&self, _tcx: TyCtxt) {} + fn read(&self, _tcx: TyCtxt<'_, '_, '_>) {} } impl DepGraphRead for ast::NodeId { - fn read(&self, _tcx: TyCtxt) {} + fn read(&self, _tcx: TyCtxt<'_, '_, '_>) {} } impl DepGraphRead for Option where T: DepGraphRead { - fn read(&self, tcx: TyCtxt) { + fn read(&self, tcx: TyCtxt<'_, '_, '_>) { match *self { Some(ref v) => v.read(tcx), None => (), @@ -158,7 +158,7 @@ fn read(&self, tcx: TyCtxt) { impl DepGraphRead for [T] where T: DepGraphRead { - fn read(&self, tcx: TyCtxt) { + fn read(&self, tcx: TyCtxt<'_, '_, '_>) { for i in self { i.read(tcx); } @@ -171,7 +171,7 @@ impl<$($name),*> DepGraphRead for ($($name),*) where $($name: DepGraphRead),* { #[allow(non_snake_case)] - fn read(&self, tcx: TyCtxt) { + fn read(&self, tcx: TyCtxt<'_, '_, '_>) { let &($(ref $name),*) = self; $($name.read(tcx);)* } @@ -184,7 +184,7 @@ fn read(&self, tcx: TyCtxt) { macro_rules! read_hir { ($t:ty) => { impl<'tcx> DepGraphRead for &'tcx $t { - fn read(&self, tcx: TyCtxt) { + fn read(&self, tcx: TyCtxt<'_, '_, '_>) { tcx.hir().read(self.id); } } @@ -208,7 +208,7 @@ fn read(&self, tcx: TyCtxt) { pub struct Untracked(pub T); impl DepGraphRead for Untracked { - fn read(&self, _tcx: TyCtxt) {} + fn read(&self, _tcx: TyCtxt<'_, '_, '_>) {} } /// Newtype that can be used to package up misc data extracted from a @@ -218,7 +218,7 @@ fn read(&self, _tcx: TyCtxt) {} pub struct FromId(pub ast::NodeId, pub T); impl DepGraphRead for FromId { - fn read(&self, tcx: TyCtxt) { + fn read(&self, tcx: TyCtxt<'_, '_, '_>) { tcx.hir().read(self.0); } } diff --git a/src/librustc_metadata/isolated_encoder.rs b/src/librustc_metadata/isolated_encoder.rs index c09d35d150a..e879a73e650 100644 --- a/src/librustc_metadata/isolated_encoder.rs +++ b/src/librustc_metadata/isolated_encoder.rs @@ -1,5 +1,5 @@ -use encoder::EncodeContext; -use schema::{Lazy, LazySeq}; +use crate::encoder::EncodeContext; +use crate::schema::{Lazy, LazySeq}; use rustc::ty::TyCtxt; use rustc_serialize::Encodable; diff --git a/src/librustc_metadata/lib.rs b/src/librustc_metadata/lib.rs index 5dc736bfbd3..a3490b7fea5 100644 --- a/src/librustc_metadata/lib.rs +++ b/src/librustc_metadata/lib.rs @@ -13,23 +13,15 @@ #![recursion_limit="256"] +#![deny(rust_2018_idioms)] + extern crate libc; -#[macro_use] -extern crate log; -extern crate memmap; -extern crate stable_deref_trait; -#[macro_use] -extern crate syntax; -extern crate syntax_pos; -extern crate flate2; +#[allow(unused_extern_crates)] extern crate serialize as rustc_serialize; // used by deriving -extern crate rustc_errors as errors; -extern crate syntax_ext; extern crate proc_macro; #[macro_use] extern crate rustc; -extern crate rustc_target; #[macro_use] extern crate rustc_data_structures; diff --git a/src/librustc_metadata/locator.rs b/src/librustc_metadata/locator.rs index 6b49d6b9e52..f120072b37c 100644 --- a/src/librustc_metadata/locator.rs +++ b/src/librustc_metadata/locator.rs @@ -212,9 +212,9 @@ //! no means all of the necessary details. Take a look at the rest of //! metadata::locator or metadata::creader for all the juicy details! -use cstore::{MetadataRef, MetadataBlob}; -use creader::Library; -use schema::{METADATA_HEADER, rustc_version}; +use crate::cstore::{MetadataRef, MetadataBlob}; +use crate::creader::Library; +use crate::schema::{METADATA_HEADER, rustc_version}; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::svh::Svh; @@ -226,6 +226,7 @@ use errors::DiagnosticBuilder; use syntax::symbol::Symbol; +use syntax::struct_span_err; use syntax_pos::Span; use rustc_target::spec::{Target, TargetTriple}; @@ -241,6 +242,8 @@ use rustc_data_structures::owning_ref::OwningRef; +use log::{debug, info, warn}; + pub struct CrateMismatch { path: PathBuf, got: String, @@ -283,7 +286,7 @@ enum CrateFlavor { } impl fmt::Display for CrateFlavor { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(match *self { CrateFlavor::Rlib => "rlib", CrateFlavor::Rmeta => "rmeta", @@ -600,7 +603,7 @@ fn extract_one(&mut self, } } - let mut err: Option = None; + let mut err: Option> = None; for (lib, kind) in m { info!("{} reading metadata from: {}", flavor, lib.display()); let (hash, metadata) = diff --git a/src/librustc_metadata/native_libs.rs b/src/librustc_metadata/native_libs.rs index 1f00086e32f..118fb203c69 100644 --- a/src/librustc_metadata/native_libs.rs +++ b/src/librustc_metadata/native_libs.rs @@ -9,6 +9,7 @@ use syntax::source_map::Span; use syntax::feature_gate::{self, GateIssue}; use syntax::symbol::Symbol; +use syntax::{span_err, struct_span_err}; pub fn collect<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Vec { let mut collector = Collector { diff --git a/src/librustc_metadata/schema.rs b/src/librustc_metadata/schema.rs index f3ff9747625..af79ea37dff 100644 --- a/src/librustc_metadata/schema.rs +++ b/src/librustc_metadata/schema.rs @@ -1,4 +1,4 @@ -use index; +use crate::index; use rustc::hir; use rustc::hir::def::{self, CtorKind}; @@ -518,7 +518,7 @@ pub enum AssociatedContainer { ImplFinal, } -impl_stable_hash_for!(enum ::schema::AssociatedContainer { +impl_stable_hash_for!(enum crate::schema::AssociatedContainer { TraitRequired, TraitWithDefault, ImplDefault, diff --git a/src/librustc_mir/Cargo.toml b/src/librustc_mir/Cargo.toml index f0234c48c3e..44a6b41cdfe 100644 --- a/src/librustc_mir/Cargo.toml +++ b/src/librustc_mir/Cargo.toml @@ -2,6 +2,7 @@ authors = ["The Rust Project Developers"] name = "rustc_mir" version = "0.0.0" +edition = "2018" [lib] name = "rustc_mir" @@ -12,7 +13,7 @@ crate-type = ["dylib"] arena = { path = "../libarena" } bitflags = "1.0" either = "1.5.0" -graphviz = { path = "../libgraphviz" } +dot = { path = "../libgraphviz", package = "graphviz" } log = "0.4" log_settings = "0.1.1" polonius-engine = "0.6.2" diff --git a/src/librustc_mir/borrow_check/borrow_set.rs b/src/librustc_mir/borrow_check/borrow_set.rs index ecbc6118bc3..2788f5d4325 100644 --- a/src/librustc_mir/borrow_check/borrow_set.rs +++ b/src/librustc_mir/borrow_check/borrow_set.rs @@ -1,7 +1,7 @@ -use borrow_check::place_ext::PlaceExt; -use borrow_check::nll::ToRegionVid; -use dataflow::indexes::BorrowIndex; -use dataflow::move_paths::MoveData; +use crate::borrow_check::place_ext::PlaceExt; +use crate::borrow_check::nll::ToRegionVid; +use crate::dataflow::indexes::BorrowIndex; +use crate::dataflow::move_paths::MoveData; use rustc::mir::traversal; use rustc::mir::visit::{ PlaceContext, Visitor, NonUseContext, MutatingUseContext, NonMutatingUseContext @@ -72,7 +72,7 @@ fn index(&self, index: BorrowIndex) -> &BorrowData<'tcx> { } impl<'tcx> fmt::Display for BorrowData<'tcx> { - fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result { let kind = match self.kind { mir::BorrowKind::Shared => "", mir::BorrowKind::Shallow => "shallow ", diff --git a/src/librustc_mir/borrow_check/error_reporting.rs b/src/librustc_mir/borrow_check/error_reporting.rs index b0700317567..afb26963217 100644 --- a/src/librustc_mir/borrow_check/error_reporting.rs +++ b/src/librustc_mir/borrow_check/error_reporting.rs @@ -1,7 +1,7 @@ -use borrow_check::nll::explain_borrow::BorrowExplanation; -use borrow_check::nll::region_infer::{RegionName, RegionNameSource}; -use borrow_check::prefixes::IsPrefixOf; -use borrow_check::WriteKind; +use crate::borrow_check::nll::explain_borrow::BorrowExplanation; +use crate::borrow_check::nll::region_infer::{RegionName, RegionNameSource}; +use crate::borrow_check::prefixes::IsPrefixOf; +use crate::borrow_check::WriteKind; use rustc::hir; use rustc::hir::def_id::DefId; use rustc::middle::region::ScopeTree; @@ -22,10 +22,10 @@ use super::borrow_set::BorrowData; use super::{Context, MirBorrowckCtxt}; use super::{InitializationRequiringAction, PrefixSet}; -use dataflow::drop_flag_effects; -use dataflow::move_paths::indexes::MoveOutIndex; -use dataflow::move_paths::MovePathIndex; -use util::borrowck_errors::{BorrowckErrors, Origin}; +use crate::dataflow::drop_flag_effects; +use crate::dataflow::move_paths::indexes::MoveOutIndex; +use crate::dataflow::move_paths::MovePathIndex; +use crate::util::borrowck_errors::{BorrowckErrors, Origin}; #[derive(Debug)] struct MoveSite { @@ -1726,7 +1726,7 @@ fn append_local_to_string(&self, local_index: Local, buf: &mut String) -> Result } /// End-user visible description of the `field`nth field of `base` - fn describe_field(&self, base: &Place, field: Field) -> String { + fn describe_field(&self, base: &Place<'_>, field: Field) -> String { match *base { Place::Local(local) => { let local = &self.mir.local_decls[local]; @@ -1751,7 +1751,7 @@ fn describe_field(&self, base: &Place, field: Field) -> String { } /// End-user visible description of the `field_index`nth field of `ty` - fn describe_field_from_ty(&self, ty: &ty::Ty, field: Field) -> String { + fn describe_field_from_ty(&self, ty: &ty::Ty<'_>, field: Field) -> String { if ty.is_box() { // If the type is a box, the field is described from the boxed type self.describe_field_from_ty(&ty.boxed_ty(), field) @@ -1860,7 +1860,7 @@ fn classify_drop_access_kind(&self, place: &Place<'tcx>) -> StorageDeadOrDrop<'t fn annotate_argument_and_return_for_borrow( &self, borrow: &BorrowData<'tcx>, - ) -> Option { + ) -> Option> { // Define a fallback for when we can't match a closure. let fallback = || { let is_closure = self.infcx.tcx.is_closure(self.mir_def_id); @@ -2081,7 +2081,7 @@ fn annotate_fn_sig( &self, did: DefId, sig: ty::PolyFnSig<'tcx>, - ) -> Option { + ) -> Option> { debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig); let is_closure = self.infcx.tcx.is_closure(did); let fn_node_id = self.infcx.tcx.hir().as_local_node_id(did)?; @@ -2368,14 +2368,22 @@ pub(super) fn var_or_use(self) -> Span { } // Add a span label to the arguments of the closure, if it exists. - pub(super) fn args_span_label(self, err: &mut DiagnosticBuilder, message: impl Into) { + pub(super) fn args_span_label( + self, + err: &mut DiagnosticBuilder<'_>, + message: impl Into, + ) { if let UseSpans::ClosureUse { args_span, .. } = self { err.span_label(args_span, message); } } // Add a span label to the use of the captured variable, if it exists. - pub(super) fn var_span_label(self, err: &mut DiagnosticBuilder, message: impl Into) { + pub(super) fn var_span_label( + self, + err: &mut DiagnosticBuilder<'_>, + message: impl Into, + ) { if let UseSpans::ClosureUse { var_span, .. } = self { err.span_label(var_span, message); } @@ -2563,7 +2571,7 @@ fn closure_span( /// Helper to retrieve span(s) of given borrow from the current MIR /// representation - pub(super) fn retrieve_borrow_spans(&self, borrow: &BorrowData) -> UseSpans { + pub(super) fn retrieve_borrow_spans(&self, borrow: &BorrowData<'_>) -> UseSpans { let span = self.mir.source_info(borrow.reserve_location).span; self.borrow_spans(span, borrow.reserve_location) } diff --git a/src/librustc_mir/borrow_check/flows.rs b/src/librustc_mir/borrow_check/flows.rs index 4eeb19c4e7a..8de39f0efc1 100644 --- a/src/librustc_mir/borrow_check/flows.rs +++ b/src/librustc_mir/borrow_check/flows.rs @@ -7,16 +7,16 @@ use rustc::ty::RegionVid; use rustc_data_structures::bit_set::BitIter; -use borrow_check::location::LocationIndex; +use crate::borrow_check::location::LocationIndex; use polonius_engine::Output; -use dataflow::move_paths::indexes::BorrowIndex; -use dataflow::move_paths::HasMoveData; -use dataflow::Borrows; -use dataflow::EverInitializedPlaces; -use dataflow::{FlowAtLocation, FlowsAtLocation}; -use dataflow::MaybeUninitializedPlaces; +use crate::dataflow::move_paths::indexes::BorrowIndex; +use crate::dataflow::move_paths::HasMoveData; +use crate::dataflow::Borrows; +use crate::dataflow::EverInitializedPlaces; +use crate::dataflow::{FlowAtLocation, FlowsAtLocation}; +use crate::dataflow::MaybeUninitializedPlaces; use either::Either; use std::fmt; use std::rc::Rc; @@ -57,7 +57,7 @@ impl<'b, 'gcx, 'tcx> Flows<'b, 'gcx, 'tcx> { } } - crate fn with_outgoing_borrows(&self, op: impl FnOnce(BitIter)) { + crate fn with_outgoing_borrows(&self, op: impl FnOnce(BitIter<'_, BorrowIndex>)) { self.borrows.with_iter_outgoing(op) } } @@ -93,7 +93,7 @@ fn apply_local_effect(&mut self, location: Location) { } impl<'b, 'gcx, 'tcx> fmt::Display for Flows<'b, 'gcx, 'tcx> { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let mut s = String::new(); s.push_str("borrows in effect: ["); diff --git a/src/librustc_mir/borrow_check/mod.rs b/src/librustc_mir/borrow_check/mod.rs index 5597e4a6c59..45a8c9e8e69 100644 --- a/src/librustc_mir/borrow_check/mod.rs +++ b/src/librustc_mir/borrow_check/mod.rs @@ -1,6 +1,6 @@ //! This query borrow-checks the MIR to (further) ensure it is not broken. -use borrow_check::nll::region_infer::RegionInferenceContext; +use crate::borrow_check::nll::region_infer::RegionInferenceContext; use rustc::hir; use rustc::hir::Node; use rustc::hir::def_id::DefId; @@ -25,16 +25,16 @@ use syntax_pos::Span; -use dataflow::indexes::{BorrowIndex, InitIndex, MoveOutIndex, MovePathIndex}; -use dataflow::move_paths::{HasMoveData, LookupResult, MoveData, MoveError}; -use dataflow::Borrows; -use dataflow::DataflowResultsConsumer; -use dataflow::FlowAtLocation; -use dataflow::MoveDataParamEnv; -use dataflow::{do_dataflow, DebugFormatted}; -use dataflow::EverInitializedPlaces; -use dataflow::{MaybeInitializedPlaces, MaybeUninitializedPlaces}; -use util::borrowck_errors::{BorrowckErrors, Origin}; +use crate::dataflow::indexes::{BorrowIndex, InitIndex, MoveOutIndex, MovePathIndex}; +use crate::dataflow::move_paths::{HasMoveData, LookupResult, MoveData, MoveError}; +use crate::dataflow::Borrows; +use crate::dataflow::DataflowResultsConsumer; +use crate::dataflow::FlowAtLocation; +use crate::dataflow::MoveDataParamEnv; +use crate::dataflow::{do_dataflow, DebugFormatted}; +use crate::dataflow::EverInitializedPlaces; +use crate::dataflow::{MaybeInitializedPlaces, MaybeUninitializedPlaces}; +use crate::util::borrowck_errors::{BorrowckErrors, Origin}; use self::borrow_set::{BorrowData, BorrowSet}; use self::flows::Flows; @@ -59,7 +59,7 @@ pub(crate) mod nll; -pub fn provide(providers: &mut Providers) { +pub fn provide(providers: &mut Providers<'_>) { *providers = Providers { mir_borrowck, ..*providers @@ -108,7 +108,7 @@ fn mir_borrowck<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> BorrowC } let opt_closure_req = tcx.infer_ctxt().enter(|infcx| { - let input_mir: &Mir = &input_mir.borrow(); + let input_mir: &Mir<'_> = &input_mir.borrow(); do_mir_borrowck(&infcx, input_mir, def_id) }); debug!("mir_borrowck done"); diff --git a/src/librustc_mir/borrow_check/move_errors.rs b/src/librustc_mir/borrow_check/move_errors.rs index 8539b5c26ce..f7d46925e17 100644 --- a/src/librustc_mir/borrow_check/move_errors.rs +++ b/src/librustc_mir/borrow_check/move_errors.rs @@ -6,13 +6,13 @@ use rustc_errors::{DiagnosticBuilder,Applicability}; use syntax_pos::Span; -use borrow_check::MirBorrowckCtxt; -use borrow_check::prefixes::PrefixSet; -use dataflow::move_paths::{ +use crate::borrow_check::MirBorrowckCtxt; +use crate::borrow_check::prefixes::PrefixSet; +use crate::dataflow::move_paths::{ IllegalMoveOrigin, IllegalMoveOriginKind, InitLocation, LookupResult, MoveError, MovePathIndex, }; -use util::borrowck_errors::{BorrowckErrors, Origin}; +use crate::util::borrowck_errors::{BorrowckErrors, Origin}; // Often when desugaring a pattern match we may have many individual moves in // MIR that are all part of one operation from the user's point-of-view. For @@ -63,7 +63,7 @@ enum BorrowedContentSource { } impl Display for BorrowedContentSource { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { BorrowedContentSource::Arc => write!(f, "an `Arc`"), BorrowedContentSource::Rc => write!(f, "an `Rc`"), @@ -240,7 +240,7 @@ fn append_binding_error( fn report(&mut self, error: GroupedMoveError<'tcx>) { let (mut err, err_span) = { - let (span, original_path, kind): (Span, &Place<'tcx>, &IllegalMoveOriginKind) = + let (span, original_path, kind): (Span, &Place<'tcx>, &IllegalMoveOriginKind<'_>) = match error { GroupedMoveError::MovesFromPlace { span, diff --git a/src/librustc_mir/borrow_check/mutability_errors.rs b/src/librustc_mir/borrow_check/mutability_errors.rs index 9d3ce7693ea..dad8d903cf9 100644 --- a/src/librustc_mir/borrow_check/mutability_errors.rs +++ b/src/librustc_mir/borrow_check/mutability_errors.rs @@ -8,11 +8,11 @@ use syntax_pos::Span; use syntax_pos::symbol::keywords; -use dataflow::move_paths::InitLocation; -use borrow_check::MirBorrowckCtxt; -use util::borrowck_errors::{BorrowckErrors, Origin}; -use util::collect_writes::FindAssignments; -use util::suggest_ref_mut; +use crate::dataflow::move_paths::InitLocation; +use crate::borrow_check::MirBorrowckCtxt; +use crate::util::borrowck_errors::{BorrowckErrors, Origin}; +use crate::util::collect_writes::FindAssignments; +use crate::util::suggest_ref_mut; use rustc_errors::Applicability; #[derive(Copy, Clone, Debug, Eq, PartialEq)] @@ -611,7 +611,7 @@ fn suggest_ampmut<'cx, 'gcx, 'tcx>( }) } -fn is_closure_or_generator(ty: ty::Ty) -> bool { +fn is_closure_or_generator(ty: ty::Ty<'_>) -> bool { ty.is_closure() || ty.is_generator() } diff --git a/src/librustc_mir/borrow_check/nll/constraint_generation.rs b/src/librustc_mir/borrow_check/nll/constraint_generation.rs index 588f46cb77f..c02c2b4934c 100644 --- a/src/librustc_mir/borrow_check/nll/constraint_generation.rs +++ b/src/librustc_mir/borrow_check/nll/constraint_generation.rs @@ -1,8 +1,8 @@ -use borrow_check::borrow_set::BorrowSet; -use borrow_check::location::LocationTable; -use borrow_check::nll::ToRegionVid; -use borrow_check::nll::facts::AllFacts; -use borrow_check::nll::region_infer::values::LivenessValues; +use crate::borrow_check::borrow_set::BorrowSet; +use crate::borrow_check::location::LocationTable; +use crate::borrow_check::nll::ToRegionVid; +use crate::borrow_check::nll::facts::AllFacts; +use crate::borrow_check::nll::region_infer::values::LivenessValues; use rustc::infer::InferCtxt; use rustc::mir::visit::TyContext; use rustc::mir::visit::Visitor; diff --git a/src/librustc_mir/borrow_check/nll/constraints/graph.rs b/src/librustc_mir/borrow_check/nll/constraints/graph.rs index fe9ccb489e4..2479dfd1c70 100644 --- a/src/librustc_mir/borrow_check/nll/constraints/graph.rs +++ b/src/librustc_mir/borrow_check/nll/constraints/graph.rs @@ -1,6 +1,6 @@ -use borrow_check::nll::type_check::Locations; -use borrow_check::nll::constraints::ConstraintIndex; -use borrow_check::nll::constraints::{ConstraintSet, OutlivesConstraint}; +use crate::borrow_check::nll::type_check::Locations; +use crate::borrow_check::nll::constraints::ConstraintIndex; +use crate::borrow_check::nll::constraints::{ConstraintSet, OutlivesConstraint}; use rustc::mir::ConstraintCategory; use rustc::ty::RegionVid; use rustc_data_structures::graph; diff --git a/src/librustc_mir/borrow_check/nll/constraints/mod.rs b/src/librustc_mir/borrow_check/nll/constraints/mod.rs index 146bd65dd11..d3f9743dfed 100644 --- a/src/librustc_mir/borrow_check/nll/constraints/mod.rs +++ b/src/librustc_mir/borrow_check/nll/constraints/mod.rs @@ -2,7 +2,7 @@ use rustc::ty::RegionVid; use rustc_data_structures::graph::scc::Sccs; use rustc_data_structures::indexed_vec::{Idx, IndexVec}; -use borrow_check::nll::type_check::Locations; +use crate::borrow_check::nll::type_check::Locations; use std::fmt; use std::ops::Deref; @@ -84,7 +84,7 @@ pub struct OutlivesConstraint { } impl fmt::Debug for OutlivesConstraint { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { write!( formatter, "({:?}: {:?}) due to {:?}", diff --git a/src/librustc_mir/borrow_check/nll/explain_borrow/find_use.rs b/src/librustc_mir/borrow_check/nll/explain_borrow/find_use.rs index 53035dae4f3..c5aaf5b811e 100644 --- a/src/librustc_mir/borrow_check/nll/explain_borrow/find_use.rs +++ b/src/librustc_mir/borrow_check/nll/explain_borrow/find_use.rs @@ -1,13 +1,13 @@ use std::collections::VecDeque; use std::rc::Rc; -use borrow_check::nll::region_infer::{Cause, RegionInferenceContext}; -use borrow_check::nll::ToRegionVid; +use crate::borrow_check::nll::region_infer::{Cause, RegionInferenceContext}; +use crate::borrow_check::nll::ToRegionVid; +use crate::util::liveness::{self, DefUse}; use rustc::mir::visit::{MirVisitable, PlaceContext, Visitor}; use rustc::mir::{Local, Location, Mir}; use rustc::ty::{RegionVid, TyCtxt}; use rustc_data_structures::fx::FxHashSet; -use util::liveness::{self, DefUse}; crate fn find<'tcx>( mir: &Mir<'tcx>, diff --git a/src/librustc_mir/borrow_check/nll/explain_borrow/mod.rs b/src/librustc_mir/borrow_check/nll/explain_borrow/mod.rs index 968c0f53a48..8e57d107aa6 100644 --- a/src/librustc_mir/borrow_check/nll/explain_borrow/mod.rs +++ b/src/librustc_mir/borrow_check/nll/explain_borrow/mod.rs @@ -1,8 +1,8 @@ -use borrow_check::borrow_set::BorrowData; -use borrow_check::error_reporting::UseSpans; -use borrow_check::nll::ConstraintDescription; -use borrow_check::nll::region_infer::{Cause, RegionName}; -use borrow_check::{Context, MirBorrowckCtxt, WriteKind}; +use crate::borrow_check::borrow_set::BorrowData; +use crate::borrow_check::error_reporting::UseSpans; +use crate::borrow_check::nll::ConstraintDescription; +use crate::borrow_check::nll::region_infer::{Cause, RegionName}; +use crate::borrow_check::{Context, MirBorrowckCtxt, WriteKind}; use rustc::ty::{self, TyCtxt}; use rustc::mir::{ CastKind, ConstraintCategory, FakeReadCause, Local, Location, Mir, Operand, @@ -14,7 +14,7 @@ mod find_use; -pub(in borrow_check) enum BorrowExplanation { +pub(in crate::borrow_check) enum BorrowExplanation { UsedLater(LaterUseKind, Span), UsedLaterInLoop(LaterUseKind, Span), UsedLaterWhenDropped { @@ -33,7 +33,7 @@ pub(in borrow_check) enum BorrowExplanation { } #[derive(Clone, Copy)] -pub(in borrow_check) enum LaterUseKind { +pub(in crate::borrow_check) enum LaterUseKind { TraitCapture, ClosureCapture, Call, @@ -42,13 +42,13 @@ pub(in borrow_check) enum LaterUseKind { } impl BorrowExplanation { - pub(in borrow_check) fn is_explained(&self) -> bool { + pub(in crate::borrow_check) fn is_explained(&self) -> bool { match self { BorrowExplanation::Unexplained => false, _ => true, } } - pub(in borrow_check) fn add_explanation_to_diagnostic<'cx, 'gcx, 'tcx>( + pub(in crate::borrow_check) fn add_explanation_to_diagnostic<'cx, 'gcx, 'tcx>( &self, tcx: TyCtxt<'cx, 'gcx, 'tcx>, mir: &Mir<'tcx>, @@ -187,7 +187,7 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> { /// - second half is the place being accessed /// /// [d]: https://rust-lang.github.io/rfcs/2094-nll.html#leveraging-intuition-framing-errors-in-terms-of-points - pub(in borrow_check) fn explain_why_borrow_contains_point( + pub(in crate::borrow_check) fn explain_why_borrow_contains_point( &self, context: Context, borrow: &BorrowData<'tcx>, diff --git a/src/librustc_mir/borrow_check/nll/facts.rs b/src/librustc_mir/borrow_check/nll/facts.rs index bc33a1c9c65..9672d3e78cd 100644 --- a/src/librustc_mir/borrow_check/nll/facts.rs +++ b/src/librustc_mir/borrow_check/nll/facts.rs @@ -1,5 +1,5 @@ -use borrow_check::location::{LocationIndex, LocationTable}; -use dataflow::indexes::BorrowIndex; +use crate::borrow_check::location::{LocationIndex, LocationTable}; +use crate::dataflow::indexes::BorrowIndex; use polonius_engine::AllFacts as PoloniusAllFacts; use polonius_engine::Atom; use rustc::ty::{RegionVid, TyCtxt}; diff --git a/src/librustc_mir/borrow_check/nll/invalidation.rs b/src/librustc_mir/borrow_check/nll/invalidation.rs index 112b3995255..3df6b797a44 100644 --- a/src/librustc_mir/borrow_check/nll/invalidation.rs +++ b/src/librustc_mir/borrow_check/nll/invalidation.rs @@ -1,15 +1,15 @@ -use borrow_check::borrow_set::BorrowSet; -use borrow_check::location::LocationTable; -use borrow_check::{JustWrite, WriteAndRead}; -use borrow_check::{AccessDepth, Deep, Shallow}; -use borrow_check::{ReadOrWrite, Activation, Read, Reservation, Write}; -use borrow_check::{Context, ContextKind}; -use borrow_check::{LocalMutationIsAllowed, MutateMode}; -use borrow_check::ArtificialField; -use borrow_check::{ReadKind, WriteKind}; -use borrow_check::nll::facts::AllFacts; -use borrow_check::path_utils::*; -use dataflow::move_paths::indexes::BorrowIndex; +use crate::borrow_check::borrow_set::BorrowSet; +use crate::borrow_check::location::LocationTable; +use crate::borrow_check::{JustWrite, WriteAndRead}; +use crate::borrow_check::{AccessDepth, Deep, Shallow}; +use crate::borrow_check::{ReadOrWrite, Activation, Read, Reservation, Write}; +use crate::borrow_check::{Context, ContextKind}; +use crate::borrow_check::{LocalMutationIsAllowed, MutateMode}; +use crate::borrow_check::ArtificialField; +use crate::borrow_check::{ReadKind, WriteKind}; +use crate::borrow_check::nll::facts::AllFacts; +use crate::borrow_check::path_utils::*; +use crate::dataflow::move_paths::indexes::BorrowIndex; use rustc::ty::TyCtxt; use rustc::mir::visit::Visitor; use rustc::mir::{BasicBlock, Location, Mir, Place, Rvalue}; diff --git a/src/librustc_mir/borrow_check/nll/mod.rs b/src/librustc_mir/borrow_check/nll/mod.rs index a092c3b8ecd..1fca104cd38 100644 --- a/src/librustc_mir/borrow_check/nll/mod.rs +++ b/src/librustc_mir/borrow_check/nll/mod.rs @@ -1,13 +1,14 @@ -use borrow_check::borrow_set::BorrowSet; -use borrow_check::location::{LocationIndex, LocationTable}; -use borrow_check::nll::facts::AllFactsExt; -use borrow_check::nll::type_check::{MirTypeckResults, MirTypeckRegionConstraints}; -use borrow_check::nll::type_check::liveness::liveness_map::NllLivenessMap; -use borrow_check::nll::region_infer::values::RegionValueElements; -use dataflow::indexes::BorrowIndex; -use dataflow::move_paths::MoveData; -use dataflow::FlowAtLocation; -use dataflow::MaybeInitializedPlaces; +use crate::borrow_check::borrow_set::BorrowSet; +use crate::borrow_check::location::{LocationIndex, LocationTable}; +use crate::borrow_check::nll::facts::AllFactsExt; +use crate::borrow_check::nll::type_check::{MirTypeckResults, MirTypeckRegionConstraints}; +use crate::borrow_check::nll::type_check::liveness::liveness_map::NllLivenessMap; +use crate::borrow_check::nll::region_infer::values::RegionValueElements; +use crate::dataflow::indexes::BorrowIndex; +use crate::dataflow::move_paths::MoveData; +use crate::dataflow::FlowAtLocation; +use crate::dataflow::MaybeInitializedPlaces; +use crate::transform::MirSource; use rustc::hir::def_id::DefId; use rustc::infer::InferCtxt; use rustc::mir::{ClosureOutlivesSubject, ClosureRegionRequirements, Mir}; @@ -19,12 +20,11 @@ use std::path::PathBuf; use std::rc::Rc; use std::str::FromStr; -use transform::MirSource; use self::mir_util::PassWhere; use polonius_engine::{Algorithm, Output}; -use util as mir_util; -use util::pretty; +use crate::util as mir_util; +use crate::util::pretty; mod constraint_generation; pub mod explain_borrow; @@ -45,7 +45,7 @@ /// scraping out the set of universal regions (e.g., region parameters) /// declared on the function. That set will need to be given to /// `compute_regions`. -pub(in borrow_check) fn replace_regions_in_mir<'cx, 'gcx, 'tcx>( +pub(in crate::borrow_check) fn replace_regions_in_mir<'cx, 'gcx, 'tcx>( infcx: &InferCtxt<'cx, 'gcx, 'tcx>, def_id: DefId, param_env: ty::ParamEnv<'tcx>, @@ -68,7 +68,7 @@ pub(in borrow_check) fn replace_regions_in_mir<'cx, 'gcx, 'tcx>( /// Computes the (non-lexical) regions from the input MIR. /// /// This may result in errors being reported. -pub(in borrow_check) fn compute_regions<'cx, 'gcx, 'tcx>( +pub(in crate::borrow_check) fn compute_regions<'cx, 'gcx, 'tcx>( infcx: &InferCtxt<'cx, 'gcx, 'tcx>, def_id: DefId, universal_regions: UniversalRegions<'tcx>, @@ -211,8 +211,8 @@ fn dump_mir_results<'a, 'gcx, 'tcx>( infcx: &InferCtxt<'a, 'gcx, 'tcx>, source: MirSource, mir: &Mir<'tcx>, - regioncx: &RegionInferenceContext, - closure_region_requirements: &Option, + regioncx: &RegionInferenceContext<'_>, + closure_region_requirements: &Option>, ) { if !mir_util::dump_enabled(infcx.tcx, "nll", source) { return; @@ -254,14 +254,14 @@ fn dump_mir_results<'a, 'gcx, 'tcx>( ); // Also dump the inference graph constraints as a graphviz file. - let _: io::Result<()> = try_block! { + let _: io::Result<()> = try { let mut file = pretty::create_dump_file(infcx.tcx, "regioncx.all.dot", None, "nll", &0, source)?; regioncx.dump_graphviz_raw_constraints(&mut file)?; }; // Also dump the inference graph constraints as a graphviz file. - let _: io::Result<()> = try_block! { + let _: io::Result<()> = try { let mut file = pretty::create_dump_file(infcx.tcx, "regioncx.scc.dot", None, "nll", &0, source)?; regioncx.dump_graphviz_scc_constraints(&mut file)?; @@ -273,7 +273,7 @@ fn dump_annotation<'a, 'gcx, 'tcx>( mir: &Mir<'tcx>, mir_def_id: DefId, regioncx: &RegionInferenceContext<'tcx>, - closure_region_requirements: &Option, + closure_region_requirements: &Option>, errors_buffer: &mut Vec, ) { let tcx = infcx.tcx; @@ -322,7 +322,7 @@ fn dump_annotation<'a, 'gcx, 'tcx>( } fn for_each_region_constraint( - closure_region_requirements: &ClosureRegionRequirements, + closure_region_requirements: &ClosureRegionRequirements<'_>, with_msg: &mut dyn FnMut(&str) -> io::Result<()>, ) -> io::Result<()> { for req in &closure_region_requirements.outlives_requirements { diff --git a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/mod.rs b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/mod.rs index 550668a7cee..3498e343767 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/mod.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/mod.rs @@ -1,8 +1,9 @@ -use borrow_check::nll::constraints::OutlivesConstraint; -use borrow_check::nll::region_infer::RegionInferenceContext; -use borrow_check::nll::type_check::Locations; -use borrow_check::nll::universal_regions::DefiningTy; -use borrow_check::nll::ConstraintDescription; +use crate::borrow_check::nll::constraints::OutlivesConstraint; +use crate::borrow_check::nll::region_infer::RegionInferenceContext; +use crate::borrow_check::nll::type_check::Locations; +use crate::borrow_check::nll::universal_regions::DefiningTy; +use crate::borrow_check::nll::ConstraintDescription; +use crate::util::borrowck_errors::{BorrowckErrors, Origin}; use rustc::hir::def_id::DefId; use rustc::infer::error_reporting::nice_region_error::NiceRegionError; use rustc::infer::InferCtxt; @@ -15,7 +16,6 @@ use syntax::errors::Applicability; use syntax::symbol::keywords; use syntax_pos::Span; -use util::borrowck_errors::{BorrowckErrors, Origin}; mod region_name; mod var_name; diff --git a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs index bff80155112..2c4f359f65f 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs @@ -1,7 +1,7 @@ use std::fmt::{self, Display}; -use borrow_check::nll::region_infer::RegionInferenceContext; -use borrow_check::nll::universal_regions::DefiningTy; -use borrow_check::nll::ToRegionVid; +use crate::borrow_check::nll::region_infer::RegionInferenceContext; +use crate::borrow_check::nll::universal_regions::DefiningTy; +use crate::borrow_check::nll::ToRegionVid; use rustc::hir; use rustc::hir::def_id::DefId; use rustc::infer::InferCtxt; @@ -109,7 +109,7 @@ impl RegionName { } impl Display for RegionName { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.name) } } diff --git a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/var_name.rs b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/var_name.rs index c2f2e99c0a5..bd7b8829c7b 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/var_name.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/var_name.rs @@ -1,5 +1,5 @@ -use borrow_check::nll::region_infer::RegionInferenceContext; -use borrow_check::nll::ToRegionVid; +use crate::borrow_check::nll::region_infer::RegionInferenceContext; +use crate::borrow_check::nll::ToRegionVid; use rustc::mir::{Local, Mir}; use rustc::ty::{RegionVid, TyCtxt}; use rustc_data_structures::indexed_vec::Idx; diff --git a/src/librustc_mir/borrow_check/nll/region_infer/graphviz.rs b/src/librustc_mir/borrow_check/nll/region_infer/graphviz.rs index 2da158be432..cffc66ac7dd 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/graphviz.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/graphviz.rs @@ -3,8 +3,7 @@ //! data to rendered labels. use super::*; -use borrow_check::nll::constraints::OutlivesConstraint; -use dot; +use crate::borrow_check::nll::constraints::OutlivesConstraint; use std::borrow::Cow; use std::io::{self, Write}; diff --git a/src/librustc_mir/borrow_check/nll/region_infer/mod.rs b/src/librustc_mir/borrow_check/nll/region_infer/mod.rs index fee5dc86465..7fe657702d7 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/mod.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/mod.rs @@ -1,9 +1,11 @@ use super::universal_regions::UniversalRegions; -use borrow_check::nll::constraints::graph::NormalConstraintGraph; -use borrow_check::nll::constraints::{ConstraintSccIndex, ConstraintSet, OutlivesConstraint}; -use borrow_check::nll::region_infer::values::{PlaceholderIndices, RegionElement, ToElementIndex}; -use borrow_check::nll::type_check::free_region_relations::UniversalRegionRelations; -use borrow_check::nll::type_check::Locations; +use crate::borrow_check::nll::constraints::graph::NormalConstraintGraph; +use crate::borrow_check::nll::constraints::{ConstraintSccIndex, ConstraintSet, OutlivesConstraint}; +use crate::borrow_check::nll::region_infer::values::{ + PlaceholderIndices, RegionElement, ToElementIndex +}; +use crate::borrow_check::nll::type_check::free_region_relations::UniversalRegionRelations; +use crate::borrow_check::nll::type_check::Locations; use rustc::hir::def_id::DefId; use rustc::infer::canonical::QueryRegionConstraint; use rustc::infer::region_constraints::{GenericKind, VarInfos, VerifyBound}; diff --git a/src/librustc_mir/borrow_check/nll/type_check/constraint_conversion.rs b/src/librustc_mir/borrow_check/nll/type_check/constraint_conversion.rs index b7555e57a62..1a72205ad7a 100644 --- a/src/librustc_mir/borrow_check/nll/type_check/constraint_conversion.rs +++ b/src/librustc_mir/borrow_check/nll/type_check/constraint_conversion.rs @@ -1,8 +1,8 @@ -use borrow_check::nll::constraints::OutlivesConstraint; -use borrow_check::nll::region_infer::TypeTest; -use borrow_check::nll::type_check::{Locations, MirTypeckRegionConstraints}; -use borrow_check::nll::universal_regions::UniversalRegions; -use borrow_check::nll::ToRegionVid; +use crate::borrow_check::nll::constraints::OutlivesConstraint; +use crate::borrow_check::nll::region_infer::TypeTest; +use crate::borrow_check::nll::type_check::{Locations, MirTypeckRegionConstraints}; +use crate::borrow_check::nll::universal_regions::UniversalRegions; +use crate::borrow_check::nll::ToRegionVid; use rustc::infer::canonical::QueryRegionConstraint; use rustc::infer::outlives::env::RegionBoundPairs; use rustc::infer::outlives::obligations::{TypeOutlives, TypeOutlivesDelegate}; diff --git a/src/librustc_mir/borrow_check/nll/type_check/free_region_relations.rs b/src/librustc_mir/borrow_check/nll/type_check/free_region_relations.rs index b19dc9091cb..f549aea81f6 100644 --- a/src/librustc_mir/borrow_check/nll/type_check/free_region_relations.rs +++ b/src/librustc_mir/borrow_check/nll/type_check/free_region_relations.rs @@ -1,7 +1,7 @@ -use borrow_check::nll::type_check::constraint_conversion; -use borrow_check::nll::type_check::{Locations, MirTypeckRegionConstraints}; -use borrow_check::nll::universal_regions::UniversalRegions; -use borrow_check::nll::ToRegionVid; +use crate::borrow_check::nll::type_check::constraint_conversion; +use crate::borrow_check::nll::type_check::{Locations, MirTypeckRegionConstraints}; +use crate::borrow_check::nll::universal_regions::UniversalRegions; +use crate::borrow_check::nll::ToRegionVid; use rustc::infer::canonical::QueryRegionConstraint; use rustc::infer::outlives::free_region_map::FreeRegionRelations; use rustc::infer::region_constraints::GenericKind; diff --git a/src/librustc_mir/borrow_check/nll/type_check/input_output.rs b/src/librustc_mir/borrow_check/nll/type_check/input_output.rs index ef0f7e1b217..50828c294fa 100644 --- a/src/librustc_mir/borrow_check/nll/type_check/input_output.rs +++ b/src/librustc_mir/borrow_check/nll/type_check/input_output.rs @@ -7,7 +7,7 @@ //! `RETURN_PLACE` the MIR arguments) are always fully normalized (and //! contain revealed `impl Trait` values). -use borrow_check::nll::universal_regions::UniversalRegions; +use crate::borrow_check::nll::universal_regions::UniversalRegions; use rustc::infer::LateBoundRegionConversionTime; use rustc::mir::*; use rustc::ty::Ty; diff --git a/src/librustc_mir/borrow_check/nll/type_check/liveness/liveness_map.rs b/src/librustc_mir/borrow_check/nll/type_check/liveness/liveness_map.rs index dda74e6a6a6..5e2e4407cbe 100644 --- a/src/librustc_mir/borrow_check/nll/type_check/liveness/liveness_map.rs +++ b/src/librustc_mir/borrow_check/nll/type_check/liveness/liveness_map.rs @@ -6,13 +6,13 @@ //! liveness code so that it only operates over variables with regions in their //! types, instead of all variables. -use borrow_check::nll::ToRegionVid; -use borrow_check::nll::facts::{AllFacts, AllFactsExt}; +use crate::borrow_check::nll::ToRegionVid; +use crate::borrow_check::nll::facts::{AllFacts, AllFactsExt}; +use crate::util::liveness::LiveVariableMap; use rustc::mir::{Local, Mir}; use rustc::ty::{RegionVid, TyCtxt}; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::indexed_vec::{Idx, IndexVec}; -use util::liveness::LiveVariableMap; /// Map between Local and LiveVar indices: the purpose of this /// map is to define the subset of local variables for which we need diff --git a/src/librustc_mir/borrow_check/nll/type_check/liveness/local_use_map.rs b/src/librustc_mir/borrow_check/nll/type_check/liveness/local_use_map.rs index 3f13cc8b647..e9765d2798c 100644 --- a/src/librustc_mir/borrow_check/nll/type_check/liveness/local_use_map.rs +++ b/src/librustc_mir/borrow_check/nll/type_check/liveness/local_use_map.rs @@ -1,10 +1,10 @@ -use borrow_check::nll::region_infer::values::{PointIndex, RegionValueElements}; -use borrow_check::nll::type_check::liveness::liveness_map::{LiveVar, NllLivenessMap}; +use crate::borrow_check::nll::region_infer::values::{PointIndex, RegionValueElements}; +use crate::borrow_check::nll::type_check::liveness::liveness_map::{LiveVar, NllLivenessMap}; +use crate::util::liveness::{categorize, DefUse, LiveVariableMap}; use rustc::mir::visit::{PlaceContext, Visitor}; use rustc::mir::{Local, Location, Mir}; use rustc_data_structures::indexed_vec::{Idx, IndexVec}; use rustc_data_structures::vec_linked_list as vll; -use util::liveness::{categorize, DefUse, LiveVariableMap}; /// A map that cross references each local with the locations where it /// is defined (assigned), used, or dropped. Used during liveness diff --git a/src/librustc_mir/borrow_check/nll/type_check/liveness/mod.rs b/src/librustc_mir/borrow_check/nll/type_check/liveness/mod.rs index 633695a9b9c..a5510ba6936 100644 --- a/src/librustc_mir/borrow_check/nll/type_check/liveness/mod.rs +++ b/src/librustc_mir/borrow_check/nll/type_check/liveness/mod.rs @@ -1,11 +1,11 @@ -use borrow_check::location::LocationTable; -use borrow_check::nll::region_infer::values::RegionValueElements; -use borrow_check::nll::constraints::ConstraintSet; -use borrow_check::nll::NllLivenessMap; -use borrow_check::nll::universal_regions::UniversalRegions; -use dataflow::move_paths::MoveData; -use dataflow::MaybeInitializedPlaces; -use dataflow::FlowAtLocation; +use crate::borrow_check::location::LocationTable; +use crate::borrow_check::nll::region_infer::values::RegionValueElements; +use crate::borrow_check::nll::constraints::ConstraintSet; +use crate::borrow_check::nll::NllLivenessMap; +use crate::borrow_check::nll::universal_regions::UniversalRegions; +use crate::dataflow::move_paths::MoveData; +use crate::dataflow::MaybeInitializedPlaces; +use crate::dataflow::FlowAtLocation; use rustc::mir::Mir; use rustc::ty::RegionVid; use rustc_data_structures::fx::FxHashSet; diff --git a/src/librustc_mir/borrow_check/nll/type_check/liveness/trace.rs b/src/librustc_mir/borrow_check/nll/type_check/liveness/trace.rs index 77e8dd9d130..d058be03f55 100644 --- a/src/librustc_mir/borrow_check/nll/type_check/liveness/trace.rs +++ b/src/librustc_mir/borrow_check/nll/type_check/liveness/trace.rs @@ -1,12 +1,13 @@ -use borrow_check::location::LocationTable; -use borrow_check::nll::region_infer::values::{self, PointIndex, RegionValueElements}; -use borrow_check::nll::type_check::liveness::liveness_map::{LiveVar, NllLivenessMap}; -use borrow_check::nll::type_check::liveness::local_use_map::LocalUseMap; -use borrow_check::nll::type_check::NormalizeLocation; -use borrow_check::nll::type_check::TypeChecker; -use dataflow::move_paths::indexes::MovePathIndex; -use dataflow::move_paths::MoveData; -use dataflow::{FlowAtLocation, FlowsAtLocation, MaybeInitializedPlaces}; +use crate::borrow_check::location::LocationTable; +use crate::borrow_check::nll::region_infer::values::{self, PointIndex, RegionValueElements}; +use crate::borrow_check::nll::type_check::liveness::liveness_map::{LiveVar, NllLivenessMap}; +use crate::borrow_check::nll::type_check::liveness::local_use_map::LocalUseMap; +use crate::borrow_check::nll::type_check::NormalizeLocation; +use crate::borrow_check::nll::type_check::TypeChecker; +use crate::dataflow::move_paths::indexes::MovePathIndex; +use crate::dataflow::move_paths::MoveData; +use crate::dataflow::{FlowAtLocation, FlowsAtLocation, MaybeInitializedPlaces}; +use crate::util::liveness::LiveVariableMap; use rustc::infer::canonical::QueryRegionConstraint; use rustc::mir::{BasicBlock, ConstraintCategory, Local, Location, Mir}; use rustc::traits::query::dropck_outlives::DropckOutlivesResult; @@ -16,7 +17,6 @@ use rustc_data_structures::bit_set::HybridBitSet; use rustc_data_structures::fx::FxHashMap; use std::rc::Rc; -use util::liveness::LiveVariableMap; /// This is the heart of the liveness computation. For each variable X /// that requires a liveness computation, it walks over all the uses diff --git a/src/librustc_mir/borrow_check/nll/type_check/mod.rs b/src/librustc_mir/borrow_check/nll/type_check/mod.rs index 3e6aa358ee0..19ff47f9c39 100644 --- a/src/librustc_mir/borrow_check/nll/type_check/mod.rs +++ b/src/librustc_mir/borrow_check/nll/type_check/mod.rs @@ -2,24 +2,25 @@ #![allow(unreachable_code)] -use borrow_check::borrow_set::BorrowSet; -use borrow_check::location::LocationTable; -use borrow_check::nll::constraints::{ConstraintSet, OutlivesConstraint}; -use borrow_check::nll::facts::AllFacts; -use borrow_check::nll::region_infer::values::LivenessValues; -use borrow_check::nll::region_infer::values::PlaceholderIndex; -use borrow_check::nll::region_infer::values::PlaceholderIndices; -use borrow_check::nll::region_infer::values::RegionValueElements; -use borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest}; -use borrow_check::nll::renumber; -use borrow_check::nll::type_check::free_region_relations::{ +use crate::borrow_check::borrow_set::BorrowSet; +use crate::borrow_check::location::LocationTable; +use crate::borrow_check::nll::constraints::{ConstraintSet, OutlivesConstraint}; +use crate::borrow_check::nll::facts::AllFacts; +use crate::borrow_check::nll::region_infer::values::LivenessValues; +use crate::borrow_check::nll::region_infer::values::PlaceholderIndex; +use crate::borrow_check::nll::region_infer::values::PlaceholderIndices; +use crate::borrow_check::nll::region_infer::values::RegionValueElements; +use crate::borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest}; +use crate::borrow_check::nll::renumber; +use crate::borrow_check::nll::type_check::free_region_relations::{ CreateResult, UniversalRegionRelations, }; -use borrow_check::nll::universal_regions::{DefiningTy, UniversalRegions}; -use borrow_check::nll::ToRegionVid; -use dataflow::move_paths::MoveData; -use dataflow::FlowAtLocation; -use dataflow::MaybeInitializedPlaces; +use crate::borrow_check::nll::universal_regions::{DefiningTy, UniversalRegions}; +use crate::borrow_check::nll::ToRegionVid; +use crate::dataflow::move_paths::MoveData; +use crate::dataflow::FlowAtLocation; +use crate::dataflow::MaybeInitializedPlaces; +use crate::transform::{MirPass, MirSource}; use either::Either; use rustc::hir; use rustc::hir::def_id::DefId; @@ -46,7 +47,6 @@ use std::rc::Rc; use std::{fmt, iter}; use syntax_pos::{Span, DUMMY_SP}; -use transform::{MirPass, MirSource}; macro_rules! span_mirbug { ($context:expr, $elem:expr, $($message:tt)*) => ({ @@ -210,7 +210,7 @@ fn type_check_internal<'a, 'gcx, 'tcx, R>( extra(&mut checker) } -fn translate_outlives_facts(cx: &mut BorrowCheckContext) { +fn translate_outlives_facts(cx: &mut BorrowCheckContext<'_, '_>) { if let Some(facts) = cx.all_facts { let location_table = cx.location_table; facts @@ -235,7 +235,7 @@ fn translate_outlives_facts(cx: &mut BorrowCheckContext) { } } -fn mirbug(tcx: TyCtxt, span: Span, msg: &str) { +fn mirbug(tcx: TyCtxt<'_, '_, '_>, span: Span, msg: &str) { // We sometimes see MIR failures (notably predicate failures) due to // the fact that we check rvalue sized predicates here. So use `delay_span_bug` // to avoid reporting bugs in those cases. @@ -266,7 +266,7 @@ fn visit_span(&mut self, span: &Span) { } } - fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) { + fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext<'_>, location: Location) { self.sanitize_place(place, location, context); } @@ -447,7 +447,7 @@ fn sanitize_place( &mut self, place: &Place<'tcx>, location: Location, - context: PlaceContext, + context: PlaceContext<'_>, ) -> PlaceTy<'tcx> { debug!("sanitize_place: {:?}", place); let place_ty = match *place { diff --git a/src/librustc_mir/borrow_check/nll/type_check/relate_tys.rs b/src/librustc_mir/borrow_check/nll/type_check/relate_tys.rs index 74ad7d988cc..1748e300890 100644 --- a/src/librustc_mir/borrow_check/nll/type_check/relate_tys.rs +++ b/src/librustc_mir/borrow_check/nll/type_check/relate_tys.rs @@ -1,5 +1,5 @@ -use borrow_check::nll::constraints::OutlivesConstraint; -use borrow_check::nll::type_check::{BorrowCheckContext, Locations}; +use crate::borrow_check::nll::constraints::OutlivesConstraint; +use crate::borrow_check::nll::type_check::{BorrowCheckContext, Locations}; use rustc::infer::nll_relate::{TypeRelating, TypeRelatingDelegate, NormalizationStrategy}; use rustc::infer::{InferCtxt, NLLRegionVariableOrigin}; use rustc::mir::ConstraintCategory; diff --git a/src/librustc_mir/borrow_check/path_utils.rs b/src/librustc_mir/borrow_check/path_utils.rs index 6875aced8d2..1cea9f662d3 100644 --- a/src/librustc_mir/borrow_check/path_utils.rs +++ b/src/librustc_mir/borrow_check/path_utils.rs @@ -1,8 +1,8 @@ -use borrow_check::borrow_set::{BorrowSet, BorrowData, TwoPhaseActivation}; -use borrow_check::places_conflict; -use borrow_check::Context; -use borrow_check::AccessDepth; -use dataflow::indexes::BorrowIndex; +use crate::borrow_check::borrow_set::{BorrowSet, BorrowData, TwoPhaseActivation}; +use crate::borrow_check::places_conflict; +use crate::borrow_check::Context; +use crate::borrow_check::AccessDepth; +use crate::dataflow::indexes::BorrowIndex; use rustc::mir::{BasicBlock, Location, Mir, Place}; use rustc::mir::{ProjectionElem, BorrowKind}; use rustc::ty::TyCtxt; diff --git a/src/librustc_mir/borrow_check/place_ext.rs b/src/librustc_mir/borrow_check/place_ext.rs index 4d0b25b1024..bad236a6f52 100644 --- a/src/librustc_mir/borrow_check/place_ext.rs +++ b/src/librustc_mir/borrow_check/place_ext.rs @@ -2,7 +2,7 @@ use rustc::mir::ProjectionElem; use rustc::mir::{Local, Mir, Place, Mutability}; use rustc::ty::{self, TyCtxt}; -use borrow_check::borrow_set::LocalsStateAtExit; +use crate::borrow_check::borrow_set::LocalsStateAtExit; /// Extension methods for the `Place` type. crate trait PlaceExt<'tcx> { diff --git a/src/librustc_mir/borrow_check/places_conflict.rs b/src/librustc_mir/borrow_check/places_conflict.rs index ac7182abb36..cd33f22bf3c 100644 --- a/src/librustc_mir/borrow_check/places_conflict.rs +++ b/src/librustc_mir/borrow_check/places_conflict.rs @@ -1,6 +1,6 @@ -use borrow_check::ArtificialField; -use borrow_check::Overlap; -use borrow_check::{Deep, Shallow, AccessDepth}; +use crate::borrow_check::ArtificialField; +use crate::borrow_check::Overlap; +use crate::borrow_check::{Deep, Shallow, AccessDepth}; use rustc::hir; use rustc::mir::{BorrowKind, Mir, Place}; use rustc::mir::{Projection, ProjectionElem}; diff --git a/src/librustc_mir/borrow_check/used_muts.rs b/src/librustc_mir/borrow_check/used_muts.rs index 0ff7ff4de10..8c7359bdee7 100644 --- a/src/librustc_mir/borrow_check/used_muts.rs +++ b/src/librustc_mir/borrow_check/used_muts.rs @@ -3,7 +3,7 @@ use rustc_data_structures::fx::FxHashSet; -use borrow_check::MirBorrowckCtxt; +use crate::borrow_check::MirBorrowckCtxt; impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> { /// Walks the MIR adding to the set of `used_mut` locals that will be ignored for the purposes diff --git a/src/librustc_mir/build/block.rs b/src/librustc_mir/build/block.rs index f3d89a7a025..7d93e131a6c 100644 --- a/src/librustc_mir/build/block.rs +++ b/src/librustc_mir/build/block.rs @@ -1,7 +1,7 @@ -use build::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; -use build::ForGuard::OutsideGuard; -use build::matches::ArmHasGuard; -use hair::*; +use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; +use crate::build::ForGuard::OutsideGuard; +use crate::build::matches::ArmHasGuard; +use crate::hair::*; use rustc::mir::*; use rustc::hir; use syntax_pos::Span; diff --git a/src/librustc_mir/build/cfg.rs b/src/librustc_mir/build/cfg.rs index a9e468db1d1..778d1e71ced 100644 --- a/src/librustc_mir/build/cfg.rs +++ b/src/librustc_mir/build/cfg.rs @@ -1,6 +1,6 @@ //! Routines for manipulating the control-flow graph. -use build::CFG; +use crate::build::CFG; use rustc::mir::*; impl<'tcx> CFG<'tcx> { diff --git a/src/librustc_mir/build/expr/as_constant.rs b/src/librustc_mir/build/expr/as_constant.rs index 31e0c0daa3f..614668170d5 100644 --- a/src/librustc_mir/build/expr/as_constant.rs +++ b/src/librustc_mir/build/expr/as_constant.rs @@ -1,7 +1,7 @@ //! See docs in build/expr/mod.rs -use build::Builder; -use hair::*; +use crate::build::Builder; +use crate::hair::*; use rustc::mir::*; use rustc::ty::CanonicalUserTypeAnnotation; diff --git a/src/librustc_mir/build/expr/as_operand.rs b/src/librustc_mir/build/expr/as_operand.rs index 1f653575a7f..38fae8539c8 100644 --- a/src/librustc_mir/build/expr/as_operand.rs +++ b/src/librustc_mir/build/expr/as_operand.rs @@ -1,8 +1,8 @@ //! See docs in build/expr/mod.rs -use build::expr::category::Category; -use build::{BlockAnd, BlockAndExtension, Builder}; -use hair::*; +use crate::build::expr::category::Category; +use crate::build::{BlockAnd, BlockAndExtension, Builder}; +use crate::hair::*; use rustc::middle::region; use rustc::mir::*; diff --git a/src/librustc_mir/build/expr/as_place.rs b/src/librustc_mir/build/expr/as_place.rs index 6bd61ab53fd..ed444191226 100644 --- a/src/librustc_mir/build/expr/as_place.rs +++ b/src/librustc_mir/build/expr/as_place.rs @@ -1,9 +1,9 @@ //! See docs in build/expr/mod.rs -use build::expr::category::Category; -use build::ForGuard::{OutsideGuard, RefWithinGuard}; -use build::{BlockAnd, BlockAndExtension, Builder}; -use hair::*; +use crate::build::expr::category::Category; +use crate::build::ForGuard::{OutsideGuard, RefWithinGuard}; +use crate::build::{BlockAnd, BlockAndExtension, Builder}; +use crate::hair::*; use rustc::mir::interpret::EvalErrorKind::BoundsCheck; use rustc::mir::*; use rustc::ty::{CanonicalUserTypeAnnotation, Variance}; diff --git a/src/librustc_mir/build/expr/as_rvalue.rs b/src/librustc_mir/build/expr/as_rvalue.rs index 3de2f475786..88dbd93939e 100644 --- a/src/librustc_mir/build/expr/as_rvalue.rs +++ b/src/librustc_mir/build/expr/as_rvalue.rs @@ -3,9 +3,9 @@ use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::indexed_vec::Idx; -use build::expr::category::{Category, RvalueFunc}; -use build::{BlockAnd, BlockAndExtension, Builder}; -use hair::*; +use crate::build::expr::category::{Category, RvalueFunc}; +use crate::build::{BlockAnd, BlockAndExtension, Builder}; +use crate::hair::*; use rustc::middle::region; use rustc::mir::interpret::EvalErrorKind; use rustc::mir::*; @@ -268,7 +268,7 @@ fn expr_as_rvalue( span: expr_span, ty: this.hir.tcx().types.u32, user_ty: None, - literal: this.hir.tcx().intern_lazy_const(ty::LazyConst::Evaluated( + literal: this.hir.tcx().mk_lazy_const(ty::LazyConst::Evaluated( ty::Const::from_bits( this.hir.tcx(), 0, diff --git a/src/librustc_mir/build/expr/as_temp.rs b/src/librustc_mir/build/expr/as_temp.rs index df271ff6e40..efa1a4895e0 100644 --- a/src/librustc_mir/build/expr/as_temp.rs +++ b/src/librustc_mir/build/expr/as_temp.rs @@ -1,7 +1,7 @@ //! See docs in build/expr/mod.rs -use build::{BlockAnd, BlockAndExtension, Builder}; -use hair::*; +use crate::build::{BlockAnd, BlockAndExtension, Builder}; +use crate::hair::*; use rustc::middle::region; use rustc::mir::*; diff --git a/src/librustc_mir/build/expr/category.rs b/src/librustc_mir/build/expr/category.rs index 53f84a49569..ca7d435e622 100644 --- a/src/librustc_mir/build/expr/category.rs +++ b/src/librustc_mir/build/expr/category.rs @@ -1,4 +1,4 @@ -use hair::*; +use crate::hair::*; #[derive(Debug, PartialEq)] pub enum Category { diff --git a/src/librustc_mir/build/expr/into.rs b/src/librustc_mir/build/expr/into.rs index 2ffff68137d..05231bc7b3f 100644 --- a/src/librustc_mir/build/expr/into.rs +++ b/src/librustc_mir/build/expr/into.rs @@ -1,8 +1,8 @@ //! See docs in build/expr/mod.rs -use build::expr::category::{Category, RvalueFunc}; -use build::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; -use hair::*; +use crate::build::expr::category::{Category, RvalueFunc}; +use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; +use crate::hair::*; use rustc::mir::*; use rustc::ty; diff --git a/src/librustc_mir/build/expr/stmt.rs b/src/librustc_mir/build/expr/stmt.rs index 1cbc60586c3..aadc2368f5a 100644 --- a/src/librustc_mir/build/expr/stmt.rs +++ b/src/librustc_mir/build/expr/stmt.rs @@ -1,6 +1,6 @@ -use build::scope::BreakableScope; -use build::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; -use hair::*; +use crate::build::scope::BreakableScope; +use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; +use crate::hair::*; use rustc::mir::*; impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { diff --git a/src/librustc_mir/build/into.rs b/src/librustc_mir/build/into.rs index 1b291260820..67b6540febe 100644 --- a/src/librustc_mir/build/into.rs +++ b/src/librustc_mir/build/into.rs @@ -4,11 +4,11 @@ //! wrapped up as expressions (e.g., blocks). To make this ergonomic, we use this //! latter `EvalInto` trait. -use build::{BlockAnd, Builder}; -use hair::*; +use crate::build::{BlockAnd, Builder}; +use crate::hair::*; use rustc::mir::*; -pub(in build) trait EvalInto<'tcx> { +pub(in crate::build) trait EvalInto<'tcx> { fn eval_into<'a, 'gcx>(self, builder: &mut Builder<'a, 'gcx, 'tcx>, destination: &Place<'tcx>, diff --git a/src/librustc_mir/build/matches/mod.rs b/src/librustc_mir/build/matches/mod.rs index 2f1e8c03f2f..cf051ba2e0f 100644 --- a/src/librustc_mir/build/matches/mod.rs +++ b/src/librustc_mir/build/matches/mod.rs @@ -3,11 +3,11 @@ //! includes the high-level algorithm, the submodules contain the //! details. -use build::scope::{CachedBlock, DropKind}; -use build::ForGuard::{self, OutsideGuard, RefWithinGuard, ValWithinGuard}; -use build::{BlockAnd, BlockAndExtension, Builder}; -use build::{GuardFrame, GuardFrameLocal, LocalsForNode}; -use hair::*; +use crate::build::scope::{CachedBlock, DropKind}; +use crate::build::ForGuard::{self, OutsideGuard, RefWithinGuard, ValWithinGuard}; +use crate::build::{BlockAnd, BlockAndExtension, Builder}; +use crate::build::{GuardFrame, GuardFrameLocal, LocalsForNode}; +use crate::hair::*; use rustc::mir::*; use rustc::ty::{self, CanonicalUserTypeAnnotation, Ty}; use rustc::ty::layout::VariantIdx; diff --git a/src/librustc_mir/build/matches/simplify.rs b/src/librustc_mir/build/matches/simplify.rs index c219fd22182..6be9ccb2703 100644 --- a/src/librustc_mir/build/matches/simplify.rs +++ b/src/librustc_mir/build/matches/simplify.rs @@ -12,9 +12,9 @@ //! sort of test: for example, testing which variant an enum is, or //! testing a value against a constant. -use build::Builder; -use build::matches::{Ascription, Binding, MatchPair, Candidate}; -use hair::*; +use crate::build::Builder; +use crate::build::matches::{Ascription, Binding, MatchPair, Candidate}; +use crate::hair::*; use rustc::ty; use rustc::ty::layout::{Integer, IntegerExt, Size}; use syntax::attr::{SignedInt, UnsignedInt}; diff --git a/src/librustc_mir/build/matches/test.rs b/src/librustc_mir/build/matches/test.rs index 696c173b048..efac4457b8e 100644 --- a/src/librustc_mir/build/matches/test.rs +++ b/src/librustc_mir/build/matches/test.rs @@ -5,10 +5,10 @@ // identify what tests are needed, perform the tests, and then filter // the candidates based on the result. -use build::Builder; -use build::matches::{Candidate, MatchPair, Test, TestKind}; -use hair::*; -use hair::pattern::compare_const_vals; +use crate::build::Builder; +use crate::build::matches::{Candidate, MatchPair, Test, TestKind}; +use crate::hair::*; +use crate::hair::pattern::compare_const_vals; use rustc_data_structures::bit_set::BitSet; use rustc_data_structures::fx::FxHashMap; use rustc::ty::{self, Ty}; @@ -302,7 +302,7 @@ pub fn perform_test(&mut self, } let eq_def_id = self.hir.tcx().lang_items().eq_trait().unwrap(); let (mty, method) = self.hir.trait_method(eq_def_id, "eq", ty, &[ty.into()]); - let method = self.hir.tcx().intern_lazy_const(ty::LazyConst::Evaluated(method)); + let method = self.hir.tcx().mk_lazy_const(ty::LazyConst::Evaluated(method)); let re_erased = self.hir.tcx().types.re_erased; // take the argument by reference diff --git a/src/librustc_mir/build/matches/util.rs b/src/librustc_mir/build/matches/util.rs index b5a1a388e9c..ed12c1b3bc9 100644 --- a/src/librustc_mir/build/matches/util.rs +++ b/src/librustc_mir/build/matches/util.rs @@ -1,6 +1,6 @@ -use build::Builder; -use build::matches::MatchPair; -use hair::*; +use crate::build::Builder; +use crate::build::matches::MatchPair; +use crate::hair::*; use rustc::mir::*; use std::u32; use std::convert::TryInto; diff --git a/src/librustc_mir/build/misc.rs b/src/librustc_mir/build/misc.rs index c849c022428..096020b0f73 100644 --- a/src/librustc_mir/build/misc.rs +++ b/src/librustc_mir/build/misc.rs @@ -1,7 +1,7 @@ //! Miscellaneous builder routines that are not specific to building any particular //! kind of thing. -use build::Builder; +use crate::build::Builder; use rustc::ty::{self, Ty}; @@ -33,7 +33,7 @@ pub fn literal_operand(&mut self, span, ty, user_ty: None, - literal: self.hir.tcx().intern_lazy_const(ty::LazyConst::Evaluated(literal)), + literal: self.hir.tcx().mk_lazy_const(ty::LazyConst::Evaluated(literal)), }; Operand::Constant(constant) } diff --git a/src/librustc_mir/build/mod.rs b/src/librustc_mir/build/mod.rs index f38648fda0e..a52b032aeb5 100644 --- a/src/librustc_mir/build/mod.rs +++ b/src/librustc_mir/build/mod.rs @@ -1,7 +1,10 @@ -use build; -use build::scope::{CachedBlock, DropKind}; -use hair::cx::Cx; -use hair::{LintLevel, BindingMode, PatternKind}; +use crate::build; +use crate::build::scope::{CachedBlock, DropKind}; +use crate::hair::cx::Cx; +use crate::hair::{LintLevel, BindingMode, PatternKind}; +use crate::shim; +use crate::transform::MirSource; +use crate::util as mir_util; use rustc::hir; use rustc::hir::Node; use rustc::hir::def_id::DefId; @@ -13,7 +16,6 @@ use rustc::util::nodemap::NodeMap; use rustc_target::spec::PanicStrategy; use rustc_data_structures::indexed_vec::{IndexVec, Idx}; -use shim; use std::mem; use std::u32; use rustc_target::spec::abi::Abi; @@ -21,8 +23,6 @@ use syntax::attr::{self, UnwindAttr}; use syntax::symbol::keywords; use syntax_pos::Span; -use transform::MirSource; -use util as mir_util; use super::lints; @@ -161,7 +161,7 @@ pub fn mir_build<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Mir<'t }; globalizer.visit_mir(&mut mir); let mir = unsafe { - mem::transmute::>(mir) + mem::transmute::, Mir<'tcx>>(mir) }; mir_util::dump_mir(tcx, None, "mir_map", &0, @@ -241,7 +241,7 @@ fn create_constructor_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, }; globalizer.visit_mir(&mut mir); let mir = unsafe { - mem::transmute::>(mir) + mem::transmute::, Mir<'tcx>>(mir) }; mir_util::dump_mir(tcx, None, "mir_map", &0, diff --git a/src/librustc_mir/build/scope.rs b/src/librustc_mir/build/scope.rs index 78abba5f885..3872f5db262 100644 --- a/src/librustc_mir/build/scope.rs +++ b/src/librustc_mir/build/scope.rs @@ -77,8 +77,8 @@ */ -use build::{BlockAnd, BlockAndExtension, Builder, CFG}; -use hair::LintLevel; +use crate::build::{BlockAnd, BlockAndExtension, Builder, CFG}; +use crate::hair::LintLevel; use rustc::middle::region; use rustc::ty::Ty; use rustc::hir; diff --git a/src/librustc_mir/const_eval.rs b/src/librustc_mir/const_eval.rs index f83a930353b..d1b4486dd93 100644 --- a/src/librustc_mir/const_eval.rs +++ b/src/librustc_mir/const_eval.rs @@ -190,7 +190,7 @@ enum ConstEvalError { } impl fmt::Display for ConstEvalError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use self::ConstEvalError::*; match *self { NeedsRfc(ref msg) => { diff --git a/src/librustc_mir/dataflow/at_location.rs b/src/librustc_mir/dataflow/at_location.rs index 375bc4fead4..d0b9fbc99f0 100644 --- a/src/librustc_mir/dataflow/at_location.rs +++ b/src/librustc_mir/dataflow/at_location.rs @@ -4,8 +4,8 @@ use rustc::mir::{BasicBlock, Location}; use rustc_data_structures::bit_set::{BitIter, BitSet, HybridBitSet}; -use dataflow::{BitDenotation, BlockSets, DataflowResults}; -use dataflow::move_paths::{HasMoveData, MovePathIndex}; +use crate::dataflow::{BitDenotation, BlockSets, DataflowResults}; +use crate::dataflow::move_paths::{HasMoveData, MovePathIndex}; use std::iter; @@ -115,7 +115,7 @@ pub fn contains(&self, x: BD::Idx) -> bool { } /// Returns an iterator over the elements present in the current state. - pub fn iter_incoming(&self) -> iter::Peekable> { + pub fn iter_incoming(&self) -> iter::Peekable> { self.curr_state.iter().peekable() } @@ -124,7 +124,7 @@ pub fn iter_incoming(&self) -> iter::Peekable> { /// Invokes `f` with an iterator over the resulting state. pub fn with_iter_outgoing(&self, f: F) where - F: FnOnce(BitIter), + F: FnOnce(BitIter<'_, BD::Idx>), { let mut curr_state = self.curr_state.clone(); curr_state.union(&self.stmt_gen); diff --git a/src/librustc_mir/dataflow/drop_flag_effects.rs b/src/librustc_mir/dataflow/drop_flag_effects.rs index 22fb7a3bc47..49499cf928d 100644 --- a/src/librustc_mir/dataflow/drop_flag_effects.rs +++ b/src/librustc_mir/dataflow/drop_flag_effects.rs @@ -1,6 +1,6 @@ use rustc::mir::{self, Mir, Location}; use rustc::ty::{self, TyCtxt}; -use util::elaborate_drops::DropFlagState; +use crate::util::elaborate_drops::DropFlagState; use super::{MoveDataParamEnv}; use super::indexes::MovePathIndex; diff --git a/src/librustc_mir/dataflow/graphviz.rs b/src/librustc_mir/dataflow/graphviz.rs index 34752baa020..9d9f18d4b0d 100644 --- a/src/librustc_mir/dataflow/graphviz.rs +++ b/src/librustc_mir/dataflow/graphviz.rs @@ -3,8 +3,6 @@ use syntax::ast::NodeId; use rustc::mir::{BasicBlock, Mir}; -use dot; - use std::fs; use std::io; use std::marker::PhantomData; @@ -59,7 +57,7 @@ pub(crate) fn print_borrowck_graph_to<'a, 'tcx, BD, P>( #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct Edge { source: BasicBlock, index: usize } -fn outgoing(mir: &Mir, bb: BasicBlock) -> Vec { +fn outgoing(mir: &Mir<'_>, bb: BasicBlock) -> Vec { (0..mir[bb].terminator().successors().count()) .map(|index| Edge { source: bb, index: index}).collect() } @@ -70,18 +68,18 @@ impl<'a, 'tcx, MWF, P> dot::Labeller<'a> for Graph<'a, 'tcx, MWF, P> { type Node = Node; type Edge = Edge; - fn graph_id(&self) -> dot::Id { + fn graph_id(&self) -> dot::Id<'_> { dot::Id::new(format!("graph_for_node_{}", self.mbcx.node_id())) .unwrap() } - fn node_id(&self, n: &Node) -> dot::Id { + fn node_id(&self, n: &Node) -> dot::Id<'_> { dot::Id::new(format!("bb_{}", n.index())) .unwrap() } - fn node_label(&self, n: &Node) -> dot::LabelText { + fn node_label(&self, n: &Node) -> dot::LabelText<'_> { // Node label is something like this: // +---------+----------------------------------+------------------+------------------+ // | ENTRY | MIR | GEN | KILL | @@ -105,7 +103,7 @@ fn node_label(&self, n: &Node) -> dot::LabelText { } - fn node_shape(&self, _n: &Node) -> Option { + fn node_shape(&self, _n: &Node) -> Option> { Some(dot::LabelText::label("none")) } @@ -125,7 +123,7 @@ fn node_label_internal(&self, n: &Node, w: &mut W, block: BasicBlock, - mir: &Mir) -> io::Result<()> { + mir: &Mir<'_>) -> io::Result<()> { // Header rows const HDRS: [&str; 4] = ["ENTRY", "MIR", "BLOCK GENS", "BLOCK KILLS"]; const HDR_FMT: &str = "bgcolor=\"grey\""; @@ -150,7 +148,7 @@ fn node_label_verbose_row(&self, n: &Node, w: &mut W, block: BasicBlock, - mir: &Mir) + mir: &Mir<'_>) -> io::Result<()> { let i = n.index(); @@ -200,7 +198,7 @@ fn node_label_final_row(&self, n: &Node, w: &mut W, block: BasicBlock, - mir: &Mir) + mir: &Mir<'_>) -> io::Result<()> { let i = n.index(); @@ -241,7 +239,7 @@ impl<'a, 'tcx, MWF, P> dot::GraphWalk<'a> for Graph<'a, 'tcx, MWF, P> { type Node = Node; type Edge = Edge; - fn nodes(&self) -> dot::Nodes { + fn nodes(&self) -> dot::Nodes<'_, Node> { self.mbcx.mir() .basic_blocks() .indices() @@ -249,7 +247,7 @@ fn nodes(&self) -> dot::Nodes { .into() } - fn edges(&self) -> dot::Edges { + fn edges(&self) -> dot::Edges<'_, Edge> { let mir = self.mbcx.mir(); mir.basic_blocks() diff --git a/src/librustc_mir/dataflow/impls/borrowed_locals.rs b/src/librustc_mir/dataflow/impls/borrowed_locals.rs index 9d03e35a350..51d628ce6c5 100644 --- a/src/librustc_mir/dataflow/impls/borrowed_locals.rs +++ b/src/librustc_mir/dataflow/impls/borrowed_locals.rs @@ -2,7 +2,7 @@ use rustc::mir::*; use rustc::mir::visit::Visitor; -use dataflow::BitDenotation; +use crate::dataflow::BitDenotation; /// This calculates if any part of a MIR local could have previously been borrowed. /// This means that once a local has been borrowed, its bit will be set @@ -38,7 +38,7 @@ fn start_block_effect(&self, _sets: &mut BitSet) { } fn statement_effect(&self, - sets: &mut BlockSets, + sets: &mut BlockSets<'_, Local>, loc: Location) { let stmt = &self.mir[loc.block].statements[loc.statement_index]; @@ -54,7 +54,7 @@ fn statement_effect(&self, } fn terminator_effect(&self, - sets: &mut BlockSets, + sets: &mut BlockSets<'_, Local>, loc: Location) { BorrowedLocalsVisitor { sets, diff --git a/src/librustc_mir/dataflow/impls/borrows.rs b/src/librustc_mir/dataflow/impls/borrows.rs index 72218e29cfd..beb0b318708 100644 --- a/src/librustc_mir/dataflow/impls/borrows.rs +++ b/src/librustc_mir/dataflow/impls/borrows.rs @@ -1,5 +1,5 @@ -use borrow_check::borrow_set::{BorrowSet, BorrowData}; -use borrow_check::place_ext::PlaceExt; +use crate::borrow_check::borrow_set::{BorrowSet, BorrowData}; +use crate::borrow_check::place_ext::PlaceExt; use rustc::mir::{self, Location, Place, Mir}; use rustc::ty::TyCtxt; @@ -9,11 +9,11 @@ use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::indexed_vec::{Idx, IndexVec}; -use dataflow::{BitDenotation, BlockSets, InitialFlow}; -pub use dataflow::indexes::BorrowIndex; -use borrow_check::nll::region_infer::RegionInferenceContext; -use borrow_check::nll::ToRegionVid; -use borrow_check::places_conflict; +use crate::dataflow::{BitDenotation, BlockSets, InitialFlow}; +pub use crate::dataflow::indexes::BorrowIndex; +use crate::borrow_check::nll::region_infer::RegionInferenceContext; +use crate::borrow_check::nll::ToRegionVid; +use crate::borrow_check::places_conflict; use std::rc::Rc; @@ -163,7 +163,7 @@ pub fn location(&self, idx: BorrowIndex) -> &Location { /// Add all borrows to the kill set, if those borrows are out of scope at `location`. /// That means they went out of a nonlexical scope fn kill_loans_out_of_scope_at_location(&self, - sets: &mut BlockSets, + sets: &mut BlockSets<'_, BorrowIndex>, location: Location) { // NOTE: The state associated with a given `location` // reflects the dataflow on entry to the statement. @@ -184,7 +184,7 @@ fn kill_loans_out_of_scope_at_location(&self, /// Kill any borrows that conflict with `place`. fn kill_borrows_on_place( &self, - sets: &mut BlockSets, + sets: &mut BlockSets<'_, BorrowIndex>, place: &Place<'tcx> ) { debug!("kill_borrows_on_place: place={:?}", place); @@ -243,13 +243,13 @@ fn start_block_effect(&self, _entry_set: &mut BitSet) { } fn before_statement_effect(&self, - sets: &mut BlockSets, + sets: &mut BlockSets<'_, BorrowIndex>, location: Location) { debug!("Borrows::before_statement_effect sets: {:?} location: {:?}", sets, location); self.kill_loans_out_of_scope_at_location(sets, location); } - fn statement_effect(&self, sets: &mut BlockSets, location: Location) { + fn statement_effect(&self, sets: &mut BlockSets<'_, BorrowIndex>, location: Location) { debug!("Borrows::statement_effect: sets={:?} location={:?}", sets, location); let block = &self.mir.basic_blocks().get(location.block).unwrap_or_else(|| { @@ -307,13 +307,13 @@ fn statement_effect(&self, sets: &mut BlockSets, location: Location } fn before_terminator_effect(&self, - sets: &mut BlockSets, + sets: &mut BlockSets<'_, BorrowIndex>, location: Location) { debug!("Borrows::before_terminator_effect sets: {:?} location: {:?}", sets, location); self.kill_loans_out_of_scope_at_location(sets, location); } - fn terminator_effect(&self, _: &mut BlockSets, _: Location) {} + fn terminator_effect(&self, _: &mut BlockSets<'_, BorrowIndex>, _: Location) {} fn propagate_call_return( &self, diff --git a/src/librustc_mir/dataflow/impls/mod.rs b/src/librustc_mir/dataflow/impls/mod.rs index 1ccda3a12e4..c8965b9f7f4 100644 --- a/src/librustc_mir/dataflow/impls/mod.rs +++ b/src/librustc_mir/dataflow/impls/mod.rs @@ -9,7 +9,7 @@ use super::MoveDataParamEnv; -use util::elaborate_drops::DropFlagState; +use crate::util::elaborate_drops::DropFlagState; use super::move_paths::{HasMoveData, MoveData, MovePathIndex, InitIndex}; use super::move_paths::{LookupResult, InitKind}; @@ -251,7 +251,7 @@ fn move_data(&self) -> &MoveData<'tcx> { &self.mdpe.move_data } impl<'a, 'gcx, 'tcx> MaybeInitializedPlaces<'a, 'gcx, 'tcx> { - fn update_bits(sets: &mut BlockSets, path: MovePathIndex, + fn update_bits(sets: &mut BlockSets<'_, MovePathIndex>, path: MovePathIndex, state: DropFlagState) { match state { @@ -262,7 +262,7 @@ fn update_bits(sets: &mut BlockSets, path: MovePathIndex, } impl<'a, 'gcx, 'tcx> MaybeUninitializedPlaces<'a, 'gcx, 'tcx> { - fn update_bits(sets: &mut BlockSets, path: MovePathIndex, + fn update_bits(sets: &mut BlockSets<'_, MovePathIndex>, path: MovePathIndex, state: DropFlagState) { match state { @@ -273,7 +273,7 @@ fn update_bits(sets: &mut BlockSets, path: MovePathIndex, } impl<'a, 'gcx, 'tcx> DefinitelyInitializedPlaces<'a, 'gcx, 'tcx> { - fn update_bits(sets: &mut BlockSets, path: MovePathIndex, + fn update_bits(sets: &mut BlockSets<'_, MovePathIndex>, path: MovePathIndex, state: DropFlagState) { match state { @@ -300,7 +300,7 @@ fn start_block_effect(&self, entry_set: &mut BitSet) { } fn statement_effect(&self, - sets: &mut BlockSets, + sets: &mut BlockSets<'_, MovePathIndex>, location: Location) { drop_flag_effects_for_location( @@ -311,7 +311,7 @@ fn statement_effect(&self, } fn terminator_effect(&self, - sets: &mut BlockSets, + sets: &mut BlockSets<'_, MovePathIndex>, location: Location) { drop_flag_effects_for_location( @@ -358,7 +358,7 @@ fn start_block_effect(&self, entry_set: &mut BitSet) { } fn statement_effect(&self, - sets: &mut BlockSets, + sets: &mut BlockSets<'_, MovePathIndex>, location: Location) { drop_flag_effects_for_location( @@ -369,7 +369,7 @@ fn statement_effect(&self, } fn terminator_effect(&self, - sets: &mut BlockSets, + sets: &mut BlockSets<'_, MovePathIndex>, location: Location) { drop_flag_effects_for_location( @@ -414,7 +414,7 @@ fn start_block_effect(&self, entry_set: &mut BitSet) { } fn statement_effect(&self, - sets: &mut BlockSets, + sets: &mut BlockSets<'_, MovePathIndex>, location: Location) { drop_flag_effects_for_location( @@ -425,7 +425,7 @@ fn statement_effect(&self, } fn terminator_effect(&self, - sets: &mut BlockSets, + sets: &mut BlockSets<'_, MovePathIndex>, location: Location) { drop_flag_effects_for_location( @@ -464,7 +464,7 @@ fn start_block_effect(&self, entry_set: &mut BitSet) { } fn statement_effect(&self, - sets: &mut BlockSets, + sets: &mut BlockSets<'_, InitIndex>, location: Location) { let (_, mir, move_data) = (self.tcx, self.mir, self.move_data()); let stmt = &mir[location.block].statements[location.statement_index]; @@ -511,7 +511,7 @@ fn statement_effect(&self, } fn terminator_effect(&self, - sets: &mut BlockSets, + sets: &mut BlockSets<'_, InitIndex>, location: Location) { let (mir, move_data) = (self.mir, self.move_data()); diff --git a/src/librustc_mir/dataflow/impls/storage_liveness.rs b/src/librustc_mir/dataflow/impls/storage_liveness.rs index 9c17076e6fd..6b8eb6f17f6 100644 --- a/src/librustc_mir/dataflow/impls/storage_liveness.rs +++ b/src/librustc_mir/dataflow/impls/storage_liveness.rs @@ -1,7 +1,7 @@ pub use super::*; use rustc::mir::*; -use dataflow::BitDenotation; +use crate::dataflow::BitDenotation; #[derive(Copy, Clone)] pub struct MaybeStorageLive<'a, 'tcx: 'a> { @@ -31,7 +31,7 @@ fn start_block_effect(&self, _sets: &mut BitSet) { } fn statement_effect(&self, - sets: &mut BlockSets, + sets: &mut BlockSets<'_, Local>, loc: Location) { let stmt = &self.mir[loc.block].statements[loc.statement_index]; @@ -43,7 +43,7 @@ fn statement_effect(&self, } fn terminator_effect(&self, - _sets: &mut BlockSets, + _sets: &mut BlockSets<'_, Local>, _loc: Location) { // Terminators have no effect } diff --git a/src/librustc_mir/dataflow/mod.rs b/src/librustc_mir/dataflow/mod.rs index f09db970b73..1853b60efd7 100644 --- a/src/librustc_mir/dataflow/mod.rs +++ b/src/librustc_mir/dataflow/mod.rs @@ -58,7 +58,7 @@ pub fn new(input: &dyn fmt::Debug) -> DebugFormatted { } impl fmt::Debug for DebugFormatted { - fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result { write!(w, "{}", self.0) } } @@ -525,7 +525,7 @@ fn apply_local_effect(&mut self) { impl AllSets { pub fn bits_per_block(&self) -> usize { self.bits_per_block } - pub fn for_block(&mut self, block_idx: usize) -> BlockSets { + pub fn for_block(&mut self, block_idx: usize) -> BlockSets<'_, E> { BlockSets { on_entry: &mut self.on_entry_sets[block_idx], gen_set: &mut self.gen_sets[block_idx], @@ -616,7 +616,7 @@ fn accumulates_intrablock_state() -> bool { false } /// applied, in that order, before moving for the next /// statement. fn before_statement_effect(&self, - _sets: &mut BlockSets, + _sets: &mut BlockSets<'_, Self::Idx>, _location: Location) {} /// Mutates the block-sets (the flow sets for the given @@ -630,7 +630,7 @@ fn before_statement_effect(&self, /// `bb_data` is the sequence of statements identified by `bb` in /// the MIR. fn statement_effect(&self, - sets: &mut BlockSets, + sets: &mut BlockSets<'_, Self::Idx>, location: Location); /// Similar to `terminator_effect`, except it applies @@ -645,7 +645,7 @@ fn statement_effect(&self, /// applied, in that order, before moving for the next /// terminator. fn before_terminator_effect(&self, - _sets: &mut BlockSets, + _sets: &mut BlockSets<'_, Self::Idx>, _location: Location) {} /// Mutates the block-sets (the flow sets for the given @@ -659,7 +659,7 @@ fn before_terminator_effect(&self, /// The effects applied here cannot depend on which branch the /// terminator took. fn terminator_effect(&self, - sets: &mut BlockSets, + sets: &mut BlockSets<'_, Self::Idx>, location: Location); /// Mutates the block-sets according to the (flow-dependent) diff --git a/src/librustc_mir/dataflow/move_paths/mod.rs b/src/librustc_mir/dataflow/move_paths/mod.rs index d77216220ac..efd979a7da4 100644 --- a/src/librustc_mir/dataflow/move_paths/mod.rs +++ b/src/librustc_mir/dataflow/move_paths/mod.rs @@ -37,7 +37,7 @@ fn index(self) -> usize { } impl fmt::Debug for $Index { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{}{}", $debug_name, self.index()) } } @@ -62,7 +62,7 @@ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { pub use self::indexes::InitIndex; impl MoveOutIndex { - pub fn move_path_index(&self, move_data: &MoveData) -> MovePathIndex { + pub fn move_path_index(&self, move_data: &MoveData<'_>) -> MovePathIndex { move_data.moves[*self].path } } @@ -88,7 +88,10 @@ pub struct MovePath<'tcx> { } impl<'tcx> MovePath<'tcx> { - pub fn parents(&self, move_paths: &IndexVec) -> Vec { + pub fn parents( + &self, + move_paths: &IndexVec>, + ) -> Vec { let mut parents = Vec::new(); let mut curr_parent = self.parent; @@ -102,7 +105,7 @@ pub fn parents(&self, move_paths: &IndexVec) -> Vec fmt::Debug for MovePath<'tcx> { - fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result { write!(w, "MovePath {{")?; if let Some(parent) = self.parent { write!(w, " parent: {:?},", parent)?; @@ -118,7 +121,7 @@ fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { } impl<'tcx> fmt::Display for MovePath<'tcx> { - fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result { write!(w, "{:?}", self.place) } } @@ -166,7 +169,7 @@ fn index_mut(&mut self, index: Location) -> &mut Self::Output { } impl LocationMap where T: Default + Clone { - fn new(mir: &Mir) -> Self { + fn new(mir: &Mir<'_>) -> Self { LocationMap { map: mir.basic_blocks().iter().map(|block| { vec![T::default(); block.statements.len()+1] @@ -190,7 +193,7 @@ pub struct MoveOut { } impl fmt::Debug for MoveOut { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{:?}@{:?}", self.path, self.source) } } @@ -227,7 +230,7 @@ pub enum InitKind { } impl fmt::Debug for Init { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{:?}@{:?} ({:?})", self.path, self.location, self.kind) } } diff --git a/src/librustc_mir/hair/cx/block.rs b/src/librustc_mir/hair/cx/block.rs index 518ae978ae1..c24cf956504 100644 --- a/src/librustc_mir/hair/cx/block.rs +++ b/src/librustc_mir/hair/cx/block.rs @@ -1,6 +1,6 @@ -use hair::*; -use hair::cx::Cx; -use hair::cx::to_ref::ToRef; +use crate::hair::*; +use crate::hair::cx::Cx; +use crate::hair::cx::to_ref::ToRef; use rustc::middle::region; use rustc::hir; use rustc::ty; diff --git a/src/librustc_mir/hair/cx/expr.rs b/src/librustc_mir/hair/cx/expr.rs index 8d64c9e9ada..7e1365f5dc1 100644 --- a/src/librustc_mir/hair/cx/expr.rs +++ b/src/librustc_mir/hair/cx/expr.rs @@ -1,9 +1,9 @@ -use hair::*; +use crate::hair::*; +use crate::hair::cx::Cx; +use crate::hair::cx::block; +use crate::hair::cx::to_ref::ToRef; +use crate::hair::util::UserAnnotatedTyHelpers; use rustc_data_structures::indexed_vec::Idx; -use hair::cx::Cx; -use hair::cx::block; -use hair::cx::to_ref::ToRef; -use hair::util::UserAnnotatedTyHelpers; use rustc::hir::def::{Def, CtorKind}; use rustc::mir::interpret::{GlobalId, ErrorHandled}; use rustc::ty::{self, AdtKind, Ty}; @@ -342,7 +342,7 @@ fn make_mirror_unadjusted<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>, } hir::ExprKind::Lit(ref lit) => ExprKind::Literal { - literal: cx.tcx.intern_lazy_const(ty::LazyConst::Evaluated( + literal: cx.tcx.mk_lazy_const(ty::LazyConst::Evaluated( cx.const_eval_literal(&lit.node, expr_ty, lit.span, false) )), user_ty: None, @@ -442,7 +442,7 @@ fn make_mirror_unadjusted<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>, } else { if let hir::ExprKind::Lit(ref lit) = arg.node { ExprKind::Literal { - literal: cx.tcx.intern_lazy_const(ty::LazyConst::Evaluated( + literal: cx.tcx.mk_lazy_const(ty::LazyConst::Evaluated( cx.const_eval_literal(&lit.node, expr_ty, lit.span, true) )), user_ty: None, @@ -702,7 +702,7 @@ fn make_mirror_unadjusted<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>, ty: var_ty, span: expr.span, kind: ExprKind::Literal { - literal: cx.tcx.intern_lazy_const(literal), + literal: cx.tcx.mk_lazy_const(literal), user_ty: None }, }.to_ref(); @@ -856,7 +856,7 @@ fn method_callee<'a, 'gcx, 'tcx>( ty, span, kind: ExprKind::Literal { - literal: cx.tcx().intern_lazy_const(ty::LazyConst::Evaluated( + literal: cx.tcx().mk_lazy_const(ty::LazyConst::Evaluated( ty::Const::zero_sized(ty) )), user_ty, @@ -918,7 +918,7 @@ fn convert_path_expr<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>, let user_ty = user_substs_applied_to_def(cx, expr.hir_id, &def); debug!("convert_path_expr: user_ty={:?}", user_ty); ExprKind::Literal { - literal: cx.tcx.intern_lazy_const(ty::LazyConst::Evaluated(ty::Const::zero_sized( + literal: cx.tcx.mk_lazy_const(ty::LazyConst::Evaluated(ty::Const::zero_sized( cx.tables().node_id_to_type(expr.hir_id), ))), user_ty, @@ -930,7 +930,7 @@ fn convert_path_expr<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>, let user_ty = user_substs_applied_to_def(cx, expr.hir_id, &def); debug!("convert_path_expr: (const) user_ty={:?}", user_ty); ExprKind::Literal { - literal: cx.tcx.intern_lazy_const(ty::LazyConst::Unevaluated(def_id, substs)), + literal: cx.tcx.mk_lazy_const(ty::LazyConst::Unevaluated(def_id, substs)), user_ty, } }, diff --git a/src/librustc_mir/hair/cx/mod.rs b/src/librustc_mir/hair/cx/mod.rs index f514cac6326..47be8223e8a 100644 --- a/src/librustc_mir/hair/cx/mod.rs +++ b/src/librustc_mir/hair/cx/mod.rs @@ -4,8 +4,8 @@ //! work. //! -use hair::*; -use hair::util::UserAnnotatedTyHelpers; +use crate::hair::*; +use crate::hair::util::UserAnnotatedTyHelpers; use rustc_data_structures::indexed_vec::Idx; use rustc::hir::def_id::{DefId, LOCAL_CRATE}; @@ -21,7 +21,7 @@ use syntax::symbol::Symbol; use rustc::hir; use rustc_data_structures::sync::Lrc; -use hair::constant::{lit_to_const, LitToConstError}; +use crate::hair::constant::{lit_to_const, LitToConstError}; #[derive(Clone)] pub struct Cx<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> { @@ -110,7 +110,7 @@ pub fn usize_ty(&mut self) -> Ty<'tcx> { } pub fn usize_literal(&mut self, value: u64) -> &'tcx ty::LazyConst<'tcx> { - self.tcx.intern_lazy_const(ty::LazyConst::Evaluated(ty::Const::from_usize(self.tcx, value))) + self.tcx.mk_lazy_const(ty::LazyConst::Evaluated(ty::Const::from_usize(self.tcx, value))) } pub fn bool_ty(&mut self) -> Ty<'tcx> { @@ -122,11 +122,11 @@ pub fn unit_ty(&mut self) -> Ty<'tcx> { } pub fn true_literal(&mut self) -> &'tcx ty::LazyConst<'tcx> { - self.tcx.intern_lazy_const(ty::LazyConst::Evaluated(ty::Const::from_bool(self.tcx, true))) + self.tcx.mk_lazy_const(ty::LazyConst::Evaluated(ty::Const::from_bool(self.tcx, true))) } pub fn false_literal(&mut self) -> &'tcx ty::LazyConst<'tcx> { - self.tcx.intern_lazy_const(ty::LazyConst::Evaluated(ty::Const::from_bool(self.tcx, false))) + self.tcx.mk_lazy_const(ty::LazyConst::Evaluated(ty::Const::from_bool(self.tcx, false))) } pub fn const_eval_literal( @@ -239,7 +239,7 @@ fn tables(&self) -> &ty::TypeckTables<'tcx> { } } -fn lint_level_for_hir_id(tcx: TyCtxt, mut id: ast::NodeId) -> ast::NodeId { +fn lint_level_for_hir_id(tcx: TyCtxt<'_, '_, '_>, mut id: ast::NodeId) -> ast::NodeId { // Right now we insert a `with_ignore` node in the dep graph here to // ignore the fact that `lint_levels` below depends on the entire crate. // For now this'll prevent false positives of recompiling too much when diff --git a/src/librustc_mir/hair/cx/to_ref.rs b/src/librustc_mir/hair/cx/to_ref.rs index 1b87e4450c5..a462c61c2ac 100644 --- a/src/librustc_mir/hair/cx/to_ref.rs +++ b/src/librustc_mir/hair/cx/to_ref.rs @@ -1,4 +1,4 @@ -use hair::*; +use crate::hair::*; use rustc::hir; use syntax::ptr::P; diff --git a/src/librustc_mir/hair/pattern/_match.rs b/src/librustc_mir/hair/pattern/_match.rs index 7f5b1a761d2..5779a032acc 100644 --- a/src/librustc_mir/hair/pattern/_match.rs +++ b/src/librustc_mir/hair/pattern/_match.rs @@ -307,7 +307,7 @@ pub fn empty() -> Self { /// + _ + [_, _, ..tail] + /// ++++++++++++++++++++++++++ impl<'p, 'tcx> fmt::Debug for Matrix<'p, 'tcx> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "\n")?; let &Matrix(ref m) = self; @@ -442,7 +442,7 @@ fn variant_index_for_adt<'a>( VariantIdx::new(0) } &ConstantValue(c) => { - ::const_eval::const_variant_index( + crate::const_eval::const_variant_index( cx.tcx, cx.param_env, c, @@ -1115,7 +1115,7 @@ pub fn is_useful<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>, } else { debug!("is_useful - expanding wildcard"); - let used_ctors: Vec = rows.iter().flat_map(|row| { + let used_ctors: Vec> = rows.iter().flat_map(|row| { pat_constructors(cx, row[0], pcx).unwrap_or(vec![]) }).collect(); debug!("used_ctors = {:#?}", used_ctors); @@ -1302,7 +1302,7 @@ fn is_useful_specialized<'p, 'a: 'p, 'tcx: 'a>( /// Returns None in case of a catch-all, which can't be specialized. fn pat_constructors<'tcx>(cx: &mut MatchCheckCtxt<'_, 'tcx>, pat: &Pattern<'tcx>, - pcx: PatternContext) + pcx: PatternContext<'_>) -> Option>> { match *pat.kind { diff --git a/src/librustc_mir/hair/pattern/check_match.rs b/src/librustc_mir/hair/pattern/check_match.rs index a47d64319bd..978051aab59 100644 --- a/src/librustc_mir/hair/pattern/check_match.rs +++ b/src/librustc_mir/hair/pattern/check_match.rs @@ -229,7 +229,7 @@ fn check_match( return; } - let matrix: Matrix = inlined_arms + let matrix: Matrix<'_, '_> = inlined_arms .iter() .filter(|&&(_, guard)| guard.is_none()) .flat_map(|arm| &arm.0) @@ -248,7 +248,7 @@ fn check_irrefutable(&self, pat: &'tcx Pat, origin: &str) { self.tables); let pattern = patcx.lower_pattern(pat); let pattern_ty = pattern.ty; - let pats: Matrix = vec![smallvec![ + let pats: Matrix<'_, '_> = vec![smallvec![ expand_pattern(cx, pattern) ]].into_iter().collect(); @@ -283,7 +283,7 @@ fn check_irrefutable(&self, pat: &'tcx Pat, origin: &str) { } } -fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor, pat: &Pat) { +fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor<'_, '_>, pat: &Pat) { pat.walk(|p| { if let PatKind::Binding(_, _, _, ident, None) = p.node { if let Some(&bm) = cx.tables.pat_binding_modes().get(p.hir_id) { @@ -462,7 +462,7 @@ fn check_exhaustive<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>, } // Legality of move bindings checking -fn check_legality_of_move_bindings(cx: &MatchVisitor, +fn check_legality_of_move_bindings(cx: &MatchVisitor<'_, '_>, has_guard: bool, pats: &[P]) { let mut by_ref_span = None; @@ -541,7 +541,7 @@ fn check_legality_of_move_bindings(cx: &MatchVisitor, /// assign. /// /// FIXME: this should be done by borrowck. -fn check_for_mutation_in_guard(cx: &MatchVisitor, guard: &hir::Guard) { +fn check_for_mutation_in_guard(cx: &MatchVisitor<'_, '_>, guard: &hir::Guard) { let mut checker = MutationChecker { cx, }; @@ -561,13 +561,13 @@ struct MutationChecker<'a, 'tcx: 'a> { } impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> { - fn matched_pat(&mut self, _: &Pat, _: &cmt_, _: euv::MatchMode) {} - fn consume(&mut self, _: ast::NodeId, _: Span, _: &cmt_, _: ConsumeMode) {} - fn consume_pat(&mut self, _: &Pat, _: &cmt_, _: ConsumeMode) {} + fn matched_pat(&mut self, _: &Pat, _: &cmt_<'_>, _: euv::MatchMode) {} + fn consume(&mut self, _: ast::NodeId, _: Span, _: &cmt_<'_>, _: ConsumeMode) {} + fn consume_pat(&mut self, _: &Pat, _: &cmt_<'_>, _: ConsumeMode) {} fn borrow(&mut self, _: ast::NodeId, span: Span, - _: &cmt_, + _: &cmt_<'_>, _: ty::Region<'tcx>, kind:ty:: BorrowKind, _: LoanCause) { @@ -588,7 +588,7 @@ fn borrow(&mut self, } } fn decl_without_init(&mut self, _: ast::NodeId, _: Span) {} - fn mutate(&mut self, _: ast::NodeId, span: Span, _: &cmt_, mode: MutateMode) { + fn mutate(&mut self, _: ast::NodeId, span: Span, _: &cmt_<'_>, mode: MutateMode) { match mode { MutateMode::JustWrite | MutateMode::WriteAndRead => { struct_span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard") @@ -603,7 +603,7 @@ fn mutate(&mut self, _: ast::NodeId, span: Span, _: &cmt_, mode: MutateMode) { /// Forbids bindings in `@` patterns. This is necessary for memory safety, /// because of the way rvalues are handled in the borrow check. (See issue /// #14587.) -fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor, pat: &Pat) { +fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat) { AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat); } diff --git a/src/librustc_mir/hair/pattern/mod.rs b/src/librustc_mir/hair/pattern/mod.rs index 6b7e1416118..84d8f32954c 100644 --- a/src/librustc_mir/hair/pattern/mod.rs +++ b/src/librustc_mir/hair/pattern/mod.rs @@ -6,10 +6,10 @@ pub use self::check_match::check_crate; pub(crate) use self::check_match::check_match; -use const_eval::{const_field, const_variant_index}; +use crate::const_eval::{const_field, const_variant_index}; -use hair::util::UserAnnotatedTyHelpers; -use hair::constant::*; +use crate::hair::util::UserAnnotatedTyHelpers; +use crate::hair::constant::*; use rustc::mir::{fmt_const_val, Field, BorrowKind, Mutability}; use rustc::mir::{UserTypeProjection}; @@ -167,6 +167,17 @@ pub enum PatternKind<'tcx> { }, } +impl<'tcx> PatternKind<'tcx> { + /// If this is a `PatternKind::AscribeUserType` then return the subpattern kind, otherwise + /// return this pattern kind. + fn with_user_type_ascription_subpattern(self) -> Self { + match self { + PatternKind::AscribeUserType { subpattern: Pattern { box kind, .. }, .. } => kind, + kind => kind, + } + } +} + #[derive(Clone, Copy, Debug, PartialEq)] pub struct PatternRange<'tcx> { pub lo: ty::Const<'tcx>, @@ -176,7 +187,7 @@ pub struct PatternRange<'tcx> { } impl<'tcx> fmt::Display for Pattern<'tcx> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self.kind { PatternKind::Wild => write!(f, "_"), PatternKind::AscribeUserType { ref subpattern, .. } => @@ -403,9 +414,15 @@ fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> { PatKind::Lit(ref value) => self.lower_lit(value), PatKind::Range(ref lo_expr, ref hi_expr, end) => { - match (self.lower_lit(lo_expr), self.lower_lit(hi_expr)) { - (PatternKind::Constant { value: lo }, - PatternKind::Constant { value: hi }) => { + match ( + // Look for `PatternKind::Constant` patterns inside of any + // `PatternKind::AscribeUserType` patterns. Type ascriptions can be safely + // ignored for the purposes of lowering a range correctly - these are checked + // elsewhere for well-formedness. + self.lower_lit(lo_expr).with_user_type_ascription_subpattern(), + self.lower_lit(hi_expr).with_user_type_ascription_subpattern(), + ) { + (PatternKind::Constant { value: lo }, PatternKind::Constant { value: hi }) => { use std::cmp::Ordering; let cmp = compare_const_vals( self.tcx, @@ -454,7 +471,15 @@ fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> { } } } - _ => PatternKind::Wild + ref pats => { + self.tcx.sess.delay_span_bug( + pat.span, + &format!("found bad range pattern `{:?}` outside of error recovery", + pats), + ); + + PatternKind::Wild + } } } diff --git a/src/librustc_mir/interpret/eval_context.rs b/src/librustc_mir/interpret/eval_context.rs index 1b976d822eb..c87338fb0ce 100644 --- a/src/librustc_mir/interpret/eval_context.rs +++ b/src/librustc_mir/interpret/eval_context.rs @@ -322,7 +322,7 @@ pub fn layout_of_local( ) -> EvalResult<'tcx, TyLayout<'tcx>> { match frame.locals[local].layout.get() { None => { - let layout = ::interpret::operand::from_known_layout(layout, || { + let layout = crate::interpret::operand::from_known_layout(layout, || { let local_ty = frame.mir.local_decls[local].ty; let local_ty = self.monomorphize_with_substs(local_ty, frame.instance.substs); self.layout_of(local_ty) diff --git a/src/librustc_mir/interpret/snapshot.rs b/src/librustc_mir/interpret/snapshot.rs index 5fae461bdc2..ee295116ba9 100644 --- a/src/librustc_mir/interpret/snapshot.rs +++ b/src/librustc_mir/interpret/snapshot.rs @@ -25,7 +25,7 @@ use super::eval_context::{LocalState, StackPopCleanup}; use super::{Frame, Memory, Operand, MemPlace, Place, Immediate, ScalarMaybeUndef, LocalValue}; -use const_eval::CompileTimeInterpreter; +use crate::const_eval::CompileTimeInterpreter; #[derive(Default)] pub(crate) struct InfiniteLoopDetector<'a, 'mir, 'tcx: 'a + 'mir> { @@ -200,7 +200,7 @@ fn snapshot(&self, ctx: &'a Ctx) -> Self::Item { Undef, }); -impl_stable_hash_for!(struct ::interpret::MemPlace { +impl_stable_hash_for!(struct crate::interpret::MemPlace { ptr, align, meta, @@ -211,7 +211,7 @@ fn snapshot(&self, ctx: &'a Ctx) -> Self::Item { align -> *align, // just copy alignment verbatim }); -impl_stable_hash_for!(enum ::interpret::Place { +impl_stable_hash_for!(enum crate::interpret::Place { Ptr(mem_place), Local { frame, local }, }); @@ -232,7 +232,7 @@ fn snapshot(&self, ctx: &'a Ctx) -> Self::Item { } } -impl_stable_hash_for!(enum ::interpret::Immediate { +impl_stable_hash_for!(enum crate::interpret::Immediate { Scalar(x), ScalarPair(x, y), }); @@ -241,7 +241,7 @@ fn snapshot(&self, ctx: &'a Ctx) -> Self::Item { ScalarPair(s, t), }); -impl_stable_hash_for!(enum ::interpret::Operand { +impl_stable_hash_for!(enum crate::interpret::Operand { Immediate(x), Indirect(x), }); @@ -250,7 +250,7 @@ fn snapshot(&self, ctx: &'a Ctx) -> Self::Item { Indirect(m), }); -impl_stable_hash_for!(enum ::interpret::LocalValue { +impl_stable_hash_for!(enum crate::interpret::LocalValue { Dead, Live(x), }); @@ -298,7 +298,7 @@ fn snapshot(&self, ctx: &'a Ctx) -> Self::Item { } } -impl_stable_hash_for!(enum ::interpret::eval_context::StackPopCleanup { +impl_stable_hash_for!(enum crate::interpret::eval_context::StackPopCleanup { Goto(block), None { cleanup }, }); diff --git a/src/librustc_mir/interpret/terminator.rs b/src/librustc_mir/interpret/terminator.rs index 7e823524c18..be50daa1709 100644 --- a/src/librustc_mir/interpret/terminator.rs +++ b/src/librustc_mir/interpret/terminator.rs @@ -112,7 +112,7 @@ pub(super) fn eval_terminator( let ty = place.layout.ty; trace!("TerminatorKind::drop: {:?}, type {}", location, ty); - let instance = ::monomorphize::resolve_drop_in_place(*self.tcx, ty); + let instance = crate::monomorphize::resolve_drop_in_place(*self.tcx, ty); self.drop_in_place( place, instance, @@ -326,7 +326,7 @@ fn eval_fn_call( // last incoming argument. These two iterators do not have the same type, // so to keep the code paths uniform we accept an allocation // (for RustCall ABI only). - let caller_args : Cow<[OpTy<'tcx, M::PointerTag>]> = + let caller_args : Cow<'_, [OpTy<'tcx, M::PointerTag>]> = if caller_abi == Abi::RustCall && !args.is_empty() { // Untuple let (&untuple_arg, args) = args.split_last().unwrap(); @@ -335,7 +335,7 @@ fn eval_fn_call( .chain((0..untuple_arg.layout.fields.count()).into_iter() .map(|i| self.operand_field(untuple_arg, i as u64)) ) - .collect::>>>()?) + .collect::>>>()?) } else { // Plain arg passing Cow::from(args) diff --git a/src/librustc_mir/interpret/traits.rs b/src/librustc_mir/interpret/traits.rs index 642bbc114f5..63253bae907 100644 --- a/src/librustc_mir/interpret/traits.rs +++ b/src/librustc_mir/interpret/traits.rs @@ -52,7 +52,7 @@ pub fn get_vtable( ).with_default_tag(); let tcx = &*self.tcx; - let drop = ::monomorphize::resolve_drop_in_place(*tcx, ty); + let drop = crate::monomorphize::resolve_drop_in_place(*tcx, ty); let drop = self.memory.create_fn_alloc(drop).with_default_tag(); // no need to do any alignment checks on the memory accesses below, because we know the // allocation is correctly aligned as we created it above. Also we're only offsetting by diff --git a/src/librustc_mir/interpret/visitor.rs b/src/librustc_mir/interpret/visitor.rs index 4773f5627d7..930bcb44374 100644 --- a/src/librustc_mir/interpret/visitor.rs +++ b/src/librustc_mir/interpret/visitor.rs @@ -26,7 +26,7 @@ fn to_op( ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>>; /// Create this from an `MPlaceTy`. - fn from_mem_place(MPlaceTy<'tcx, M::PointerTag>) -> Self; + fn from_mem_place(mplace: MPlaceTy<'tcx, M::PointerTag>) -> Self; /// Project to the given enum variant. fn project_downcast( diff --git a/src/librustc_mir/lib.rs b/src/librustc_mir/lib.rs index ccfc15bac04..909f9695669 100644 --- a/src/librustc_mir/lib.rs +++ b/src/librustc_mir/lib.rs @@ -26,39 +26,21 @@ #![feature(slice_concat_ext)] #![feature(try_from)] #![feature(reverse_bits)] +#![feature(try_blocks)] #![recursion_limit="256"] -extern crate arena; +#![deny(rust_2018_idioms)] +#![allow(explicit_outlives_requirements)] -#[macro_use] -extern crate bitflags; #[macro_use] extern crate log; -extern crate either; -extern crate graphviz as dot; -extern crate polonius_engine; #[macro_use] extern crate rustc; #[macro_use] extern crate rustc_data_structures; -extern crate serialize as rustc_serialize; -extern crate rustc_errors; +#[allow(unused_extern_crates)] +extern crate serialize as rustc_serialize; // used by deriving #[macro_use] extern crate syntax; -extern crate syntax_pos; -extern crate rustc_target; -extern crate log_settings; -extern crate rustc_apfloat; -extern crate byteorder; -extern crate core; -extern crate smallvec; - -// Once we can use edition 2018 in the compiler, -// replace this with real try blocks. -macro_rules! try_block { - ($($inside:tt)*) => ( - (||{ ::std::ops::Try::from_ok({ $($inside)* }) })() - ) -} mod diagnostics; @@ -77,7 +59,7 @@ macro_rules! try_block { pub use hair::pattern::check_crate as matchck_crate; use rustc::ty::query::Providers; -pub fn provide(providers: &mut Providers) { +pub fn provide(providers: &mut Providers<'_>) { borrow_check::provide(providers); shim::provide(providers); transform::provide(providers); diff --git a/src/librustc_mir/lints.rs b/src/librustc_mir/lints.rs index 8ded31d89da..6b6e8fcdc82 100644 --- a/src/librustc_mir/lints.rs +++ b/src/librustc_mir/lints.rs @@ -18,7 +18,7 @@ pub fn check(tcx: TyCtxt<'a, 'tcx, 'tcx>, } fn check_fn_for_unconditional_recursion(tcx: TyCtxt<'a, 'tcx, 'tcx>, - fn_kind: FnKind, + fn_kind: FnKind<'_>, mir: &Mir<'tcx>, def_id: DefId) { if let FnKind::Closure(_) = fn_kind { diff --git a/src/librustc_mir/monomorphize/collector.rs b/src/librustc_mir/monomorphize/collector.rs index e713ab17c3a..7f3c24daf60 100644 --- a/src/librustc_mir/monomorphize/collector.rs +++ b/src/librustc_mir/monomorphize/collector.rs @@ -189,11 +189,11 @@ use rustc::mir::mono::MonoItem; use rustc::mir::interpret::{Scalar, GlobalId, AllocKind, ErrorHandled}; -use monomorphize::{self, Instance}; +use crate::monomorphize::{self, Instance}; use rustc::util::nodemap::{FxHashSet, FxHashMap, DefIdMap}; use rustc::util::common::time; -use monomorphize::item::{MonoItemExt, DefPathBasedNames, InstantiationMode}; +use crate::monomorphize::item::{MonoItemExt, DefPathBasedNames, InstantiationMode}; use rustc_data_structures::bit_set::GrowableBitSet; use rustc_data_structures::sync::{MTRef, MTLock, ParallelIterator, par_iter}; diff --git a/src/librustc_mir/monomorphize/item.rs b/src/librustc_mir/monomorphize/item.rs index 431cc0d52b4..d3381f463f4 100644 --- a/src/librustc_mir/monomorphize/item.rs +++ b/src/librustc_mir/monomorphize/item.rs @@ -1,4 +1,4 @@ -use monomorphize::Instance; +use crate::monomorphize::Instance; use rustc::hir; use rustc::hir::def_id::{DefId, LOCAL_CRATE}; use rustc::session::config::OptLevel; diff --git a/src/librustc_mir/monomorphize/partitioning.rs b/src/librustc_mir/monomorphize/partitioning.rs index 569e4c828f6..d4c7ebefe17 100644 --- a/src/librustc_mir/monomorphize/partitioning.rs +++ b/src/librustc_mir/monomorphize/partitioning.rs @@ -111,9 +111,9 @@ use rustc::util::nodemap::{DefIdSet, FxHashMap, FxHashSet}; use rustc::mir::mono::MonoItem; -use monomorphize::collector::InliningMap; -use monomorphize::collector::{self, MonoItemCollectionMode}; -use monomorphize::item::{MonoItemExt, InstantiationMode}; +use crate::monomorphize::collector::InliningMap; +use crate::monomorphize::collector::{self, MonoItemCollectionMode}; +use crate::monomorphize::item::{MonoItemExt, InstantiationMode}; pub use rustc::mir::mono::CodegenUnit; @@ -146,7 +146,7 @@ fn work_product_id(&self) -> WorkProductId { WorkProductId::from_cgu_name(&self.name().as_str()) } - fn work_product(&self, tcx: TyCtxt) -> WorkProduct { + fn work_product(&self, tcx: TyCtxt<'_, '_, '_>) -> WorkProduct { let work_product_id = self.work_product_id(); tcx.dep_graph .previous_work_product(&work_product_id) @@ -213,7 +213,7 @@ fn as_codegen_unit(&self) -> &CodegenUnit<'tcx> { } // Anything we can't find a proper codegen unit for goes into this. -fn fallback_cgu_name(name_builder: &mut CodegenUnitNameBuilder) -> InternedString { +fn fallback_cgu_name(name_builder: &mut CodegenUnitNameBuilder<'_, '_, '_>) -> InternedString { name_builder.build_cgu_name(LOCAL_CRATE, &["fallback"], Some("cgu")) } @@ -536,7 +536,7 @@ fn mono_item_visibility( } } -fn default_visibility(tcx: TyCtxt, id: DefId, is_generic: bool) -> Visibility { +fn default_visibility(tcx: TyCtxt<'_, '_, '_>, id: DefId, is_generic: bool) -> Visibility { if !tcx.sess.target.target.options.default_hidden_visibility { return Visibility::Default } @@ -795,8 +795,8 @@ fn characteristic_def_id_of_mono_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, type CguNameCache = FxHashMap<(DefId, bool), InternedString>; -fn compute_codegen_unit_name(tcx: TyCtxt, - name_builder: &mut CodegenUnitNameBuilder, +fn compute_codegen_unit_name(tcx: TyCtxt<'_, '_, '_>, + name_builder: &mut CodegenUnitNameBuilder<'_, '_, '_>, def_id: DefId, volatile: bool, cache: &mut CguNameCache) @@ -855,7 +855,7 @@ fn compute_codegen_unit_name(tcx: TyCtxt, }).clone() } -fn numbered_codegen_unit_name(name_builder: &mut CodegenUnitNameBuilder, +fn numbered_codegen_unit_name(name_builder: &mut CodegenUnitNameBuilder<'_, '_, '_>, index: usize) -> InternedString { name_builder.build_cgu_name_no_mangle(LOCAL_CRATE, &["cgu"], Some(index)) @@ -929,7 +929,7 @@ fn collect_and_partition_mono_items<'a, 'tcx>( tcx.sess.abort_if_errors(); - ::monomorphize::assert_symbols_are_distinct(tcx, items.iter()); + crate::monomorphize::assert_symbols_are_distinct(tcx, items.iter()); let strategy = if tcx.sess.opts.incremental.is_some() { PartitioningStrategy::PerModule @@ -1013,7 +1013,7 @@ fn collect_and_partition_mono_items<'a, 'tcx>( (Arc::new(mono_items), Arc::new(codegen_units)) } -pub fn provide(providers: &mut Providers) { +pub fn provide(providers: &mut Providers<'_>) { providers.collect_and_partition_mono_items = collect_and_partition_mono_items; diff --git a/src/librustc_mir/shim.rs b/src/librustc_mir/shim.rs index 751815eab28..f4c3049548d 100644 --- a/src/librustc_mir/shim.rs +++ b/src/librustc_mir/shim.rs @@ -16,12 +16,12 @@ use std::fmt; use std::iter; -use transform::{add_moves_for_packed_drops, add_call_guards}; -use transform::{remove_noop_landing_pads, no_landing_pads, simplify}; -use util::elaborate_drops::{self, DropElaborator, DropStyle, DropFlagMode}; -use util::patch::MirPatch; +use crate::transform::{add_moves_for_packed_drops, add_call_guards}; +use crate::transform::{remove_noop_landing_pads, no_landing_pads, simplify}; +use crate::util::elaborate_drops::{self, DropElaborator, DropStyle, DropFlagMode}; +use crate::util::patch::MirPatch; -pub fn provide(providers: &mut Providers) { +pub fn provide(providers: &mut Providers<'_>) { providers.mir_shims = make_shim; } @@ -138,7 +138,7 @@ enum CallKind { Direct(DefId), } -fn temp_decl(mutability: Mutability, ty: Ty, span: Span) -> LocalDecl { +fn temp_decl(mutability: Mutability, ty: Ty<'_>, span: Span) -> LocalDecl<'_> { let source_info = SourceInfo { scope: OUTERMOST_SOURCE_SCOPE, span }; LocalDecl { mutability, @@ -259,7 +259,7 @@ pub struct DropShimElaborator<'a, 'tcx: 'a> { } impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> { - fn fmt(&self, _f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { Ok(()) } } @@ -459,7 +459,7 @@ fn make_clone_call( span: self.span, ty: func_ty, user_ty: None, - literal: tcx.intern_lazy_const(ty::LazyConst::Evaluated( + literal: tcx.mk_lazy_const(ty::LazyConst::Evaluated( ty::Const::zero_sized(func_ty), )), }); @@ -521,7 +521,7 @@ fn make_usize(&self, value: u64) -> Box> { span: self.span, ty: self.tcx.types.usize, user_ty: None, - literal: self.tcx.intern_lazy_const(ty::LazyConst::Evaluated( + literal: self.tcx.mk_lazy_const(ty::LazyConst::Evaluated( ty::Const::from_usize(self.tcx, value), )), } @@ -759,7 +759,7 @@ fn build_call_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span, ty, user_ty: None, - literal: tcx.intern_lazy_const(ty::LazyConst::Evaluated( + literal: tcx.mk_lazy_const(ty::LazyConst::Evaluated( ty::Const::zero_sized(ty) )), }), diff --git a/src/librustc_mir/transform/add_call_guards.rs b/src/librustc_mir/transform/add_call_guards.rs index 3ea1c8e82ff..dab96faaa2a 100644 --- a/src/librustc_mir/transform/add_call_guards.rs +++ b/src/librustc_mir/transform/add_call_guards.rs @@ -1,7 +1,7 @@ use rustc::ty::TyCtxt; use rustc::mir::*; use rustc_data_structures::indexed_vec::{Idx, IndexVec}; -use transform::{MirPass, MirSource}; +use crate::transform::{MirPass, MirSource}; #[derive(PartialEq)] pub enum AddCallGuards { @@ -40,7 +40,7 @@ fn run_pass<'a, 'tcx>(&self, } impl AddCallGuards { - pub fn add_call_guards(&self, mir: &mut Mir) { + pub fn add_call_guards(&self, mir: &mut Mir<'_>) { let pred_count: IndexVec<_, _> = mir.predecessors().iter().map(|ps| ps.len()).collect(); diff --git a/src/librustc_mir/transform/add_moves_for_packed_drops.rs b/src/librustc_mir/transform/add_moves_for_packed_drops.rs index 8ec6902cf15..1492f0c50a3 100644 --- a/src/librustc_mir/transform/add_moves_for_packed_drops.rs +++ b/src/librustc_mir/transform/add_moves_for_packed_drops.rs @@ -2,9 +2,9 @@ use rustc::mir::*; use rustc::ty::TyCtxt; -use transform::{MirPass, MirSource}; -use util::patch::MirPatch; -use util; +use crate::transform::{MirPass, MirSource}; +use crate::util::patch::MirPatch; +use crate::util; // This pass moves values being dropped that are within a packed // struct to a separate local before dropping them, to ensure that diff --git a/src/librustc_mir/transform/add_retag.rs b/src/librustc_mir/transform/add_retag.rs index 3d5897bca9f..7bfcd318afe 100644 --- a/src/librustc_mir/transform/add_retag.rs +++ b/src/librustc_mir/transform/add_retag.rs @@ -6,7 +6,7 @@ use rustc::ty::{self, Ty, TyCtxt}; use rustc::mir::*; -use transform::{MirPass, MirSource}; +use crate::transform::{MirPass, MirSource}; pub struct AddRetag; diff --git a/src/librustc_mir/transform/check_unsafety.rs b/src/librustc_mir/transform/check_unsafety.rs index ab8da2f352c..b2e1afc519e 100644 --- a/src/librustc_mir/transform/check_unsafety.rs +++ b/src/librustc_mir/transform/check_unsafety.rs @@ -17,7 +17,7 @@ use std::ops::Bound; -use util; +use crate::util; pub struct UnsafetyChecker<'a, 'tcx: 'a> { mir: &'a Mir<'tcx>, @@ -458,7 +458,7 @@ fn check_mut_borrowing_layout_constrained_field( } } -pub(crate) fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers<'_>) { *providers = Providers { unsafety_check_result, unsafe_derive_on_repr_packed, @@ -575,7 +575,7 @@ fn unsafe_derive_on_repr_packed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: D } /// Return the NodeId for an enclosing scope that is also `unsafe` -fn is_enclosed(tcx: TyCtxt, +fn is_enclosed(tcx: TyCtxt<'_, '_, '_>, used_unsafe: &FxHashSet, id: ast::NodeId) -> Option<(String, ast::NodeId)> { let parent_id = tcx.hir().get_parent_node(id); @@ -598,7 +598,9 @@ fn is_enclosed(tcx: TyCtxt, } } -fn report_unused_unsafe(tcx: TyCtxt, used_unsafe: &FxHashSet, id: ast::NodeId) { +fn report_unused_unsafe(tcx: TyCtxt<'_, '_, '_>, + used_unsafe: &FxHashSet, + id: ast::NodeId) { let span = tcx.sess.source_map().def_span(tcx.hir().span(id)); let msg = "unnecessary `unsafe` block"; let mut db = tcx.struct_span_lint_node(UNUSED_UNSAFE, id, span, msg); diff --git a/src/librustc_mir/transform/cleanup_post_borrowck.rs b/src/librustc_mir/transform/cleanup_post_borrowck.rs index e6df6b7fd27..240ef7c8ba4 100644 --- a/src/librustc_mir/transform/cleanup_post_borrowck.rs +++ b/src/librustc_mir/transform/cleanup_post_borrowck.rs @@ -26,7 +26,7 @@ use rustc::mir::{Statement, StatementKind}; use rustc::mir::visit::MutVisitor; use rustc::ty::TyCtxt; -use transform::{MirPass, MirSource}; +use crate::transform::{MirPass, MirSource}; pub struct CleanAscribeUserType; diff --git a/src/librustc_mir/transform/const_prop.rs b/src/librustc_mir/transform/const_prop.rs index dc556a15cd8..dd1f37a5918 100644 --- a/src/librustc_mir/transform/const_prop.rs +++ b/src/librustc_mir/transform/const_prop.rs @@ -18,12 +18,12 @@ HasTyCtxt, TargetDataLayout, HasDataLayout, }; -use interpret::{self, EvalContext, ScalarMaybeUndef, Immediate, OpTy, MemoryKind}; -use const_eval::{ +use crate::interpret::{self, EvalContext, ScalarMaybeUndef, Immediate, OpTy, MemoryKind}; +use crate::const_eval::{ CompileTimeInterpreter, error_to_const_error, eval_promoted, mk_eval_cx, lazy_const_to_op, }; -use transform::{MirPass, MirSource}; +use crate::transform::{MirPass, MirSource}; pub struct ConstProp; @@ -486,7 +486,7 @@ struct CanConstProp { impl CanConstProp { /// returns true if `local` can be propagated - fn check(mir: &Mir) -> IndexVec { + fn check(mir: &Mir<'_>) -> IndexVec { let mut cpv = CanConstProp { can_const_prop: IndexVec::from_elem(true, &mir.local_decls), found_assignment: IndexVec::from_elem(false, &mir.local_decls), diff --git a/src/librustc_mir/transform/copy_prop.rs b/src/librustc_mir/transform/copy_prop.rs index 55e14077c3e..4789c35740e 100644 --- a/src/librustc_mir/transform/copy_prop.rs +++ b/src/librustc_mir/transform/copy_prop.rs @@ -22,8 +22,8 @@ use rustc::mir::{Constant, Local, LocalKind, Location, Place, Mir, Operand, Rvalue, StatementKind}; use rustc::mir::visit::MutVisitor; use rustc::ty::TyCtxt; -use transform::{MirPass, MirSource}; -use util::def_use::DefUseAnalysis; +use crate::transform::{MirPass, MirSource}; +use crate::util::def_use::DefUseAnalysis; pub struct CopyPropagation; @@ -173,7 +173,7 @@ enum Action<'tcx> { } impl<'tcx> Action<'tcx> { - fn local_copy(mir: &Mir<'tcx>, def_use_analysis: &DefUseAnalysis, src_place: &Place<'tcx>) + fn local_copy(mir: &Mir<'tcx>, def_use_analysis: &DefUseAnalysis<'_>, src_place: &Place<'tcx>) -> Option> { // The source must be a local. let src_local = if let Place::Local(local) = *src_place { diff --git a/src/librustc_mir/transform/deaggregator.rs b/src/librustc_mir/transform/deaggregator.rs index a2fe9def8ee..669384e31da 100644 --- a/src/librustc_mir/transform/deaggregator.rs +++ b/src/librustc_mir/transform/deaggregator.rs @@ -1,7 +1,7 @@ use rustc::ty::TyCtxt; use rustc::mir::*; use rustc_data_structures::indexed_vec::Idx; -use transform::{MirPass, MirSource}; +use crate::transform::{MirPass, MirSource}; pub struct Deaggregator; diff --git a/src/librustc_mir/transform/dump_mir.rs b/src/librustc_mir/transform/dump_mir.rs index 8fabb2d11fc..d7f697a3200 100644 --- a/src/librustc_mir/transform/dump_mir.rs +++ b/src/librustc_mir/transform/dump_mir.rs @@ -8,8 +8,8 @@ use rustc::mir::Mir; use rustc::session::config::{OutputFilenames, OutputType}; use rustc::ty::TyCtxt; -use transform::{MirPass, MirSource}; -use util as mir_util; +use crate::transform::{MirPass, MirSource}; +use crate::util as mir_util; pub struct Marker(pub &'static str); @@ -31,7 +31,7 @@ pub struct Disambiguator { } impl fmt::Display for Disambiguator { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { let title = if self.is_after { "after" } else { "before" }; write!(formatter, "{}", title) } diff --git a/src/librustc_mir/transform/elaborate_drops.rs b/src/librustc_mir/transform/elaborate_drops.rs index 06e16de8b43..a3750d801bd 100644 --- a/src/librustc_mir/transform/elaborate_drops.rs +++ b/src/librustc_mir/transform/elaborate_drops.rs @@ -1,10 +1,14 @@ -use dataflow::move_paths::{HasMoveData, MoveData, MovePathIndex, LookupResult}; -use dataflow::{MaybeInitializedPlaces, MaybeUninitializedPlaces}; -use dataflow::{DataflowResults}; -use dataflow::{on_all_children_bits, on_all_drop_children_bits}; -use dataflow::{drop_flag_effects_for_location, on_lookup_result_bits}; -use dataflow::MoveDataParamEnv; -use dataflow::{self, do_dataflow, DebugFormatted}; +use crate::dataflow::move_paths::{HasMoveData, MoveData, MovePathIndex, LookupResult}; +use crate::dataflow::{MaybeInitializedPlaces, MaybeUninitializedPlaces}; +use crate::dataflow::{DataflowResults}; +use crate::dataflow::{on_all_children_bits, on_all_drop_children_bits}; +use crate::dataflow::{drop_flag_effects_for_location, on_lookup_result_bits}; +use crate::dataflow::MoveDataParamEnv; +use crate::dataflow::{self, do_dataflow, DebugFormatted}; +use crate::transform::{MirPass, MirSource}; +use crate::util::patch::MirPatch; +use crate::util::elaborate_drops::{DropFlagState, Unwind, elaborate_drop}; +use crate::util::elaborate_drops::{DropElaborator, DropStyle, DropFlagMode}; use rustc::ty::{self, TyCtxt}; use rustc::ty::layout::VariantIdx; use rustc::mir::*; @@ -13,10 +17,6 @@ use std::fmt; use syntax::ast; use syntax_pos::Span; -use transform::{MirPass, MirSource}; -use util::patch::MirPatch; -use util::elaborate_drops::{DropFlagState, Unwind, elaborate_drop}; -use util::elaborate_drops::{DropElaborator, DropStyle, DropFlagMode}; pub struct ElaborateDrops; @@ -174,7 +174,7 @@ struct Elaborator<'a, 'b: 'a, 'tcx: 'b> { } impl<'a, 'b, 'tcx> fmt::Debug for Elaborator<'a, 'b, 'tcx> { - fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { Ok(()) } } @@ -533,7 +533,7 @@ fn constant_bool(&self, span: Span, val: bool) -> Rvalue<'tcx> { span, ty: self.tcx.types.bool, user_ty: None, - literal: self.tcx.intern_lazy_const(ty::LazyConst::Evaluated( + literal: self.tcx.mk_lazy_const(ty::LazyConst::Evaluated( ty::Const::from_bool(self.tcx, val), )), }))) diff --git a/src/librustc_mir/transform/erase_regions.rs b/src/librustc_mir/transform/erase_regions.rs index b464b7d65e4..b555a2aa83e 100644 --- a/src/librustc_mir/transform/erase_regions.rs +++ b/src/librustc_mir/transform/erase_regions.rs @@ -8,7 +8,7 @@ use rustc::ty::{self, Ty, TyCtxt}; use rustc::mir::*; use rustc::mir::visit::{MutVisitor, TyContext}; -use transform::{MirPass, MirSource}; +use crate::transform::{MirPass, MirSource}; struct EraseRegionsVisitor<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx>, diff --git a/src/librustc_mir/transform/generator.rs b/src/librustc_mir/transform/generator.rs index f5cc6a43e28..f408bc0d2fb 100644 --- a/src/librustc_mir/transform/generator.rs +++ b/src/librustc_mir/transform/generator.rs @@ -56,19 +56,19 @@ use rustc::ty::{self, TyCtxt, AdtDef, Ty}; use rustc::ty::layout::VariantIdx; use rustc::ty::subst::Substs; -use util::dump_mir; -use util::liveness::{self, IdentityMap}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::indexed_vec::Idx; use rustc_data_structures::bit_set::BitSet; use std::borrow::Cow; use std::iter::once; use std::mem; -use transform::{MirPass, MirSource}; -use transform::simplify; -use transform::no_landing_pads::no_landing_pads; -use dataflow::{do_dataflow, DebugFormatted, state_for_location}; -use dataflow::{MaybeStorageLive, HaveBeenBorrowedLocals}; +use crate::transform::{MirPass, MirSource}; +use crate::transform::simplify; +use crate::transform::no_landing_pads::no_landing_pads; +use crate::dataflow::{do_dataflow, DebugFormatted, state_for_location}; +use crate::dataflow::{MaybeStorageLive, HaveBeenBorrowedLocals}; +use crate::util::dump_mir; +use crate::util::liveness::{self, IdentityMap}; pub struct StateTransform; @@ -198,7 +198,7 @@ fn set_state(&self, state_disc: u32, source_info: SourceInfo) -> Statement<'tcx> span: source_info.span, ty: self.tcx.types.u32, user_ty: None, - literal: self.tcx.intern_lazy_const(ty::LazyConst::Evaluated(ty::Const::from_bits( + literal: self.tcx.mk_lazy_const(ty::LazyConst::Evaluated(ty::Const::from_bits( self.tcx, state_disc.into(), ty::ParamEnv::empty().and(self.tcx.types.u32) @@ -581,9 +581,9 @@ fn insert_switch<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, fn elaborate_generator_drops<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId, mir: &mut Mir<'tcx>) { - use util::elaborate_drops::{elaborate_drop, Unwind}; - use util::patch::MirPatch; - use shim::DropShimElaborator; + use crate::util::elaborate_drops::{elaborate_drop, Unwind}; + use crate::util::patch::MirPatch; + use crate::shim::DropShimElaborator; // Note that `elaborate_drops` only drops the upvars of a generator, and // this is ok because `open_drop` can only be reached within that own @@ -731,7 +731,7 @@ fn insert_panic_block<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: mir.span, ty: tcx.types.bool, user_ty: None, - literal: tcx.intern_lazy_const(ty::LazyConst::Evaluated( + literal: tcx.mk_lazy_const(ty::LazyConst::Evaluated( ty::Const::from_bool(tcx, false), )), }), diff --git a/src/librustc_mir/transform/inline.rs b/src/librustc_mir/transform/inline.rs index 9f0907adc98..4fddf6f8e09 100644 --- a/src/librustc_mir/transform/inline.rs +++ b/src/librustc_mir/transform/inline.rs @@ -13,10 +13,10 @@ use std::collections::VecDeque; use std::iter; -use transform::{MirPass, MirSource}; +use crate::transform::{MirPass, MirSource}; use super::simplify::{remove_dead_blocks, CfgSimplifier}; -use syntax::{attr}; +use syntax::attr; use rustc_target::spec::abi::Abi; const DEFAULT_THRESHOLD: usize = 50; @@ -426,7 +426,7 @@ fn inline_call(&self, // Place could result in two different locations if `f` // writes to `i`. To prevent this we need to create a temporary // borrow of the place and pass the destination as `*temp` instead. - fn dest_needs_borrow(place: &Place) -> bool { + fn dest_needs_borrow(place: &Place<'_>) -> bool { match *place { Place::Projection(ref p) => { match p.elem { diff --git a/src/librustc_mir/transform/instcombine.rs b/src/librustc_mir/transform/instcombine.rs index 2b5e761d1d0..21772e1f1cd 100644 --- a/src/librustc_mir/transform/instcombine.rs +++ b/src/librustc_mir/transform/instcombine.rs @@ -6,7 +6,7 @@ use rustc::util::nodemap::{FxHashMap, FxHashSet}; use rustc_data_structures::indexed_vec::Idx; use std::mem; -use transform::{MirPass, MirSource}; +use crate::transform::{MirPass, MirSource}; pub struct InstCombine; diff --git a/src/librustc_mir/transform/lower_128bit.rs b/src/librustc_mir/transform/lower_128bit.rs index d14e0f078e6..aa248ba7c53 100644 --- a/src/librustc_mir/transform/lower_128bit.rs +++ b/src/librustc_mir/transform/lower_128bit.rs @@ -5,8 +5,7 @@ use rustc::mir::*; use rustc::ty::{List, Ty, TyCtxt, TyKind}; use rustc_data_structures::indexed_vec::{Idx}; -use transform::{MirPass, MirSource}; -use syntax; +use crate::transform::{MirPass, MirSource}; pub struct Lower128Bit; @@ -182,7 +181,7 @@ fn ty<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option> { } } -fn sign_of_128bit(ty: Ty) -> Option { +fn sign_of_128bit(ty: Ty<'_>) -> Option { match ty.sty { TyKind::Int(syntax::ast::IntTy::I128) => Some(true), TyKind::Uint(syntax::ast::UintTy::U128) => Some(false), diff --git a/src/librustc_mir/transform/mod.rs b/src/librustc_mir/transform/mod.rs index a4f011b2e2e..cc37a8381f2 100644 --- a/src/librustc_mir/transform/mod.rs +++ b/src/librustc_mir/transform/mod.rs @@ -1,5 +1,5 @@ -use borrow_check::nll::type_check; -use build; +use crate::borrow_check::nll::type_check; +use crate::build; use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; use rustc::mir::{Mir, MirPhase, Promoted}; use rustc::ty::TyCtxt; @@ -38,7 +38,7 @@ pub mod lower_128bit; pub mod uniform_array_move_out; -pub(crate) fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers<'_>) { self::qualify_consts::provide(providers); self::check_unsafety::provide(providers); *providers = Providers { diff --git a/src/librustc_mir/transform/no_landing_pads.rs b/src/librustc_mir/transform/no_landing_pads.rs index 2d13b066270..15b59d36d36 100644 --- a/src/librustc_mir/transform/no_landing_pads.rs +++ b/src/librustc_mir/transform/no_landing_pads.rs @@ -4,7 +4,7 @@ use rustc::ty::TyCtxt; use rustc::mir::*; use rustc::mir::visit::MutVisitor; -use transform::{MirPass, MirSource}; +use crate::transform::{MirPass, MirSource}; pub struct NoLandingPads; diff --git a/src/librustc_mir/transform/promote_consts.rs b/src/librustc_mir/transform/promote_consts.rs index 1602fc35a2c..d1dc5cfec99 100644 --- a/src/librustc_mir/transform/promote_consts.rs +++ b/src/librustc_mir/transform/promote_consts.rs @@ -130,7 +130,8 @@ fn visit_source_info(&mut self, source_info: &SourceInfo) { } } -pub fn collect_temps(mir: &Mir, rpo: &mut ReversePostorder) -> IndexVec { +pub fn collect_temps(mir: &Mir<'_>, + rpo: &mut ReversePostorder<'_, '_>) -> IndexVec { let mut collector = TempCollector { temps: IndexVec::from_elem(TempState::Undefined, &mir.local_decls), span: mir.span, diff --git a/src/librustc_mir/transform/qualify_consts.rs b/src/librustc_mir/transform/qualify_consts.rs index 7d1943e21b9..ab4e3ad23f6 100644 --- a/src/librustc_mir/transform/qualify_consts.rs +++ b/src/librustc_mir/transform/qualify_consts.rs @@ -27,10 +27,10 @@ use std::fmt; use std::usize; -use transform::{MirPass, MirSource}; +use crate::transform::{MirPass, MirSource}; use super::promote_consts::{self, Candidate, TempState}; -bitflags! { +bitflags::bitflags! { // Borrows of temporaries can be promoted only if // they have none of these qualifications, with // the exception of `STATIC_REF` (in statics only). @@ -84,7 +84,7 @@ enum Mode { } impl fmt::Display for Mode { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Mode::Const => write!(f, "constant"), Mode::Static | Mode::StaticMut => write!(f, "static"), @@ -1128,7 +1128,7 @@ fn visit_terminator(&mut self, } } -pub fn provide(providers: &mut Providers) { +pub fn provide(providers: &mut Providers<'_>) { *providers = Providers { mir_const_qualif, ..*providers @@ -1317,7 +1317,7 @@ fn run_pass<'a, 'tcx>(&self, } } -fn args_required_const(tcx: TyCtxt, def_id: DefId) -> Option> { +fn args_required_const(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> Option> { let attrs = tcx.get_attrs(def_id); let attr = attrs.iter().find(|a| a.check_name("rustc_args_required_const"))?; let mut ret = FxHashSet::default(); diff --git a/src/librustc_mir/transform/remove_noop_landing_pads.rs b/src/librustc_mir/transform/remove_noop_landing_pads.rs index c8ef2decf26..4fcb4c10f9e 100644 --- a/src/librustc_mir/transform/remove_noop_landing_pads.rs +++ b/src/librustc_mir/transform/remove_noop_landing_pads.rs @@ -1,8 +1,8 @@ use rustc::ty::TyCtxt; use rustc::mir::*; use rustc_data_structures::bit_set::BitSet; -use transform::{MirPass, MirSource}; -use util::patch::MirPatch; +use crate::transform::{MirPass, MirSource}; +use crate::util::patch::MirPatch; /// A pass that removes no-op landing pads and replaces jumps to them with /// `None`. This is important because otherwise LLVM generates terrible @@ -34,7 +34,7 @@ impl RemoveNoopLandingPads { fn is_nop_landing_pad( &self, bb: BasicBlock, - mir: &Mir, + mir: &Mir<'_>, nop_landing_pads: &BitSet, ) -> bool { for stmt in &mir[bb].statements { @@ -86,7 +86,7 @@ fn is_nop_landing_pad( } } - fn remove_nop_landing_pads(&self, mir: &mut Mir) { + fn remove_nop_landing_pads(&self, mir: &mut Mir<'_>) { // make sure there's a single resume block let resume_block = { let patch = MirPatch::new(mir); diff --git a/src/librustc_mir/transform/rustc_peek.rs b/src/librustc_mir/transform/rustc_peek.rs index 36a6279e503..806c1c1cca4 100644 --- a/src/librustc_mir/transform/rustc_peek.rs +++ b/src/librustc_mir/transform/rustc_peek.rs @@ -5,18 +5,20 @@ use rustc::ty::{self, TyCtxt}; use rustc::mir::{self, Mir, Location}; use rustc_data_structures::bit_set::BitSet; -use transform::{MirPass, MirSource}; - -use dataflow::{do_dataflow, DebugFormatted}; -use dataflow::MoveDataParamEnv; -use dataflow::BitDenotation; -use dataflow::DataflowResults; -use dataflow::{DefinitelyInitializedPlaces, MaybeInitializedPlaces, MaybeUninitializedPlaces}; -use dataflow::move_paths::{MovePathIndex, LookupResult}; -use dataflow::move_paths::{HasMoveData, MoveData}; -use dataflow; - -use dataflow::has_rustc_mir_with; +use crate::transform::{MirPass, MirSource}; + +use crate::dataflow::{do_dataflow, DebugFormatted}; +use crate::dataflow::MoveDataParamEnv; +use crate::dataflow::BitDenotation; +use crate::dataflow::DataflowResults; +use crate::dataflow::{ + DefinitelyInitializedPlaces, MaybeInitializedPlaces, MaybeUninitializedPlaces +}; +use crate::dataflow::move_paths::{MovePathIndex, LookupResult}; +use crate::dataflow::move_paths::{HasMoveData, MoveData}; +use crate::dataflow; + +use crate::dataflow::has_rustc_mir_with; pub struct SanityCheck; diff --git a/src/librustc_mir/transform/simplify.rs b/src/librustc_mir/transform/simplify.rs index ed2da98dd53..90486d15664 100644 --- a/src/librustc_mir/transform/simplify.rs +++ b/src/librustc_mir/transform/simplify.rs @@ -34,7 +34,7 @@ use rustc::mir::visit::{MutVisitor, Visitor, PlaceContext}; use rustc::session::config::DebugInfo; use std::borrow::Cow; -use transform::{MirPass, MirSource}; +use crate::transform::{MirPass, MirSource}; pub struct SimplifyCfg { label: String } @@ -44,7 +44,7 @@ pub fn new(label: &str) -> Self { } } -pub fn simplify_cfg(mir: &mut Mir) { +pub fn simplify_cfg(mir: &mut Mir<'_>) { CfgSimplifier::new(mir).simplify(); remove_dead_blocks(mir); @@ -263,7 +263,7 @@ fn strip_nops(&mut self) { } } -pub fn remove_dead_blocks(mir: &mut Mir) { +pub fn remove_dead_blocks(mir: &mut Mir<'_>) { let mut seen = BitSet::new_empty(mir.basic_blocks().len()); for (bb, _) in traversal::preorder(mir) { seen.insert(bb.index()); diff --git a/src/librustc_mir/transform/simplify_branches.rs b/src/librustc_mir/transform/simplify_branches.rs index abaea709463..0dc89bfe147 100644 --- a/src/librustc_mir/transform/simplify_branches.rs +++ b/src/librustc_mir/transform/simplify_branches.rs @@ -2,7 +2,7 @@ use rustc::ty::{TyCtxt, ParamEnv}; use rustc::mir::*; -use transform::{MirPass, MirSource}; +use crate::transform::{MirPass, MirSource}; use std::borrow::Cow; diff --git a/src/librustc_mir/transform/uniform_array_move_out.rs b/src/librustc_mir/transform/uniform_array_move_out.rs index 5ab9669baac..09918436817 100644 --- a/src/librustc_mir/transform/uniform_array_move_out.rs +++ b/src/librustc_mir/transform/uniform_array_move_out.rs @@ -30,9 +30,9 @@ use rustc::ty::TyCtxt; use rustc::mir::*; use rustc::mir::visit::{Visitor, PlaceContext, NonUseContext}; -use transform::{MirPass, MirSource}; -use util::patch::MirPatch; use rustc_data_structures::indexed_vec::{IndexVec}; +use crate::transform::{MirPass, MirSource}; +use crate::util::patch::MirPatch; pub struct UniformArrayMoveOut; diff --git a/src/librustc_mir/util/borrowck_errors.rs b/src/librustc_mir/util/borrowck_errors.rs index 7ad73aaa3f9..fd694ddbbd1 100644 --- a/src/librustc_mir/util/borrowck_errors.rs +++ b/src/librustc_mir/util/borrowck_errors.rs @@ -12,7 +12,7 @@ pub enum Origin { } impl fmt::Display for Origin { - fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result { // If the user passed `-Z borrowck=compare`, then include // origin info as part of the error report, // otherwise @@ -437,7 +437,7 @@ fn cannot_move_out_of( fn cannot_move_out_of_interior_noncopy( self, move_from_span: Span, - ty: ty::Ty, + ty: ty::Ty<'_>, is_index: Option, o: Origin, ) -> DiagnosticBuilder<'cx> { @@ -464,7 +464,7 @@ fn cannot_move_out_of_interior_noncopy( fn cannot_move_out_of_interior_of_drop( self, move_from_span: Span, - container_ty: ty::Ty, + container_ty: ty::Ty<'_>, o: Origin, ) -> DiagnosticBuilder<'cx> { let mut err = struct_span_err!( diff --git a/src/librustc_mir/util/def_use.rs b/src/librustc_mir/util/def_use.rs index 057a7c8be88..3b9d7c3612a 100644 --- a/src/librustc_mir/util/def_use.rs +++ b/src/librustc_mir/util/def_use.rs @@ -107,7 +107,7 @@ pub fn def_count_not_including_drop(&self) -> usize { pub fn defs_not_including_drop( &self, - ) -> iter::Filter>, fn(&&Use<'tcx>) -> bool> { + ) -> iter::Filter>, fn(&&Use<'tcx>) -> bool> { self.defs_and_uses.iter().filter(|place_use| { place_use.context.is_mutating_use() && !place_use.context.is_drop() }) diff --git a/src/librustc_mir/util/elaborate_drops.rs b/src/librustc_mir/util/elaborate_drops.rs index 8b55a4424ae..1bc956e5ffe 100644 --- a/src/librustc_mir/util/elaborate_drops.rs +++ b/src/librustc_mir/util/elaborate_drops.rs @@ -8,7 +8,7 @@ use rustc::ty::subst::Substs; use rustc::ty::util::IntTypeExt; use rustc_data_structures::indexed_vec::Idx; -use util::patch::MirPatch; +use crate::util::patch::MirPatch; use std::u32; @@ -963,7 +963,7 @@ fn constant_usize(&self, val: u16) -> Operand<'tcx> { span: self.source_info.span, ty: self.tcx().types.usize, user_ty: None, - literal: self.tcx().intern_lazy_const(ty::LazyConst::Evaluated( + literal: self.tcx().mk_lazy_const(ty::LazyConst::Evaluated( ty::Const::from_usize(self.tcx(), val.into()) )), }) diff --git a/src/librustc_mir/util/graphviz.rs b/src/librustc_mir/util/graphviz.rs index b68898f7130..e93b96c1216 100644 --- a/src/librustc_mir/util/graphviz.rs +++ b/src/librustc_mir/util/graphviz.rs @@ -1,4 +1,3 @@ -use dot; use rustc::hir::def_id::DefId; use rustc::mir::*; use rustc::ty::TyCtxt; @@ -24,7 +23,7 @@ pub fn write_mir_graphviz<'tcx, W>(tcx: TyCtxt<'_, '_, 'tcx>, /// Write a graphviz DOT graph of the MIR. pub fn write_mir_fn_graphviz<'tcx, W>(tcx: TyCtxt<'_, '_, 'tcx>, def_id: DefId, - mir: &Mir, + mir: &Mir<'_>, w: &mut W) -> io::Result<()> where W: Write { @@ -58,7 +57,7 @@ pub fn write_mir_fn_graphviz<'tcx, W>(tcx: TyCtxt<'_, '_, 'tcx>, /// `init` and `fini` are callbacks for emitting additional rows of /// data (using HTML enclosed with `` in the emitted text). pub fn write_node_label(block: BasicBlock, - mir: &Mir, + mir: &Mir<'_>, w: &mut W, num_cols: u32, init: INIT, @@ -100,7 +99,7 @@ pub fn write_node_label(block: BasicBlock, } /// Write a graphviz DOT node for the given basic block. -fn write_node(block: BasicBlock, mir: &Mir, w: &mut W) -> io::Result<()> { +fn write_node(block: BasicBlock, mir: &Mir<'_>, w: &mut W) -> io::Result<()> { // Start a new node with the label to follow, in one of DOT's pseudo-HTML tables. write!(w, r#" {} [shape="none", label=<"#, node(block))?; write_node_label(block, mir, w, 1, |_| Ok(()), |_| Ok(()))?; @@ -109,7 +108,7 @@ fn write_node(block: BasicBlock, mir: &Mir, w: &mut W) -> io::Result<( } /// Write graphviz DOT edges with labels between the given basic block and all of its successors. -fn write_edges(source: BasicBlock, mir: &Mir, w: &mut W) -> io::Result<()> { +fn write_edges(source: BasicBlock, mir: &Mir<'_>, w: &mut W) -> io::Result<()> { let terminator = mir[source].terminator(); let labels = terminator.kind.fmt_successor_labels(); @@ -125,7 +124,7 @@ fn write_edges(source: BasicBlock, mir: &Mir, w: &mut W) -> io::Result /// all the variables and temporaries. fn write_graph_label<'a, 'gcx, 'tcx, W: Write>(tcx: TyCtxt<'a, 'gcx, 'tcx>, def_id: DefId, - mir: &Mir, + mir: &Mir<'_>, w: &mut W) -> io::Result<()> { write!(w, " label= = BitSet; diff --git a/src/librustc_mir/util/patch.rs b/src/librustc_mir/util/patch.rs index 5a1f94677a1..366cd71f6d4 100644 --- a/src/librustc_mir/util/patch.rs +++ b/src/librustc_mir/util/patch.rs @@ -170,14 +170,14 @@ pub fn apply(self, mir: &mut Mir<'tcx>) { } } - pub fn source_info_for_index(data: &BasicBlockData, loc: Location) -> SourceInfo { + pub fn source_info_for_index(data: &BasicBlockData<'_>, loc: Location) -> SourceInfo { match data.statements.get(loc.statement_index) { Some(stmt) => stmt.source_info, None => data.terminator().source_info } } - pub fn source_info_for_location(&self, mir: &Mir, loc: Location) -> SourceInfo { + pub fn source_info_for_location(&self, mir: &Mir<'_>, loc: Location) -> SourceInfo { let data = match loc.block.index().checked_sub(mir.basic_blocks().len()) { Some(new) => &self.new_blocks[new], None => &mir[loc.block] diff --git a/src/librustc_mir/util/pretty.rs b/src/librustc_mir/util/pretty.rs index 3a15356806a..2e1fc756833 100644 --- a/src/librustc_mir/util/pretty.rs +++ b/src/librustc_mir/util/pretty.rs @@ -12,7 +12,7 @@ use std::io::{self, Write}; use std::path::{Path, PathBuf}; use super::graphviz::write_mir_fn_graphviz; -use transform::MirSource; +use crate::transform::MirSource; const INDENT: &str = " "; /// Alignment for lining up comments following MIR statements @@ -131,7 +131,7 @@ fn dump_matched_mir_node<'a, 'gcx, 'tcx, F>( ) where F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>, { - let _: io::Result<()> = try_block! { + let _: io::Result<()> = try { let mut file = create_dump_file(tcx, "mir", pass_num, pass_name, disambiguator, source)?; writeln!(file, "// MIR for `{}`", node_path)?; writeln!(file, "// source = {:?}", source)?; @@ -148,7 +148,7 @@ fn dump_matched_mir_node<'a, 'gcx, 'tcx, F>( }; if tcx.sess.opts.debugging_opts.dump_mir_graphviz { - let _: io::Result<()> = try_block! { + let _: io::Result<()> = try { let mut file = create_dump_file(tcx, "dot", pass_num, pass_name, disambiguator, source)?; write_mir_fn_graphviz(tcx, source.def_id, mir, &mut file)?; @@ -446,7 +446,7 @@ fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) { } } -fn comment(tcx: TyCtxt, SourceInfo { span, scope }: SourceInfo) -> String { +fn comment(tcx: TyCtxt<'_, '_, '_>, SourceInfo { span, scope }: SourceInfo) -> String { format!( "scope {} at {}", scope.index(), @@ -458,8 +458,8 @@ fn comment(tcx: TyCtxt, SourceInfo { span, scope }: SourceInfo) -> String { /// /// Returns the total number of variables printed. fn write_scope_tree( - tcx: TyCtxt, - mir: &Mir, + tcx: TyCtxt<'_, '_, '_>, + mir: &Mir<'_>, scope_tree: &FxHashMap>, w: &mut dyn Write, parent: SourceScope, @@ -529,7 +529,7 @@ fn write_scope_tree( pub fn write_mir_intro<'a, 'gcx, 'tcx>( tcx: TyCtxt<'a, 'gcx, 'tcx>, src: MirSource, - mir: &Mir, + mir: &Mir<'_>, w: &mut dyn Write, ) -> io::Result<()> { write_mir_sig(tcx, src, mir, w)?; @@ -568,7 +568,12 @@ pub fn write_mir_intro<'a, 'gcx, 'tcx>( Ok(()) } -fn write_mir_sig(tcx: TyCtxt, src: MirSource, mir: &Mir, w: &mut dyn Write) -> io::Result<()> { +fn write_mir_sig( + tcx: TyCtxt<'_, '_, '_>, + src: MirSource, + mir: &Mir<'_>, + w: &mut dyn Write, +) -> io::Result<()> { let id = tcx.hir().as_local_node_id(src.def_id).unwrap(); let body_owner_kind = tcx.hir().body_owner_kind(id); match (body_owner_kind, src.promoted) { @@ -614,7 +619,7 @@ fn write_mir_sig(tcx: TyCtxt, src: MirSource, mir: &Mir, w: &mut dyn Write) -> i Ok(()) } -fn write_temp_decls(mir: &Mir, w: &mut dyn Write) -> io::Result<()> { +fn write_temp_decls(mir: &Mir<'_>, w: &mut dyn Write) -> io::Result<()> { // Compiler-introduced temporary types. for temp in mir.temps_iter() { writeln!( @@ -630,7 +635,7 @@ fn write_temp_decls(mir: &Mir, w: &mut dyn Write) -> io::Result<()> { Ok(()) } -fn write_user_type_annotations(mir: &Mir, w: &mut dyn Write) -> io::Result<()> { +fn write_user_type_annotations(mir: &Mir<'_>, w: &mut dyn Write) -> io::Result<()> { if !mir.user_type_annotations.is_empty() { writeln!(w, "| User Type Annotations")?; } @@ -643,7 +648,7 @@ fn write_user_type_annotations(mir: &Mir, w: &mut dyn Write) -> io::Result<()> { Ok(()) } -pub fn dump_mir_def_ids(tcx: TyCtxt, single: Option) -> Vec { +pub fn dump_mir_def_ids(tcx: TyCtxt<'_, '_, '_>, single: Option) -> Vec { if let Some(i) = single { vec![i] } else { diff --git a/src/librustc_passes/Cargo.toml b/src/librustc_passes/Cargo.toml index f5154a033af..00bdcdc0cc0 100644 --- a/src/librustc_passes/Cargo.toml +++ b/src/librustc_passes/Cargo.toml @@ -2,6 +2,7 @@ authors = ["The Rust Project Developers"] name = "rustc_passes" version = "0.0.0" +edition = "2018" [lib] name = "rustc_passes" @@ -16,4 +17,4 @@ rustc_data_structures = { path = "../librustc_data_structures" } syntax = { path = "../libsyntax" } syntax_ext = { path = "../libsyntax_ext" } syntax_pos = { path = "../libsyntax_pos" } -rustc_errors = { path = "../librustc_errors" } +errors = { path = "../librustc_errors", package = "rustc_errors" } diff --git a/src/librustc_passes/ast_validation.rs b/src/librustc_passes/ast_validation.rs index 3deb2ff8d8a..a391a316312 100644 --- a/src/librustc_passes/ast_validation.rs +++ b/src/librustc_passes/ast_validation.rs @@ -7,18 +7,21 @@ // or type checking or some other kind of complex analysis. use std::mem; +use syntax::print::pprust; use rustc::lint; use rustc::session::Session; +use rustc_data_structures::fx::FxHashMap; use syntax::ast::*; use syntax::attr; use syntax::source_map::Spanned; use syntax::symbol::keywords; use syntax::ptr::P; use syntax::visit::{self, Visitor}; +use syntax::{span_err, struct_span_err, walk_list}; use syntax_ext::proc_macro_decls::is_proc_macro_attr; use syntax_pos::Span; -use errors; use errors::Applicability; +use log::debug; struct AstValidator<'a> { session: &'a Session, @@ -271,7 +274,74 @@ fn while_if_let_expr_ambiguity(&self, expr: &P) -> Option<(Span, BinOpKind _ => None, } } +} +enum GenericPosition { + Param, + Arg, +} + +fn validate_generics_order<'a>( + handler: &errors::Handler, + generics: impl Iterator)>, + pos: GenericPosition, + span: Span, +) { + let mut max_param: Option = None; + let mut out_of_order = FxHashMap::default(); + let mut param_idents = vec![]; + + for (kind, span, ident) in generics { + if let Some(ident) = ident { + param_idents.push((kind, param_idents.len(), ident)); + } + let max_param = &mut max_param; + match max_param { + Some(max_param) if *max_param > kind => { + let entry = out_of_order.entry(kind).or_insert((*max_param, vec![])); + entry.1.push(span); + } + Some(_) | None => *max_param = Some(kind), + }; + } + + let mut ordered_params = "<".to_string(); + if !out_of_order.is_empty() { + param_idents.sort_by_key(|&(po, i, _)| (po, i)); + let mut first = true; + for (_, _, ident) in param_idents { + if !first { + ordered_params += ", "; + } + ordered_params += &ident; + first = false; + } + } + ordered_params += ">"; + + let pos_str = match pos { + GenericPosition::Param => "parameter", + GenericPosition::Arg => "argument", + }; + + for (param_ord, (max_param, spans)) in out_of_order { + let mut err = handler.struct_span_err(spans, + &format!( + "{} {pos}s must be declared prior to {} {pos}s", + param_ord, + max_param, + pos = pos_str, + )); + if let GenericPosition::Param = pos { + err.span_suggestion( + span, + &format!("reorder the {}s: lifetimes, then types, then consts", pos_str), + ordered_params.clone(), + Applicability::MachineApplicable, + ); + } + err.emit(); + } } impl<'a> Visitor<'a> for AstValidator<'a> { @@ -412,6 +482,26 @@ fn visit_item(&mut self, item: &'a Item) { .note("only trait implementations may be annotated with default").emit(); } } + ItemKind::Fn(_, header, ref generics, _) => { + // We currently do not permit const generics in `const fn`, as + // this is tantamount to allowing compile-time dependent typing. + if header.constness.node == Constness::Const { + // Look for const generics and error if we find any. + for param in &generics.params { + match param.kind { + GenericParamKind::Const { .. } => { + self.err_handler() + .struct_span_err( + item.span, + "const parameters are not permitted in `const fn`", + ) + .emit(); + } + _ => {} + } + } + } + } ItemKind::ForeignMod(..) => { self.invalid_visibility( &item.vis, @@ -508,6 +598,13 @@ fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) { match *generic_args { GenericArgs::AngleBracketed(ref data) => { walk_list!(self, visit_generic_arg, &data.args); + validate_generics_order(self.err_handler(), data.args.iter().map(|arg| { + (match arg { + GenericArg::Lifetime(..) => ParamKindOrd::Lifetime, + GenericArg::Type(..) => ParamKindOrd::Type, + GenericArg::Const(..) => ParamKindOrd::Const, + }, arg.span(), None) + }), GenericPosition::Arg, generic_args.span()); // Type bindings such as `Item=impl Debug` in `Iterator` // are allowed to contain nested `impl Trait`. self.with_impl_trait(None, |this| { @@ -526,27 +623,32 @@ fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) { } fn visit_generics(&mut self, generics: &'a Generics) { - let mut seen_non_lifetime_param = false; - let mut seen_default = None; + let mut prev_ty_default = None; for param in &generics.params { - match (¶m.kind, seen_non_lifetime_param) { - (GenericParamKind::Lifetime { .. }, true) => { + if let GenericParamKind::Type { ref default, .. } = param.kind { + if default.is_some() { + prev_ty_default = Some(param.ident.span); + } else if let Some(span) = prev_ty_default { self.err_handler() - .span_err(param.ident.span, "lifetime parameters must be leading"); - }, - (GenericParamKind::Lifetime { .. }, false) => {} - (GenericParamKind::Type { ref default, .. }, _) => { - seen_non_lifetime_param = true; - if default.is_some() { - seen_default = Some(param.ident.span); - } else if let Some(span) = seen_default { - self.err_handler() - .span_err(span, "type parameters with a default must be trailing"); - break; - } + .span_err(span, "type parameters with a default must be trailing"); + break; } } } + + validate_generics_order(self.err_handler(), generics.params.iter().map(|param| { + let span = param.ident.span; + let ident = Some(param.ident.to_string()); + match ¶m.kind { + GenericParamKind::Lifetime { .. } => (ParamKindOrd::Lifetime, span, ident), + GenericParamKind::Type { .. } => (ParamKindOrd::Type, span, ident), + GenericParamKind::Const { ref ty } => { + let ty = pprust::ty_to_string(ty); + (ParamKindOrd::Const, span, Some(format!("const {}: {}", param.ident, ty))) + } + } + }), GenericPosition::Param, generics.span); + for predicate in &generics.where_clause.predicates { if let WherePredicate::EqPredicate(ref predicate) = *predicate { self.err_handler() @@ -554,6 +656,7 @@ fn visit_generics(&mut self, generics: &'a Generics) { supported in where clauses (see #20041)"); } } + visit::walk_generics(self, generics) } diff --git a/src/librustc_passes/diagnostics.rs b/src/librustc_passes/diagnostics.rs index 037227aeb71..19d4d3aeb0f 100644 --- a/src/librustc_passes/diagnostics.rs +++ b/src/librustc_passes/diagnostics.rs @@ -1,5 +1,7 @@ #![allow(non_snake_case)] +use syntax::{register_diagnostic, register_diagnostics, register_long_diagnostics}; + register_long_diagnostics! { /* E0014: r##" diff --git a/src/librustc_passes/hir_stats.rs b/src/librustc_passes/hir_stats.rs index 74d6d75a7f5..2427abad07c 100644 --- a/src/librustc_passes/hir_stats.rs +++ b/src/librustc_passes/hir_stats.rs @@ -61,7 +61,7 @@ fn record(&mut self, label: &'static str, id: Id, node: &T) { }); entry.count += 1; - entry.size = ::std::mem::size_of_val(node); + entry.size = std::mem::size_of_val(node); } fn print(&self, title: &str) { diff --git a/src/librustc_passes/lib.rs b/src/librustc_passes/lib.rs index 625f2fcb249..ff2e345d084 100644 --- a/src/librustc_passes/lib.rs +++ b/src/librustc_passes/lib.rs @@ -11,18 +11,10 @@ #![recursion_limit="256"] -#[macro_use] -extern crate rustc; -extern crate rustc_mir; -extern crate rustc_data_structures; +#![deny(rust_2018_idioms)] #[macro_use] -extern crate log; -#[macro_use] -extern crate syntax; -extern crate syntax_ext; -extern crate syntax_pos; -extern crate rustc_errors as errors; +extern crate rustc; use rustc::ty::query::Providers; @@ -36,7 +28,7 @@ __build_diagnostic_array! { librustc_passes, DIAGNOSTICS } -pub fn provide(providers: &mut Providers) { +pub fn provide(providers: &mut Providers<'_>) { rvalue_promotion::provide(providers); loops::provide(providers); } diff --git a/src/librustc_passes/loops.rs b/src/librustc_passes/loops.rs index f05a7be7d75..533e043efa9 100644 --- a/src/librustc_passes/loops.rs +++ b/src/librustc_passes/loops.rs @@ -1,4 +1,4 @@ -use self::Context::*; +use Context::*; use rustc::session::Session; @@ -9,6 +9,7 @@ use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap}; use rustc::hir::{self, Node, Destination}; use syntax::ast; +use syntax::struct_span_err; use syntax_pos::Span; use errors::Applicability; @@ -59,7 +60,7 @@ fn check_mod_loops<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>, module_def_id: DefId) { }.as_deep_visitor()); } -pub(crate) fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers<'_>) { *providers = Providers { check_mod_loops, ..*providers diff --git a/src/librustc_passes/rvalue_promotion.rs b/src/librustc_passes/rvalue_promotion.rs index 739c96934e6..8d33fef5303 100644 --- a/src/librustc_passes/rvalue_promotion.rs +++ b/src/librustc_passes/rvalue_promotion.rs @@ -28,10 +28,11 @@ use rustc_data_structures::sync::Lrc; use syntax::ast; use syntax_pos::{Span, DUMMY_SP}; -use self::Promotability::*; +use log::debug; +use Promotability::*; use std::ops::{BitAnd, BitAndAssign, BitOr}; -pub fn provide(providers: &mut Providers) { +pub fn provide(providers: &mut Providers<'_>) { *providers = Providers { rvalue_promotable_map, const_is_rvalue_promotable_to_static, @@ -621,7 +622,7 @@ impl<'a, 'gcx, 'tcx> euv::Delegate<'tcx> for CheckCrateVisitor<'a, 'gcx> { fn consume(&mut self, _consume_id: ast::NodeId, _consume_span: Span, - _cmt: &mc::cmt_, + _cmt: &mc::cmt_<'_>, _mode: euv::ConsumeMode) {} fn borrow(&mut self, @@ -680,11 +681,14 @@ fn decl_without_init(&mut self, _id: ast::NodeId, _span: Span) {} fn mutate(&mut self, _assignment_id: ast::NodeId, _assignment_span: Span, - _assignee_cmt: &mc::cmt_, + _assignee_cmt: &mc::cmt_<'_>, _mode: euv::MutateMode) { } - fn matched_pat(&mut self, _: &hir::Pat, _: &mc::cmt_, _: euv::MatchMode) {} + fn matched_pat(&mut self, _: &hir::Pat, _: &mc::cmt_<'_>, _: euv::MatchMode) {} - fn consume_pat(&mut self, _consume_pat: &hir::Pat, _cmt: &mc::cmt_, _mode: euv::ConsumeMode) {} + fn consume_pat(&mut self, + _consume_pat: &hir::Pat, + _cmt: &mc::cmt_<'_>, + _mode: euv::ConsumeMode) {} } diff --git a/src/librustc_resolve/diagnostics.rs b/src/librustc_resolve/diagnostics.rs index 0db8689c0c1..5c095994a1b 100644 --- a/src/librustc_resolve/diagnostics.rs +++ b/src/librustc_resolve/diagnostics.rs @@ -414,8 +414,8 @@ fn main() {} "##, E0401: r##" -Inner items do not inherit type parameters from the functions they are embedded -in. +Inner items do not inherit type or const parameters from the functions +they are embedded in. Erroneous code example: diff --git a/src/librustc_resolve/error_reporting.rs b/src/librustc_resolve/error_reporting.rs index b131a6b62f9..8300e691bbe 100644 --- a/src/librustc_resolve/error_reporting.rs +++ b/src/librustc_resolve/error_reporting.rs @@ -1,16 +1,423 @@ -use crate::{CrateLint, PathResult, Segment}; -use crate::macros::ParentScope; -use crate::resolve_imports::ImportResolver; +use std::cmp::Reverse; +use log::debug; +use rustc::hir::def::*; +use rustc::hir::def::Namespace::*; +use rustc::hir::def_id::{CRATE_DEF_INDEX, DefId}; +use rustc::session::config::nightly_options; +use syntax::ast::{ExprKind}; use syntax::symbol::keywords; use syntax_pos::Span; -use log::debug; +use crate::errors::{Applicability, DiagnosticBuilder, DiagnosticId}; +use crate::macros::ParentScope; +use crate::resolve_imports::ImportResolver; +use crate::{import_candidate_to_enum_paths, is_self_type, is_self_value, path_names_to_string}; +use crate::{AssocSuggestion, CrateLint, ImportSuggestion, ModuleOrUniformRoot, PathResult, + PathSource, Resolver, Segment}; -use std::cmp::Reverse; +impl<'a> Resolver<'a> { + /// Handles error reporting for `smart_resolve_path_fragment` function. + /// Creates base error and amends it with one short label and possibly some longer helps/notes. + pub(crate) fn smart_resolve_report_errors( + &mut self, + path: &[Segment], + span: Span, + source: PathSource<'_>, + def: Option, + ) -> (DiagnosticBuilder<'a>, Vec) { + let ident_span = path.last().map_or(span, |ident| ident.ident.span); + let ns = source.namespace(); + let is_expected = &|def| source.is_expected(def); + let is_enum_variant = &|def| if let Def::Variant(..) = def { true } else { false }; + + // Make the base error. + let expected = source.descr_expected(); + let path_str = Segment::names_to_string(path); + let item_str = path.last().unwrap().ident; + let code = source.error_code(def.is_some()); + let (base_msg, fallback_label, base_span) = if let Some(def) = def { + (format!("expected {}, found {} `{}`", expected, def.kind_name(), path_str), + format!("not a {}", expected), + span) + } else { + let item_span = path.last().unwrap().ident.span; + let (mod_prefix, mod_str) = if path.len() == 1 { + (String::new(), "this scope".to_string()) + } else if path.len() == 2 && path[0].ident.name == keywords::PathRoot.name() { + (String::new(), "the crate root".to_string()) + } else { + let mod_path = &path[..path.len() - 1]; + let mod_prefix = match self.resolve_path_without_parent_scope( + mod_path, Some(TypeNS), false, span, CrateLint::No + ) { + PathResult::Module(ModuleOrUniformRoot::Module(module)) => + module.def(), + _ => None, + }.map_or(String::new(), |def| format!("{} ", def.kind_name())); + (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path))) + }; + (format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str), + format!("not found in {}", mod_str), + item_span) + }; + + let code = DiagnosticId::Error(code.into()); + let mut err = self.session.struct_span_err_with_code(base_span, &base_msg, code); + + // Emit help message for fake-self from other languages (e.g., `this` in Javascript). + if ["this", "my"].contains(&&*item_str.as_str()) + && self.self_value_is_available(path[0].ident.span, span) { + err.span_suggestion( + span, + "did you mean", + "self".to_string(), + Applicability::MaybeIncorrect, + ); + } + + // Emit special messages for unresolved `Self` and `self`. + if is_self_type(path, ns) { + __diagnostic_used!(E0411); + err.code(DiagnosticId::Error("E0411".into())); + err.span_label(span, format!("`Self` is only available in impls, traits, \ + and type definitions")); + return (err, Vec::new()); + } + if is_self_value(path, ns) { + debug!("smart_resolve_path_fragment: E0424, source={:?}", source); + + __diagnostic_used!(E0424); + err.code(DiagnosticId::Error("E0424".into())); + err.span_label(span, match source { + PathSource::Pat => { + format!("`self` value is a keyword \ + and may not be bound to \ + variables or shadowed") + } + _ => { + format!("`self` value is a keyword \ + only available in methods \ + with `self` parameter") + } + }); + return (err, Vec::new()); + } + + // Try to lookup name in more relaxed fashion for better error reporting. + let ident = path.last().unwrap().ident; + let candidates = self.lookup_import_candidates(ident, ns, is_expected); + if candidates.is_empty() && is_expected(Def::Enum(DefId::local(CRATE_DEF_INDEX))) { + let enum_candidates = + self.lookup_import_candidates(ident, ns, is_enum_variant); + let mut enum_candidates = enum_candidates.iter() + .map(|suggestion| { + import_candidate_to_enum_paths(&suggestion) + }).collect::>(); + enum_candidates.sort(); + + if !enum_candidates.is_empty() { + // Contextualize for E0412 "cannot find type", but don't belabor the point + // (that it's a variant) for E0573 "expected type, found variant". + let preamble = if def.is_none() { + let others = match enum_candidates.len() { + 1 => String::new(), + 2 => " and 1 other".to_owned(), + n => format!(" and {} others", n) + }; + format!("there is an enum variant `{}`{}; ", + enum_candidates[0].0, others) + } else { + String::new() + }; + let msg = format!("{}try using the variant's enum", preamble); + + err.span_suggestions( + span, + &msg, + enum_candidates.into_iter() + .map(|(_variant_path, enum_ty_path)| enum_ty_path) + // Variants re-exported in prelude doesn't mean `prelude::v1` is the + // type name! + // FIXME: is there a more principled way to do this that + // would work for other re-exports? + .filter(|enum_ty_path| enum_ty_path != "std::prelude::v1") + // Also write `Option` rather than `std::prelude::v1::Option`. + .map(|enum_ty_path| { + // FIXME #56861: DRY-er prelude filtering. + enum_ty_path.trim_start_matches("std::prelude::v1::").to_owned() + }), + Applicability::MachineApplicable, + ); + } + } + if path.len() == 1 && self.self_type_is_available(span) { + if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) { + let self_is_available = self.self_value_is_available(path[0].ident.span, span); + match candidate { + AssocSuggestion::Field => { + err.span_suggestion( + span, + "try", + format!("self.{}", path_str), + Applicability::MachineApplicable, + ); + if !self_is_available { + err.span_label(span, format!("`self` value is a keyword \ + only available in \ + methods with `self` parameter")); + } + } + AssocSuggestion::MethodWithSelf if self_is_available => { + err.span_suggestion( + span, + "try", + format!("self.{}", path_str), + Applicability::MachineApplicable, + ); + } + AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => { + err.span_suggestion( + span, + "try", + format!("Self::{}", path_str), + Applicability::MachineApplicable, + ); + } + } + return (err, candidates); + } + } + + let mut levenshtein_worked = false; + + // Try Levenshtein algorithm. + let suggestion = self.lookup_typo_candidate(path, ns, is_expected, span); + if let Some(suggestion) = suggestion { + let msg = format!( + "{} {} with a similar name exists", + suggestion.article, suggestion.kind + ); + err.span_suggestion( + ident_span, + &msg, + suggestion.candidate.to_string(), + Applicability::MaybeIncorrect, + ); + + levenshtein_worked = true; + } + + // Try context-dependent help if relaxed lookup didn't work. + if let Some(def) = def { + if self.smart_resolve_context_dependent_help(&mut err, + span, + source, + def, + &path_str, + &fallback_label) { + return (err, candidates); + } + } + + // Fallback label. + if !levenshtein_worked { + err.span_label(base_span, fallback_label); + self.type_ascription_suggestion(&mut err, base_span); + } + (err, candidates) + } + + /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment` + /// function. + /// Returns `true` if able to provide context-dependent help. + fn smart_resolve_context_dependent_help( + &mut self, + err: &mut DiagnosticBuilder<'a>, + span: Span, + source: PathSource<'_>, + def: Def, + path_str: &str, + fallback_label: &str, + ) -> bool { + let ns = source.namespace(); + let is_expected = &|def| source.is_expected(def); + + match (def, source) { + (Def::Macro(..), _) => { + err.span_suggestion( + span, + "use `!` to invoke the macro", + format!("{}!", path_str), + Applicability::MaybeIncorrect, + ); + } + (Def::TyAlias(..), PathSource::Trait(_)) => { + err.span_label(span, "type aliases cannot be used as traits"); + if nightly_options::is_nightly_build() { + err.note("did you mean to use a trait alias?"); + } + } + (Def::Mod(..), PathSource::Expr(Some(parent))) => match parent.node { + ExprKind::Field(_, ident) => { + err.span_suggestion( + parent.span, + "use the path separator to refer to an item", + format!("{}::{}", path_str, ident), + Applicability::MaybeIncorrect, + ); + } + ExprKind::MethodCall(ref segment, ..) => { + let span = parent.span.with_hi(segment.ident.span.hi()); + err.span_suggestion( + span, + "use the path separator to refer to an item", + format!("{}::{}", path_str, segment.ident), + Applicability::MaybeIncorrect, + ); + } + _ => return false, + }, + (Def::Enum(..), PathSource::TupleStruct) + | (Def::Enum(..), PathSource::Expr(..)) => { + if let Some(variants) = self.collect_enum_variants(def) { + err.note(&format!("did you mean to use one \ + of the following variants?\n{}", + variants.iter() + .map(|suggestion| path_names_to_string(suggestion)) + .map(|suggestion| format!("- `{}`", suggestion)) + .collect::>() + .join("\n"))); + } else { + err.note("did you mean to use one of the enum's variants?"); + } + }, + (Def::Struct(def_id), _) if ns == ValueNS => { + if let Some((ctor_def, ctor_vis)) + = self.struct_constructors.get(&def_id).cloned() { + let accessible_ctor = self.is_accessible(ctor_vis); + if is_expected(ctor_def) && !accessible_ctor { + err.span_label(span, format!("constructor is not visible \ + here due to private fields")); + } + } else { + // HACK(estebank): find a better way to figure out that this was a + // parser issue where a struct literal is being used on an expression + // where a brace being opened means a block is being started. Look + // ahead for the next text to see if `span` is followed by a `{`. + let sm = self.session.source_map(); + let mut sp = span; + loop { + sp = sm.next_point(sp); + match sm.span_to_snippet(sp) { + Ok(ref snippet) => { + if snippet.chars().any(|c| { !c.is_whitespace() }) { + break; + } + } + _ => break, + } + } + let followed_by_brace = match sm.span_to_snippet(sp) { + Ok(ref snippet) if snippet == "{" => true, + _ => false, + }; + // In case this could be a struct literal that needs to be surrounded + // by parenthesis, find the appropriate span. + let mut i = 0; + let mut closing_brace = None; + loop { + sp = sm.next_point(sp); + match sm.span_to_snippet(sp) { + Ok(ref snippet) => { + if snippet == "}" { + let sp = span.to(sp); + if let Ok(snippet) = sm.span_to_snippet(sp) { + closing_brace = Some((sp, snippet)); + } + break; + } + } + _ => break, + } + i += 1; + // The bigger the span, the more likely we're incorrect -- + // bound it to 100 chars long. + if i > 100 { + break; + } + } + match source { + PathSource::Expr(Some(parent)) => { + match parent.node { + ExprKind::MethodCall(ref path_assignment, _) => { + err.span_suggestion( + sm.start_point(parent.span) + .to(path_assignment.ident.span), + "use `::` to access an associated function", + format!("{}::{}", + path_str, + path_assignment.ident), + Applicability::MaybeIncorrect + ); + }, + _ => { + err.span_label( + span, + format!("did you mean `{} {{ /* fields */ }}`?", + path_str), + ); + }, + } + }, + PathSource::Expr(None) if followed_by_brace == true => { + if let Some((sp, snippet)) = closing_brace { + err.span_suggestion( + sp, + "surround the struct literal with parenthesis", + format!("({})", snippet), + Applicability::MaybeIncorrect, + ); + } else { + err.span_label( + span, + format!("did you mean `({} {{ /* fields */ }})`?", + path_str), + ); + } + }, + _ => { + err.span_label( + span, + format!("did you mean `{} {{ /* fields */ }}`?", + path_str), + ); + }, + } + } + } + (Def::Union(..), _) | + (Def::Variant(..), _) | + (Def::VariantCtor(_, CtorKind::Fictive), _) if ns == ValueNS => { + err.span_label(span, format!("did you mean `{} {{ /* fields */ }}`?", + path_str)); + } + (Def::SelfTy(..), _) if ns == ValueNS => { + err.span_label(span, fallback_label); + err.note("can't use `Self` as a constructor, you must use the \ + implemented struct"); + } + (Def::TyAlias(_), _) | (Def::AssociatedTy(..), _) if ns == ValueNS => { + err.note("can't use a type alias as a constructor"); + } + _ => return false, + } + true + } +} impl<'a, 'b:'a> ImportResolver<'a, 'b> { - /// Add suggestions for a path that cannot be resolved. + /// Adds suggestions for a path that cannot be resolved. pub(crate) fn make_path_suggestion( &mut self, span: Span, @@ -24,7 +431,7 @@ pub(crate) fn make_path_suggestion( // On 2015 `{{root}}` is usually added implicitly. (Some(fst), Some(snd)) if fst.ident.name == keywords::PathRoot.name() && !snd.ident.is_path_segment_keyword() => {} - // `ident::...` on 2018 + // `ident::...` on 2018. (Some(fst), _) if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() => { // Insert a placeholder that's later replaced by `self`/`super`/etc. @@ -63,7 +470,7 @@ fn make_missing_self_suggestion( } } - /// Suggest a missing `crate::` if that resolves to an correct module. + /// Suggests a missing `crate::` if that resolves to an correct module. /// /// ``` /// | @@ -94,7 +501,7 @@ fn make_missing_crate_suggestion( } } - /// Suggest a missing `super::` if that resolves to an correct module. + /// Suggests a missing `super::` if that resolves to an correct module. /// /// ``` /// | @@ -118,7 +525,7 @@ fn make_missing_super_suggestion( } } - /// Suggest a missing external crate name if that resolves to an correct module. + /// Suggests a missing external crate name if that resolves to an correct module. /// /// ``` /// | @@ -139,7 +546,7 @@ fn make_external_crate_suggestion( } // Sort extern crate names in reverse order to get - // 1) some consistent ordering for emitted dignostics and + // 1) some consistent ordering for emitted dignostics, and // 2) `std` suggestions before `core` suggestions. let mut extern_crate_names = self.resolver.extern_prelude.iter().map(|(ident, _)| ident.name).collect::>(); diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 270f2424197..ecbfcec3c5e 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -13,7 +13,7 @@ pub use rustc::hir::def::{Namespace, PerNS}; -use TypeParameters::*; +use GenericParameters::*; use RibKind::*; use rustc::hir::map::{Definitions, DefCollector}; @@ -25,7 +25,6 @@ use rustc::hir::def::Namespace::*; use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId}; use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap}; -use rustc::session::config::nightly_options; use rustc::ty; use rustc::util::nodemap::{NodeMap, NodeSet, FxHashMap, FxHashSet, DefIdMap}; use rustc::{bug, span_bug}; @@ -140,10 +139,11 @@ fn cmp(&self, other: &BindingError) -> cmp::Ordering { } enum ResolutionError<'a> { - /// error E0401: can't use type parameters from outer function - TypeParametersFromOuterFunction(Def), - /// error E0403: the name is already used for a type parameter in this type parameter list - NameAlreadyUsedInTypeParameterList(Name, &'a Span), + /// error E0401: can't use type or const parameters from outer function + GenericParamsFromOuterFunction(Def), + /// error E0403: the name is already used for a type/const parameter in this list of + /// generic parameters + NameAlreadyUsedInParameterList(Name, &'a Span), /// error E0407: method is not a member of trait MethodNotMemberOfTrait(Name, &'a str), /// error E0437: type is not a member of trait @@ -175,7 +175,7 @@ enum ResolutionError<'a> { /// error E0530: X bindings cannot shadow Ys BindingShadowsSomethingUnacceptable(&'a str, Name, &'a NameBinding<'a>), /// error E0128: type parameters with a default cannot use forward declared identifiers - ForwardDeclaredTyParam, + ForwardDeclaredTyParam, // FIXME(const_generics:defaults) } /// Combines an error with provided span and emits it @@ -193,12 +193,13 @@ fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver<'_>, resolution_error: ResolutionError<'a>) -> DiagnosticBuilder<'sess> { match resolution_error { - ResolutionError::TypeParametersFromOuterFunction(outer_def) => { + ResolutionError::GenericParamsFromOuterFunction(outer_def) => { let mut err = struct_span_err!(resolver.session, - span, - E0401, - "can't use type parameters from outer function"); - err.span_label(span, "use of type variable from outer function"); + span, + E0401, + "can't use generic parameters from outer function", + ); + err.span_label(span, format!("use of generic parameter from outer function")); let cm = resolver.session.source_map(); match outer_def { @@ -222,20 +223,25 @@ fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver<'_>, } return err; }, - Def::TyParam(typaram_defid) => { - if let Some(typaram_span) = resolver.definitions.opt_span(typaram_defid) { - err.span_label(typaram_span, "type variable from outer function"); + Def::TyParam(def_id) => { + if let Some(span) = resolver.definitions.opt_span(def_id) { + err.span_label(span, "type variable from outer function"); } - }, + } + Def::ConstParam(def_id) => { + if let Some(span) = resolver.definitions.opt_span(def_id) { + err.span_label(span, "const variable from outer function"); + } + } _ => { - bug!("TypeParametersFromOuterFunction should only be used with Def::SelfTy or \ - Def::TyParam") + bug!("GenericParamsFromOuterFunction should only be used with Def::SelfTy, \ + Def::TyParam"); } } // Try to retrieve the span of the function signature and generate a new message with - // a local type parameter - let sugg_msg = "try using a local type parameter instead"; + // a local type or const parameter. + let sugg_msg = &format!("try using a local generic parameter instead"); if let Some((sugg_span, new_snippet)) = cm.generate_local_type_param_snippet(span) { // Suggest the modification to the user err.span_suggestion( @@ -245,19 +251,20 @@ fn resolve_struct_error<'sess, 'a>(resolver: &'sess Resolver<'_>, Applicability::MachineApplicable, ); } else if let Some(sp) = cm.generate_fn_name_span(span) { - err.span_label(sp, "try adding a local type parameter in this method instead"); + err.span_label(sp, + format!("try adding a local generic parameter in this method instead")); } else { - err.help("try using a local type parameter instead"); + err.help(&format!("try using a local generic parameter instead")); } err } - ResolutionError::NameAlreadyUsedInTypeParameterList(name, first_use_span) => { + ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => { let mut err = struct_span_err!(resolver.session, span, E0403, - "the name `{}` is already used for a type parameter \ - in this type parameter list", + "the name `{}` is already used for a generic \ + parameter in this list of generic parameters", name); err.span_label(span, "already used"); err.span_label(first_use_span.clone(), format!("first use of `{}`", name)); @@ -544,8 +551,7 @@ fn is_expected(self, def: Def) -> bool { Def::Struct(..) | Def::Union(..) | Def::Enum(..) | Def::Trait(..) | Def::TraitAlias(..) | Def::TyAlias(..) | Def::AssociatedTy(..) | Def::PrimTy(..) | Def::TyParam(..) | - Def::SelfTy(..) | Def::Existential(..) | - Def::ForeignTy(..) => true, + Def::SelfTy(..) | Def::Existential(..) | Def::ForeignTy(..) => true, _ => false, }, PathSource::Trait(AliasPossibility::No) => match def { @@ -562,7 +568,7 @@ fn is_expected(self, def: Def) -> bool { Def::VariantCtor(_, CtorKind::Const) | Def::VariantCtor(_, CtorKind::Fn) | Def::Const(..) | Def::Static(..) | Def::Local(..) | Def::Upvar(..) | Def::Fn(..) | Def::Method(..) | Def::AssociatedConst(..) | - Def::SelfCtor(..) => true, + Def::SelfCtor(..) | Def::ConstParam(..) => true, _ => false, }, PathSource::Pat => match def { @@ -746,6 +752,7 @@ fn visit_block(&mut self, block: &'tcx Block) { self.resolve_block(block); } fn visit_anon_const(&mut self, constant: &'tcx ast::AnonConst) { + debug!("visit_anon_const {:?}", constant); self.with_constant_rib(|this| { visit::walk_anon_const(this, constant); }); @@ -779,15 +786,15 @@ fn visit_poly_trait_ref(&mut self, visit::walk_poly_trait_ref(self, tref, m); } fn visit_foreign_item(&mut self, foreign_item: &'tcx ForeignItem) { - let type_parameters = match foreign_item.node { + let generic_params = match foreign_item.node { ForeignItemKind::Fn(_, ref generics) => { - HasTypeParameters(generics, ItemRibKind) + HasGenericParams(generics, ItemRibKind) } - ForeignItemKind::Static(..) => NoTypeParameters, - ForeignItemKind::Ty => NoTypeParameters, - ForeignItemKind::Macro(..) => NoTypeParameters, + ForeignItemKind::Static(..) => NoGenericParams, + ForeignItemKind::Ty => NoGenericParams, + ForeignItemKind::Macro(..) => NoGenericParams, }; - self.with_type_parameter_rib(type_parameters, |this| { + self.with_generic_param_rib(generic_params, |this| { visit::walk_foreign_item(this, foreign_item); }); } @@ -797,6 +804,7 @@ fn visit_fn(&mut self, _: Span, node_id: NodeId) { + debug!("(resolving function) entering function"); let (rib_kind, asyncness) = match function_kind { FnKind::ItemFn(_, ref header, ..) => (ItemRibKind, header.asyncness), @@ -853,6 +861,7 @@ fn visit_fn(&mut self, self.label_ribs.pop(); self.ribs[ValueNS].pop(); } + fn visit_generics(&mut self, generics: &'tcx Generics) { // For type parameter defaults, we have to ban access // to following type parameters, as the Substs can only @@ -863,6 +872,7 @@ fn visit_generics(&mut self, generics: &'tcx Generics) { let mut found_default = false; default_ban_rib.bindings.extend(generics.params.iter() .filter_map(|param| match param.kind { + GenericParamKind::Const { .. } | GenericParamKind::Lifetime { .. } => None, GenericParamKind::Type { ref default, .. } => { found_default |= default.is_some(); @@ -891,6 +901,13 @@ fn visit_generics(&mut self, generics: &'tcx Generics) { // Allow all following defaults to refer to this type parameter. default_ban_rib.bindings.remove(&Ident::with_empty_ctxt(param.ident.name)); } + GenericParamKind::Const { ref ty } => { + for bound in ¶m.bounds { + self.visit_param_bound(bound); + } + + self.visit_ty(ty); + } } } for p in &generics.where_clause.predicates { @@ -900,9 +917,9 @@ fn visit_generics(&mut self, generics: &'tcx Generics) { } #[derive(Copy, Clone)] -enum TypeParameters<'a, 'b> { - NoTypeParameters, - HasTypeParameters(// Type parameters. +enum GenericParameters<'a, 'b> { + NoGenericParams, + HasGenericParams(// Type parameters. &'b Generics, // The kind of the rib used for type parameters. @@ -1738,7 +1755,7 @@ pub fn resolve_str_path_error(&mut self, span: Span, path_str: &str, is_value: b } } - /// resolve_hir_path, but takes a callback in case there was an error + /// Like `resolve_hir_path`, but takes a callback in case there was an error. fn resolve_hir_path_cb( &mut self, path: &ast::Path, @@ -1751,7 +1768,7 @@ fn resolve_hir_path_cb( let span = path.span; let segments = &path.segments; let path = Segment::from_path(&path); - // FIXME (Manishearth): Intra doc links won't get warned of epoch changes + // FIXME(Manishearth): intra-doc links won't get warned of epoch changes. let def = match self.resolve_path_without_parent_scope(&path, Some(namespace), true, span, CrateLint::No) { PathResult::Module(ModuleOrUniformRoot::Module(module)) => @@ -2038,6 +2055,7 @@ fn resolve_ident_in_lexical_scope(&mut self, let record_used = record_used_id.is_some(); let mut module = self.graph_root; for i in (0 .. self.ribs[ns].len()).rev() { + debug!("walk rib\n{:?}", self.ribs[ns][i].bindings); if let Some(def) = self.ribs[ns][i].bindings.get(&ident).cloned() { // The ident resolves to a type parameter or local variable. return Some(LexicalScopeBinding::Def( @@ -2359,8 +2377,9 @@ fn search_label(&self, mut ident: Ident, pred: P) -> Option } fn resolve_adt(&mut self, item: &Item, generics: &Generics) { + debug!("resolve_adt"); self.with_current_self_item(item, |this| { - this.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| { + this.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| { let item_def_id = this.definitions.local_def_id(item.id); this.with_self_rib(Def::SelfTy(None, Some(item_def_id)), |this| { visit::walk_item(this, item); @@ -2413,13 +2432,13 @@ fn future_proof_import(&mut self, use_tree: &ast::UseTree) { fn resolve_item(&mut self, item: &Item) { let name = item.ident.name; - debug!("(resolving item) resolving {}", name); + debug!("(resolving item) resolving {} ({:?})", name, item.node); match item.node { ItemKind::Ty(_, ref generics) | ItemKind::Fn(_, _, ref generics, _) | ItemKind::Existential(_, ref generics) => { - self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), + self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| visit::walk_item(this, item)); } @@ -2438,16 +2457,16 @@ fn resolve_item(&mut self, item: &Item) { ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => { // Create a new rib for the trait-wide type parameters. - self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| { + self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| { let local_def_id = this.definitions.local_def_id(item.id); this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| { this.visit_generics(generics); walk_list!(this, visit_param_bound, bounds); for trait_item in trait_items { - let type_parameters = HasTypeParameters(&trait_item.generics, + let generic_params = HasGenericParams(&trait_item.generics, TraitOrImplItemRibKind); - this.with_type_parameter_rib(type_parameters, |this| { + this.with_generic_param_rib(generic_params, |this| { match trait_item.node { TraitItemKind::Const(ref ty, ref default) => { this.visit_ty(ty); @@ -2479,7 +2498,7 @@ fn resolve_item(&mut self, item: &Item) { ItemKind::TraitAlias(ref generics, ref bounds) => { // Create a new rib for the trait-wide type parameters. - self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| { + self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| { let local_def_id = this.definitions.local_def_id(item.id); this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| { this.visit_generics(generics); @@ -2496,6 +2515,7 @@ fn resolve_item(&mut self, item: &Item) { ItemKind::Static(ref ty, _, ref expr) | ItemKind::Const(ref ty, ref expr) => { + debug!("resolve_item ItemKind::Const"); self.with_item_rib(|this| { this.visit_ty(ty); this.with_constant_rib(|this| { @@ -2517,23 +2537,25 @@ fn resolve_item(&mut self, item: &Item) { } } - fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<'a, 'b>, f: F) + fn with_generic_param_rib<'b, F>(&'b mut self, generic_params: GenericParameters<'a, 'b>, f: F) where F: FnOnce(&mut Resolver<'_>) { - match type_parameters { - HasTypeParameters(generics, rib_kind) => { + debug!("with_generic_param_rib"); + match generic_params { + HasGenericParams(generics, rib_kind) => { let mut function_type_rib = Rib::new(rib_kind); + let mut function_value_rib = Rib::new(rib_kind); let mut seen_bindings = FxHashMap::default(); for param in &generics.params { match param.kind { GenericParamKind::Lifetime { .. } => {} GenericParamKind::Type { .. } => { let ident = param.ident.modern(); - debug!("with_type_parameter_rib: {}", param.id); + debug!("with_generic_param_rib: {}", param.id); if seen_bindings.contains_key(&ident) { let span = seen_bindings.get(&ident).unwrap(); - let err = ResolutionError::NameAlreadyUsedInTypeParameterList( + let err = ResolutionError::NameAlreadyUsedInParameterList( ident.name, span, ); @@ -2546,20 +2568,40 @@ fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters< function_type_rib.bindings.insert(ident, def); self.record_def(param.id, PathResolution::new(def)); } + GenericParamKind::Const { .. } => { + let ident = param.ident.modern(); + debug!("with_generic_param_rib: {}", param.id); + + if seen_bindings.contains_key(&ident) { + let span = seen_bindings.get(&ident).unwrap(); + let err = ResolutionError::NameAlreadyUsedInParameterList( + ident.name, + span, + ); + resolve_error(self, param.ident.span, err); + } + seen_bindings.entry(ident).or_insert(param.ident.span); + + let def = Def::ConstParam(self.definitions.local_def_id(param.id)); + function_value_rib.bindings.insert(ident, def); + self.record_def(param.id, PathResolution::new(def)); + } } } + self.ribs[ValueNS].push(function_value_rib); self.ribs[TypeNS].push(function_type_rib); } - NoTypeParameters => { + NoGenericParams => { // Nothing to do. } } f(self); - if let HasTypeParameters(..) = type_parameters { + if let HasGenericParams(..) = generic_params { self.ribs[TypeNS].pop(); + self.ribs[ValueNS].pop(); } } @@ -2584,6 +2626,7 @@ fn with_item_rib(&mut self, f: F) fn with_constant_rib(&mut self, f: F) where F: FnOnce(&mut Resolver<'_>) { + debug!("with_constant_rib"); self.ribs[ValueNS].push(Rib::new(ConstantItemRibKind)); self.label_ribs.push(Rib::new(ConstantItemRibKind)); f(self); @@ -2677,8 +2720,9 @@ fn resolve_implementation(&mut self, self_type: &Ty, item_id: NodeId, impl_items: &[ImplItem]) { + debug!("resolve_implementation"); // If applicable, create a rib for the type parameters. - self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| { + self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| { // Dummy self type for better errors if `Self` is used in the trait path. this.with_self_rib(Def::SelfTy(None, None), |this| { // Resolve the trait reference, if necessary. @@ -2691,30 +2735,37 @@ fn resolve_implementation(&mut self, } // Resolve the self type. this.visit_ty(self_type); - // Resolve the type parameters. + // Resolve the generic parameters. this.visit_generics(generics); // Resolve the items within the impl. this.with_current_self_type(self_type, |this| { this.with_self_struct_ctor_rib(item_def_id, |this| { + debug!("resolve_implementation with_self_struct_ctor_rib"); for impl_item in impl_items { this.resolve_visibility(&impl_item.vis); // We also need a new scope for the impl item type parameters. - let type_parameters = HasTypeParameters(&impl_item.generics, - TraitOrImplItemRibKind); - this.with_type_parameter_rib(type_parameters, |this| { + let generic_params = HasGenericParams(&impl_item.generics, + TraitOrImplItemRibKind); + this.with_generic_param_rib(generic_params, |this| { use self::ResolutionError::*; match impl_item.node { ImplItemKind::Const(..) => { + debug!( + "resolve_implementation ImplItemKind::Const", + ); // If this is a trait impl, ensure the const // exists in trait - this.check_trait_item(impl_item.ident, - ValueNS, - impl_item.span, - |n, s| ConstNotMemberOfTrait(n, s)); - this.with_constant_rib(|this| - visit::walk_impl_item(this, impl_item) + this.check_trait_item( + impl_item.ident, + ValueNS, + impl_item.span, + |n, s| ConstNotMemberOfTrait(n, s), ); + + this.with_constant_rib(|this| { + visit::walk_impl_item(this, impl_item) + }); } ImplItemKind::Method(..) => { // If this is a trait impl, ensure the method @@ -3132,383 +3183,11 @@ fn smart_resolve_path_fragment(&mut self, source: PathSource<'_>, crate_lint: CrateLint) -> PathResolution { - let ident_span = path.last().map_or(span, |ident| ident.ident.span); let ns = source.namespace(); let is_expected = &|def| source.is_expected(def); - let is_enum_variant = &|def| if let Def::Variant(..) = def { true } else { false }; - // Base error is amended with one short label and possibly some longer helps/notes. let report_errors = |this: &mut Self, def: Option| { - // Make the base error. - let expected = source.descr_expected(); - let path_str = Segment::names_to_string(path); - let item_str = path.last().unwrap().ident; - let code = source.error_code(def.is_some()); - let (base_msg, fallback_label, base_span) = if let Some(def) = def { - (format!("expected {}, found {} `{}`", expected, def.kind_name(), path_str), - format!("not a {}", expected), - span) - } else { - let item_span = path.last().unwrap().ident.span; - let (mod_prefix, mod_str) = if path.len() == 1 { - (String::new(), "this scope".to_string()) - } else if path.len() == 2 && path[0].ident.name == keywords::PathRoot.name() { - (String::new(), "the crate root".to_string()) - } else { - let mod_path = &path[..path.len() - 1]; - let mod_prefix = match this.resolve_path_without_parent_scope( - mod_path, Some(TypeNS), false, span, CrateLint::No - ) { - PathResult::Module(ModuleOrUniformRoot::Module(module)) => - module.def(), - _ => None, - }.map_or(String::new(), |def| format!("{} ", def.kind_name())); - (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path))) - }; - (format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str), - format!("not found in {}", mod_str), - item_span) - }; - - let code = DiagnosticId::Error(code.into()); - let mut err = this.session.struct_span_err_with_code(base_span, &base_msg, code); - - // Emit help message for fake-self from other languages like `this`(javascript) - if ["this", "my"].contains(&&*item_str.as_str()) - && this.self_value_is_available(path[0].ident.span, span) { - err.span_suggestion( - span, - "did you mean", - "self".to_string(), - Applicability::MaybeIncorrect, - ); - } - - // Emit special messages for unresolved `Self` and `self`. - if is_self_type(path, ns) { - __diagnostic_used!(E0411); - err.code(DiagnosticId::Error("E0411".into())); - err.span_label(span, format!("`Self` is only available in impls, traits, \ - and type definitions")); - return (err, Vec::new()); - } - if is_self_value(path, ns) { - debug!("smart_resolve_path_fragment E0424 source:{:?}", source); - - __diagnostic_used!(E0424); - err.code(DiagnosticId::Error("E0424".into())); - err.span_label(span, match source { - PathSource::Pat => { - format!("`self` value is a keyword \ - and may not be bound to \ - variables or shadowed") - } - _ => { - format!("`self` value is a keyword \ - only available in methods \ - with `self` parameter") - } - }); - return (err, Vec::new()); - } - - // Try to lookup the name in more relaxed fashion for better error reporting. - let ident = path.last().unwrap().ident; - let candidates = this.lookup_import_candidates(ident, ns, is_expected); - if candidates.is_empty() && is_expected(Def::Enum(DefId::local(CRATE_DEF_INDEX))) { - let enum_candidates = - this.lookup_import_candidates(ident, ns, is_enum_variant); - let mut enum_candidates = enum_candidates.iter() - .map(|suggestion| { - import_candidate_to_enum_paths(&suggestion) - }).collect::>(); - enum_candidates.sort(); - - if !enum_candidates.is_empty() { - // contextualize for E0412 "cannot find type", but don't belabor the point - // (that it's a variant) for E0573 "expected type, found variant" - let preamble = if def.is_none() { - let others = match enum_candidates.len() { - 1 => String::new(), - 2 => " and 1 other".to_owned(), - n => format!(" and {} others", n) - }; - format!("there is an enum variant `{}`{}; ", - enum_candidates[0].0, others) - } else { - String::new() - }; - let msg = format!("{}try using the variant's enum", preamble); - - err.span_suggestions( - span, - &msg, - enum_candidates.into_iter() - .map(|(_variant_path, enum_ty_path)| enum_ty_path) - // variants reëxported in prelude doesn't mean `prelude::v1` is the - // type name! FIXME: is there a more principled way to do this that - // would work for other reëxports? - .filter(|enum_ty_path| enum_ty_path != "std::prelude::v1") - // also say `Option` rather than `std::prelude::v1::Option` - .map(|enum_ty_path| { - // FIXME #56861: DRYer prelude filtering - enum_ty_path.trim_start_matches("std::prelude::v1::").to_owned() - }), - Applicability::MachineApplicable, - ); - } - } - if path.len() == 1 && this.self_type_is_available(span) { - if let Some(candidate) = this.lookup_assoc_candidate(ident, ns, is_expected) { - let self_is_available = this.self_value_is_available(path[0].ident.span, span); - match candidate { - AssocSuggestion::Field => { - err.span_suggestion( - span, - "try", - format!("self.{}", path_str), - Applicability::MachineApplicable, - ); - if !self_is_available { - err.span_label(span, format!("`self` value is a keyword \ - only available in \ - methods with `self` parameter")); - } - } - AssocSuggestion::MethodWithSelf if self_is_available => { - err.span_suggestion( - span, - "try", - format!("self.{}", path_str), - Applicability::MachineApplicable, - ); - } - AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => { - err.span_suggestion( - span, - "try", - format!("Self::{}", path_str), - Applicability::MachineApplicable, - ); - } - } - return (err, candidates); - } - } - - let mut levenshtein_worked = false; - - // Try Levenshtein algorithm. - let suggestion = this.lookup_typo_candidate(path, ns, is_expected, span); - if let Some(suggestion) = suggestion { - let msg = format!( - "{} {} with a similar name exists", - suggestion.article, suggestion.kind - ); - err.span_suggestion( - ident_span, - &msg, - suggestion.candidate.to_string(), - Applicability::MaybeIncorrect, - ); - - levenshtein_worked = true; - } - - // Try context dependent help if relaxed lookup didn't work. - if let Some(def) = def { - match (def, source) { - (Def::Macro(..), _) => { - err.span_suggestion( - span, - "use `!` to invoke the macro", - format!("{}!", path_str), - Applicability::MaybeIncorrect, - ); - return (err, candidates); - } - (Def::TyAlias(..), PathSource::Trait(_)) => { - err.span_label(span, "type aliases cannot be used as traits"); - if nightly_options::is_nightly_build() { - err.note("did you mean to use a trait alias?"); - } - return (err, candidates); - } - (Def::Mod(..), PathSource::Expr(Some(parent))) => match parent.node { - ExprKind::Field(_, ident) => { - err.span_suggestion( - parent.span, - "use the path separator to refer to an item", - format!("{}::{}", path_str, ident), - Applicability::MaybeIncorrect, - ); - return (err, candidates); - } - ExprKind::MethodCall(ref segment, ..) => { - let span = parent.span.with_hi(segment.ident.span.hi()); - err.span_suggestion( - span, - "use the path separator to refer to an item", - format!("{}::{}", path_str, segment.ident), - Applicability::MaybeIncorrect, - ); - return (err, candidates); - } - _ => {} - }, - (Def::Enum(..), PathSource::TupleStruct) - | (Def::Enum(..), PathSource::Expr(..)) => { - if let Some(variants) = this.collect_enum_variants(def) { - err.note(&format!("did you mean to use one \ - of the following variants?\n{}", - variants.iter() - .map(|suggestion| path_names_to_string(suggestion)) - .map(|suggestion| format!("- `{}`", suggestion)) - .collect::>() - .join("\n"))); - - } else { - err.note("did you mean to use one of the enum's variants?"); - } - return (err, candidates); - }, - (Def::Struct(def_id), _) if ns == ValueNS => { - if let Some((ctor_def, ctor_vis)) - = this.struct_constructors.get(&def_id).cloned() { - let accessible_ctor = this.is_accessible(ctor_vis); - if is_expected(ctor_def) && !accessible_ctor { - err.span_label(span, format!("constructor is not visible \ - here due to private fields")); - } - } else { - // HACK(estebank): find a better way to figure out that this was a - // parser issue where a struct literal is being used on an expression - // where a brace being opened means a block is being started. Look - // ahead for the next text to see if `span` is followed by a `{`. - let sm = this.session.source_map(); - let mut sp = span; - loop { - sp = sm.next_point(sp); - match sm.span_to_snippet(sp) { - Ok(ref snippet) => { - if snippet.chars().any(|c| { !c.is_whitespace() }) { - break; - } - } - _ => break, - } - } - let followed_by_brace = match sm.span_to_snippet(sp) { - Ok(ref snippet) if snippet == "{" => true, - _ => false, - }; - // In case this could be a struct literal that needs to be surrounded - // by parenthesis, find the appropriate span. - let mut i = 0; - let mut closing_brace = None; - loop { - sp = sm.next_point(sp); - match sm.span_to_snippet(sp) { - Ok(ref snippet) => { - if snippet == "}" { - let sp = span.to(sp); - if let Ok(snippet) = sm.span_to_snippet(sp) { - closing_brace = Some((sp, snippet)); - } - break; - } - } - _ => break, - } - i += 1; - if i > 100 { // The bigger the span the more likely we're - break; // incorrect. Bound it to 100 chars long. - } - } - match source { - PathSource::Expr(Some(parent)) => { - match parent.node { - ExprKind::MethodCall(ref path_assignment, _) => { - err.span_suggestion( - sm.start_point(parent.span) - .to(path_assignment.ident.span), - "use `::` to access an associated function", - format!("{}::{}", - path_str, - path_assignment.ident), - Applicability::MaybeIncorrect - ); - return (err, candidates); - }, - _ => { - err.span_label( - span, - format!("did you mean `{} {{ /* fields */ }}`?", - path_str), - ); - return (err, candidates); - }, - } - }, - PathSource::Expr(None) if followed_by_brace == true => { - if let Some((sp, snippet)) = closing_brace { - err.span_suggestion( - sp, - "surround the struct literal with parenthesis", - format!("({})", snippet), - Applicability::MaybeIncorrect, - ); - } else { - err.span_label( - span, - format!("did you mean `({} {{ /* fields */ }})`?", - path_str), - ); - } - return (err, candidates); - }, - _ => { - err.span_label( - span, - format!("did you mean `{} {{ /* fields */ }}`?", - path_str), - ); - return (err, candidates); - }, - } - } - return (err, candidates); - } - (Def::Union(..), _) | - (Def::Variant(..), _) | - (Def::VariantCtor(_, CtorKind::Fictive), _) if ns == ValueNS => { - err.span_label(span, format!("did you mean `{} {{ /* fields */ }}`?", - path_str)); - return (err, candidates); - } - (Def::SelfTy(..), _) if ns == ValueNS => { - err.span_label(span, fallback_label); - err.note("can't use `Self` as a constructor, you must use the \ - implemented struct"); - return (err, candidates); - } - (Def::TyAlias(_), _) | (Def::AssociatedTy(..), _) if ns == ValueNS => { - err.note("can't use a type alias as a constructor"); - return (err, candidates); - } - _ => {} - } - } - - // Fallback label. - if !levenshtein_worked { - err.span_label(base_span, fallback_label); - this.type_ascription_suggestion(&mut err, base_span); - } - (err, candidates) - }; - let report_errors = |this: &mut Self, def: Option| { - let (err, candidates) = report_errors(this, def); + let (err, candidates) = this.smart_resolve_report_errors(path, span, source, def); let def_id = this.current_module.normal_ancestor_id; let node_id = this.definitions.as_local_node_id(def_id).unwrap(); let better = def.is_some(); @@ -3579,7 +3258,8 @@ fn type_ascription_suggestion(&self, debug!("self.current_type_ascription {:?}", self.current_type_ascription); if let Some(sp) = self.current_type_ascription.last() { let mut sp = *sp; - loop { // try to find the `:`, bail on first non-':'/non-whitespace + loop { + // Try to find the `:`; bail on first non-':' / non-whitespace. sp = cm.next_point(sp); if let Ok(snippet) = cm.span_to_snippet(sp.to(cm.next_point(sp))) { debug!("snippet {:?}", snippet); @@ -4093,6 +3773,7 @@ fn adjust_local_def(&mut self, mut def: Def, record_used: bool, span: Span) -> Def { + debug!("adjust_local_def"); let ribs = &self.ribs[ns][rib_index + 1..]; // An invalid forward use of a type parameter from a previous default. @@ -4109,6 +3790,9 @@ fn adjust_local_def(&mut self, span_bug!(span, "unexpected {:?} in bindings", def) } Def::Local(node_id) => { + use ResolutionError::*; + let mut res_err = None; + for rib in ribs { match rib.kind { NormalRibKind | ModuleRibKind(..) | MacroDefinition(..) | @@ -4144,21 +3828,26 @@ fn adjust_local_def(&mut self, // named function item. This is not allowed, so we // report an error. if record_used { - resolve_error(self, span, - ResolutionError::CannotCaptureDynamicEnvironmentInFnItem); + // We don't immediately trigger a resolve error, because + // we want certain other resolution errors (namely those + // emitted for `ConstantItemRibKind` below) to take + // precedence. + res_err = Some(CannotCaptureDynamicEnvironmentInFnItem); } - return Def::Err; } ConstantItemRibKind => { // Still doesn't deal with upvars if record_used { - resolve_error(self, span, - ResolutionError::AttemptToUseNonConstantValueInConstant); + resolve_error(self, span, AttemptToUseNonConstantValueInConstant); } return Def::Err; } } } + if let Some(res_err) = res_err { + resolve_error(self, span, res_err); + return Def::Err; + } } Def::TyParam(..) | Def::SelfTy(..) => { for rib in ribs { @@ -4169,17 +3858,38 @@ fn adjust_local_def(&mut self, // Nothing to do. Continue. } ItemRibKind => { - // This was an attempt to use a type parameter outside - // its scope. + // This was an attempt to use a type parameter outside its scope. if record_used { - resolve_error(self, span, - ResolutionError::TypeParametersFromOuterFunction(def)); + resolve_error( + self, + span, + ResolutionError::GenericParamsFromOuterFunction(def), + ); } return Def::Err; } } } } + Def::ConstParam(..) => { + // A const param is always declared in a signature, which is always followed by + // some kind of function rib kind (specifically, ItemRibKind in the case of a + // normal function), so we can skip the first rib as it will be guaranteed to + // (spuriously) conflict with the const param. + for rib in &ribs[1..] { + if let ItemRibKind = rib.kind { + // This was an attempt to use a const parameter outside its scope. + if record_used { + resolve_error( + self, + span, + ResolutionError::GenericParamsFromOuterFunction(def), + ); + } + return Def::Err; + } + } + } _ => {} } def @@ -5438,7 +5148,6 @@ fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, Str (variant_path_string, enum_path_string) } - /// When an entity with a given name is not available in scope, we search for /// entities with that name in all crates. This method allows outputting the /// results of this search in a programmer-friendly way diff --git a/src/librustc_save_analysis/Cargo.toml b/src/librustc_save_analysis/Cargo.toml index e47f89c64ff..8bb2e722b57 100644 --- a/src/librustc_save_analysis/Cargo.toml +++ b/src/librustc_save_analysis/Cargo.toml @@ -2,6 +2,7 @@ authors = ["The Rust Project Developers"] name = "rustc_save_analysis" version = "0.0.0" +edition = "2018" [lib] name = "rustc_save_analysis" diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index 995df3802aa..1a49056bc7f 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -16,6 +16,7 @@ use rustc::hir::def::Def as HirDef; use rustc::hir::def_id::DefId; use rustc::session::config::Input; +use rustc::span_bug; use rustc::ty::{self, TyCtxt}; use rustc_data_structures::fx::FxHashSet; @@ -32,16 +33,20 @@ }; use syntax::ptr::P; use syntax::source_map::{Spanned, DUMMY_SP, respan}; +use syntax::walk_list; use syntax_pos::*; -use {escape, generated_code, lower_attributes, PathCollector, SaveContext}; -use json_dumper::{Access, DumpOutput, JsonDumper}; -use span_utils::SpanUtils; -use sig; +use crate::{escape, generated_code, id_from_def_id, id_from_node_id, lower_attributes, + PathCollector, SaveContext}; +use crate::json_dumper::{Access, DumpOutput, JsonDumper}; +use crate::span_utils::SpanUtils; +use crate::sig; use rls_data::{CompilationOptions, CratePreludeData, Def, DefKind, GlobalCrateId, Import, ImportKind, Ref, RefKind, Relation, RelationKind, SpanData}; +use log::{debug, error}; + macro_rules! down_cast_data { ($id:ident, $kind:ident, $sp:expr) => { let $id = if let super::Data::$kind(data) = $id { @@ -68,7 +73,7 @@ macro_rules! access_from { }; } -pub struct DumpVisitor<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> { +pub struct DumpVisitor<'l, 'tcx: 'l, 'll, O: DumpOutput> { save_ctxt: SaveContext<'l, 'tcx>, tcx: TyCtxt<'l, 'tcx, 'tcx>, dumper: &'ll mut JsonDumper, @@ -245,7 +250,7 @@ fn process_formals(&mut self, formals: &'l [ast::Arg], qualname: &str) { None => continue, }; if !self.span.filter_generated(ident.span) { - let id = ::id_from_node_id(id, &self.save_ctxt); + let id = id_from_node_id(id, &self.save_ctxt); let span = self.span_from_span(ident.span); self.dumper.dump_def( @@ -286,7 +291,7 @@ fn process_method( debug!("process_method: {}:{}", id, ident); if let Some(mut method_data) = self.save_ctxt.get_method_data(id, ident, span) { - let sig_str = ::make_signature(&sig.decl, &generics); + let sig_str = crate::make_signature(&sig.decl, &generics); if body.is_some() { self.nest_tables( id, @@ -339,7 +344,7 @@ fn process_generic_params( // Append $id to name to make sure each one is unique. let qualname = format!("{}::{}${}", prefix, name, id); if !self.span.filter_generated(param_ss) { - let id = ::id_from_node_id(param.id, &self.save_ctxt); + let id = id_from_node_id(param.id, &self.save_ctxt); let span = self.span_from_span(param_ss); self.dumper.dump_def( @@ -364,6 +369,7 @@ fn process_generic_params( ); } } + ast::GenericParamKind::Const { .. } => {} } } self.visit_generics(generics); @@ -433,12 +439,12 @@ fn process_assoc_const( &access_from!(self.save_ctxt, vis, id), Def { kind: DefKind::Const, - id: ::id_from_node_id(id, &self.save_ctxt), + id: id_from_node_id(id, &self.save_ctxt), span, name: ident.name.to_string(), qualname, value: ty_to_string(&typ), - parent: Some(::id_from_def_id(parent_id)), + parent: Some(id_from_def_id(parent_id)), children: vec![], decl_id: None, docs: self.save_ctxt.docs_for_attrs(attrs), @@ -495,7 +501,7 @@ fn process_struct( value, fields .iter() - .map(|f| ::id_from_node_id(f.id, &self.save_ctxt)) + .map(|f| id_from_node_id(f.id, &self.save_ctxt)) .collect(), ) } @@ -508,7 +514,7 @@ fn process_struct( &access_from!(self.save_ctxt, item), Def { kind, - id: ::id_from_node_id(item.id, &self.save_ctxt), + id: id_from_node_id(item.id, &self.save_ctxt), span, name, qualname: qualname.clone(), @@ -564,8 +570,8 @@ fn process_enum( let value = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str); if !self.span.filter_generated(name_span) { let span = self.span_from_span(name_span); - let id = ::id_from_node_id(variant.node.data.id(), &self.save_ctxt); - let parent = Some(::id_from_node_id(item.id, &self.save_ctxt)); + let id = id_from_node_id(variant.node.data.id(), &self.save_ctxt); + let parent = Some(id_from_node_id(item.id, &self.save_ctxt)); self.dumper.dump_def( &access, @@ -602,8 +608,8 @@ fn process_enum( } if !self.span.filter_generated(name_span) { let span = self.span_from_span(name_span); - let id = ::id_from_node_id(variant.node.data.id(), &self.save_ctxt); - let parent = Some(::id_from_node_id(item.id, &self.save_ctxt)); + let id = id_from_node_id(variant.node.data.id(), &self.save_ctxt); + let parent = Some(id_from_node_id(item.id, &self.save_ctxt)); self.dumper.dump_def( &access, @@ -686,11 +692,11 @@ fn process_trait( val.push_str(&bounds_to_string(trait_refs)); } if !self.span.filter_generated(item.ident.span) { - let id = ::id_from_node_id(item.id, &self.save_ctxt); + let id = id_from_node_id(item.id, &self.save_ctxt); let span = self.span_from_span(item.ident.span); let children = methods .iter() - .map(|i| ::id_from_node_id(i.id, &self.save_ctxt)) + .map(|i| id_from_node_id(i.id, &self.save_ctxt)) .collect(); self.dumper.dump_def( &access_from!(self.save_ctxt, item), @@ -726,14 +732,14 @@ fn process_trait( self.dumper.dump_ref(Ref { kind: RefKind::Type, span: span.clone(), - ref_id: ::id_from_def_id(id), + ref_id: id_from_def_id(id), }); self.dumper.dump_relation(Relation { kind: RelationKind::SuperTrait, span, - from: ::id_from_def_id(id), - to: ::id_from_node_id(item.id, &self.save_ctxt), + from: id_from_def_id(id), + to: id_from_node_id(item.id, &self.save_ctxt), }); } } @@ -873,7 +879,7 @@ fn process_pat(&mut self, p: &'l ast::Pat) { self.dumper.dump_ref(Ref { kind: RefKind::Variable, span, - ref_id: ::id_from_def_id(variant.fields[index].did), + ref_id: id_from_def_id(variant.fields[index].did), }); } } @@ -912,7 +918,7 @@ fn process_var_decl_multi(&mut self, pats: &'l [P]) { if !self.span.filter_generated(ident.span) { let qualname = format!("{}${}", ident.to_string(), id); - let id = ::id_from_node_id(id, &self.save_ctxt); + let id = id_from_node_id(id, &self.save_ctxt); let span = self.span_from_span(ident.span); self.dumper.dump_def( @@ -988,7 +994,7 @@ fn process_var_decl(&mut self, p: &'l ast::Pat, value: String) { // Rust uses the id of the pattern for var lookups, so we'll use it too. if !self.span.filter_generated(ident.span) { let qualname = format!("{}${}", ident.to_string(), id); - let id = ::id_from_node_id(id, &self.save_ctxt); + let id = id_from_node_id(id, &self.save_ctxt); let span = self.span_from_span(ident.span); self.dumper.dump_def( @@ -1091,7 +1097,7 @@ fn process_trait_item(&mut self, trait_item: &'l ast::TraitItem, trait_id: DefId if !self.span.filter_generated(trait_item.ident.span) { let span = self.span_from_span(trait_item.ident.span); - let id = ::id_from_node_id(trait_item.id, &self.save_ctxt); + let id = id_from_node_id(trait_item.id, &self.save_ctxt); self.dumper.dump_def( &Access { @@ -1105,7 +1111,7 @@ fn process_trait_item(&mut self, trait_item: &'l ast::TraitItem, trait_id: DefId name, qualname, value: self.span.snippet(trait_item.span), - parent: Some(::id_from_def_id(trait_id)), + parent: Some(id_from_def_id(trait_id)), children: vec![], decl_id: None, docs: self.save_ctxt.docs_for_attrs(&trait_item.attrs), @@ -1196,7 +1202,7 @@ fn process_use_tree(&mut self, // The parent def id of a given use tree is always the enclosing item. let parent = self.save_ctxt.tcx.hir().opt_local_def_id(id) .and_then(|id| self.save_ctxt.tcx.parent_def_id(id)) - .map(::id_from_def_id); + .map(id_from_def_id); match use_tree.kind { ast::UseTreeKind::Simple(alias, ..) => { @@ -1212,7 +1218,7 @@ fn process_use_tree(&mut self, let sub_span = path.segments.last().unwrap().ident.span; if !self.span.filter_generated(sub_span) { - let ref_id = self.lookup_def_id(id).map(|id| ::id_from_def_id(id)); + let ref_id = self.lookup_def_id(id).map(|id| id_from_def_id(id)); let alias_span = alias.map(|i| self.span_from_span(i.span)); let span = self.span_from_span(sub_span); self.dumper.import(&access, Import { @@ -1298,10 +1304,10 @@ fn visit_mod(&mut self, m: &'l ast::Mod, span: Span, attrs: &[ast::Attribute], i let cm = self.tcx.sess.source_map(); let filename = cm.span_to_filename(span); - let data_id = ::id_from_node_id(id, &self.save_ctxt); + let data_id = id_from_node_id(id, &self.save_ctxt); let children = m.items .iter() - .map(|i| ::id_from_node_id(i.id, &self.save_ctxt)) + .map(|i| id_from_node_id(i.id, &self.save_ctxt)) .collect(); let span = self.span_from_span(span); @@ -1345,7 +1351,7 @@ fn visit_item(&mut self, item: &'l ast::Item) { let span = self.span_from_span(name_span); let parent = self.save_ctxt.tcx.hir().opt_local_def_id(item.id) .and_then(|id| self.save_ctxt.tcx.parent_def_id(id)) - .map(::id_from_def_id); + .map(id_from_def_id); self.dumper.import( &Access { public: false, @@ -1387,7 +1393,7 @@ fn visit_item(&mut self, item: &'l ast::Item) { let value = ty_to_string(&ty); if !self.span.filter_generated(item.ident.span) { let span = self.span_from_span(item.ident.span); - let id = ::id_from_node_id(item.id, &self.save_ctxt); + let id = id_from_node_id(item.id, &self.save_ctxt); self.dumper.dump_def( &access_from!(self.save_ctxt, item), @@ -1417,7 +1423,7 @@ fn visit_item(&mut self, item: &'l ast::Item) { let value = String::new(); if !self.span.filter_generated(item.ident.span) { let span = self.span_from_span(item.ident.span); - let id = ::id_from_node_id(item.id, &self.save_ctxt); + let id = id_from_node_id(item.id, &self.save_ctxt); self.dumper.dump_def( &access_from!(self.save_ctxt, item), @@ -1447,9 +1453,16 @@ fn visit_item(&mut self, item: &'l ast::Item) { fn visit_generics(&mut self, generics: &'l ast::Generics) { for param in &generics.params { - if let ast::GenericParamKind::Type { ref default, .. } = param.kind { - self.process_bounds(¶m.bounds); - if let Some(ref ty) = default { + match param.kind { + ast::GenericParamKind::Lifetime { .. } => {} + ast::GenericParamKind::Type { ref default, .. } => { + self.process_bounds(¶m.bounds); + if let Some(ref ty) = default { + self.visit_ty(&ty); + } + } + ast::GenericParamKind::Const { ref ty } => { + self.process_bounds(¶m.bounds); self.visit_ty(&ty); } } @@ -1476,7 +1489,7 @@ fn visit_ty(&mut self, t: &'l ast::Ty) { self.dumper.dump_ref(Ref { kind: RefKind::Type, span, - ref_id: ::id_from_def_id(id), + ref_id: id_from_def_id(id), }); } diff --git a/src/librustc_save_analysis/json_dumper.rs b/src/librustc_save_analysis/json_dumper.rs index 3627c5577a6..1840cf652e1 100644 --- a/src/librustc_save_analysis/json_dumper.rs +++ b/src/librustc_save_analysis/json_dumper.rs @@ -7,6 +7,8 @@ MacroRef, Ref, RefKind, Relation}; use rls_span::{Column, Row}; +use log::error; + #[derive(Debug)] pub struct Access { pub reachable: bool, @@ -23,7 +25,7 @@ pub trait DumpOutput { fn dump(&mut self, result: &Analysis); } -pub struct WriteOutput<'b, W: Write + 'b> { +pub struct WriteOutput<'b, W: Write> { output: &'b mut W, } diff --git a/src/librustc_save_analysis/lib.rs b/src/librustc_save_analysis/lib.rs index b9d195d5715..c4a2ebeba65 100644 --- a/src/librustc_save_analysis/lib.rs +++ b/src/librustc_save_analysis/lib.rs @@ -1,27 +1,10 @@ #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")] #![feature(custom_attribute)] -#![feature(nll)] +#![deny(rust_2018_idioms)] #![allow(unused_attributes)] #![recursion_limit="256"] -#[macro_use] -extern crate rustc; - -#[macro_use] -extern crate log; -extern crate rustc_data_structures; -extern crate rustc_codegen_utils; -extern crate rustc_serialize; -extern crate rustc_target; -extern crate rustc_typeck; -#[macro_use] -extern crate syntax; -extern crate syntax_pos; - -extern crate rls_data; -extern crate rls_span; - mod json_dumper; mod dump_visitor; @@ -37,6 +20,7 @@ use rustc::middle::cstore::ExternCrate; use rustc::session::config::{CrateType, Input, OutputType}; use rustc::ty::{self, TyCtxt}; +use rustc::{bug, span_bug}; use rustc_typeck::hir_ty_to_ty; use rustc_codegen_utils::link::{filename_for_metadata, out_filename}; use rustc_data_structures::sync::Lrc; @@ -64,6 +48,8 @@ RelationKind, SpanData, Impl, ImplKind}; use rls_data::config::Config; +use log::{debug, error, info}; + pub struct SaveContext<'l, 'tcx: 'l> { tcx: TyCtxt<'l, 'tcx, 'tcx>, @@ -170,7 +156,7 @@ pub fn get_extern_item_data(&self, item: &ast::ForeignItem) -> Option { ast::ForeignItemKind::Static(ref ty, _) => { filter!(self.span_utils, item.ident.span); - let id = ::id_from_node_id(item.id, self); + let id = id_from_node_id(item.id, self); let span = self.span_from_span(item.ident.span); Some(Data::DefData(Def { @@ -760,6 +746,13 @@ fn fn_type(seg: &ast::PathSegment) -> bool { ref_id: id_from_def_id(def_id), }) } + HirDef::ConstParam(def_id) => { + Some(Ref { + kind: RefKind::Variable, + span, + ref_id: id_from_def_id(def_id), + }) + } HirDef::StructCtor(def_id, _) => { // This is a reference to a tuple struct where the def_id points // to an invisible constructor function. That is not a very useful @@ -1027,7 +1020,7 @@ pub fn new(odir: Option<&'a Path>, cratename: &str) -> DumpHandler<'a> { } } - fn output_file(&self, ctx: &SaveContext) -> File { + fn output_file(&self, ctx: &SaveContext<'_, '_>) -> File { let sess = &ctx.tcx.sess; let file_name = match ctx.config.output_file { Some(ref s) => PathBuf::from(s), @@ -1178,7 +1171,7 @@ fn id_from_def_id(id: DefId) -> rls_data::Id { } } -fn id_from_node_id(id: NodeId, scx: &SaveContext) -> rls_data::Id { +fn id_from_node_id(id: NodeId, scx: &SaveContext<'_, '_>) -> rls_data::Id { let def_id = scx.tcx.hir().opt_local_def_id(id); def_id.map(|id| id_from_def_id(id)).unwrap_or_else(|| { // Create a *fake* `DefId` out of a `NodeId` by subtracting the `NodeId` @@ -1198,7 +1191,7 @@ fn null_id() -> rls_data::Id { } } -fn lower_attributes(attrs: Vec, scx: &SaveContext) -> Vec { +fn lower_attributes(attrs: Vec, scx: &SaveContext<'_, '_>) -> Vec { attrs.into_iter() // Only retain real attributes. Doc comments are lowered separately. .filter(|attr| attr.path != "doc") diff --git a/src/librustc_save_analysis/sig.rs b/src/librustc_save_analysis/sig.rs index 7d4c0d0f9f5..50a335bf908 100644 --- a/src/librustc_save_analysis/sig.rs +++ b/src/librustc_save_analysis/sig.rs @@ -25,7 +25,7 @@ // // FIXME where clauses need implementing, defs/refs in generics are mostly missing. -use {id_from_def_id, id_from_node_id, SaveContext}; +use crate::{id_from_def_id, id_from_node_id, SaveContext}; use rls_data::{SigElement, Signature}; @@ -34,14 +34,17 @@ use syntax::print::pprust; -pub fn item_signature(item: &ast::Item, scx: &SaveContext) -> Option { +pub fn item_signature(item: &ast::Item, scx: &SaveContext<'_, '_>) -> Option { if !scx.config.signatures { return None; } item.make(0, None, scx).ok() } -pub fn foreign_item_signature(item: &ast::ForeignItem, scx: &SaveContext) -> Option { +pub fn foreign_item_signature( + item: &ast::ForeignItem, + scx: &SaveContext<'_, '_> +) -> Option { if !scx.config.signatures { return None; } @@ -50,7 +53,7 @@ pub fn foreign_item_signature(item: &ast::ForeignItem, scx: &SaveContext) -> Opt /// Signature for a struct or tuple field declaration. /// Does not include a trailing comma. -pub fn field_signature(field: &ast::StructField, scx: &SaveContext) -> Option { +pub fn field_signature(field: &ast::StructField, scx: &SaveContext<'_, '_>) -> Option { if !scx.config.signatures { return None; } @@ -58,7 +61,7 @@ pub fn field_signature(field: &ast::StructField, scx: &SaveContext) -> Option Option { +pub fn variant_signature(variant: &ast::Variant, scx: &SaveContext<'_, '_>) -> Option { if !scx.config.signatures { return None; } @@ -70,7 +73,7 @@ pub fn method_signature( ident: ast::Ident, generics: &ast::Generics, m: &ast::MethodSig, - scx: &SaveContext, + scx: &SaveContext<'_, '_>, ) -> Option { if !scx.config.signatures { return None; @@ -83,7 +86,7 @@ pub fn assoc_const_signature( ident: ast::Name, ty: &ast::Ty, default: Option<&ast::Expr>, - scx: &SaveContext, + scx: &SaveContext<'_, '_>, ) -> Option { if !scx.config.signatures { return None; @@ -96,7 +99,7 @@ pub fn assoc_type_signature( ident: ast::Ident, bounds: Option<&ast::GenericBounds>, default: Option<&ast::Ty>, - scx: &SaveContext, + scx: &SaveContext<'_, '_>, ) -> Option { if !scx.config.signatures { return None; @@ -104,10 +107,10 @@ pub fn assoc_type_signature( make_assoc_type_signature(id, ident, bounds, default, scx).ok() } -type Result = ::std::result::Result; +type Result = std::result::Result; trait Sig { - fn make(&self, offset: usize, id: Option, scx: &SaveContext) -> Result; + fn make(&self, offset: usize, id: Option, scx: &SaveContext<'_, '_>) -> Result; } fn extend_sig( @@ -155,7 +158,7 @@ fn text_sig(text: String) -> Signature { } impl Sig for ast::Ty { - fn make(&self, offset: usize, _parent_id: Option, scx: &SaveContext) -> Result { + fn make(&self, offset: usize, _parent_id: Option, scx: &SaveContext<'_, '_>) -> Result { let id = Some(self.id); match self.node { ast::TyKind::Slice(ref ty) => { @@ -227,7 +230,7 @@ fn make(&self, offset: usize, _parent_id: Option, scx: &SaveContext) -> if f.unsafety == ast::Unsafety::Unsafe { text.push_str("unsafe "); } - if f.abi != ::rustc_target::spec::abi::Abi::Rust { + if f.abi != rustc_target::spec::abi::Abi::Rust { text.push_str("extern"); text.push_str(&f.abi.to_string()); text.push(' '); @@ -317,7 +320,7 @@ fn make(&self, offset: usize, _parent_id: Option, scx: &SaveContext) -> } impl Sig for ast::Item { - fn make(&self, offset: usize, _parent_id: Option, scx: &SaveContext) -> Result { + fn make(&self, offset: usize, _parent_id: Option, scx: &SaveContext<'_, '_>) -> Result { let id = Some(self.id); match self.node { @@ -381,7 +384,7 @@ fn make(&self, offset: usize, _parent_id: Option, scx: &SaveContext) -> if header.unsafety == ast::Unsafety::Unsafe { text.push_str("unsafe "); } - if header.abi != ::rustc_target::spec::abi::Abi::Rust { + if header.abi != rustc_target::spec::abi::Abi::Rust { text.push_str("extern"); text.push_str(&header.abi.to_string()); text.push(' '); @@ -571,7 +574,7 @@ fn make(&self, offset: usize, _parent_id: Option, scx: &SaveContext) -> } impl Sig for ast::Path { - fn make(&self, offset: usize, id: Option, scx: &SaveContext) -> Result { + fn make(&self, offset: usize, id: Option, scx: &SaveContext<'_, '_>) -> Result { let def = scx.get_path_def(id.ok_or("Missing id for Path")?); let (name, start, end) = match def { @@ -613,7 +616,7 @@ fn make(&self, offset: usize, id: Option, scx: &SaveContext) -> Result { // This does not cover the where clause, which must be processed separately. impl Sig for ast::Generics { - fn make(&self, offset: usize, _parent_id: Option, scx: &SaveContext) -> Result { + fn make(&self, offset: usize, _parent_id: Option, scx: &SaveContext<'_, '_>) -> Result { if self.params.is_empty() { return Ok(text_sig(String::new())); } @@ -622,12 +625,20 @@ fn make(&self, offset: usize, _parent_id: Option, scx: &SaveContext) -> let mut defs = Vec::with_capacity(self.params.len()); for param in &self.params { - let mut param_text = param.ident.to_string(); + let mut param_text = String::new(); + if let ast::GenericParamKind::Const { .. } = param.kind { + param_text.push_str("const "); + } + param_text.push_str(¶m.ident.as_str()); defs.push(SigElement { id: id_from_node_id(param.id, scx), start: offset + text.len(), - end: offset + text.len() + param_text.len(), + end: offset + text.len() + param_text.as_str().len(), }); + if let ast::GenericParamKind::Const { ref ty } = param.kind { + param_text.push_str(": "); + param_text.push_str(&pprust::ty_to_string(&ty)); + } if !param.bounds.is_empty() { param_text.push_str(": "); match param.kind { @@ -646,6 +657,9 @@ fn make(&self, offset: usize, _parent_id: Option, scx: &SaveContext) -> param_text.push_str(&pprust::bounds_to_string(¶m.bounds)); // FIXME descend properly into bounds. } + ast::GenericParamKind::Const { .. } => { + // Const generics cannot contain bounds. + } } } text.push_str(¶m_text); @@ -662,7 +676,7 @@ fn make(&self, offset: usize, _parent_id: Option, scx: &SaveContext) -> } impl Sig for ast::StructField { - fn make(&self, offset: usize, _parent_id: Option, scx: &SaveContext) -> Result { + fn make(&self, offset: usize, _parent_id: Option, scx: &SaveContext<'_, '_>) -> Result { let mut text = String::new(); let mut defs = None; if let Some(ident) = self.ident { @@ -685,7 +699,7 @@ fn make(&self, offset: usize, _parent_id: Option, scx: &SaveContext) -> impl Sig for ast::Variant_ { - fn make(&self, offset: usize, _parent_id: Option, scx: &SaveContext) -> Result { + fn make(&self, offset: usize, _parent_id: Option, scx: &SaveContext<'_, '_>) -> Result { let mut text = self.ident.to_string(); match self.data { ast::VariantData::Struct(ref fields, id) => { @@ -743,7 +757,7 @@ fn make(&self, offset: usize, _parent_id: Option, scx: &SaveContext) -> } impl Sig for ast::ForeignItem { - fn make(&self, offset: usize, _parent_id: Option, scx: &SaveContext) -> Result { + fn make(&self, offset: usize, _parent_id: Option, scx: &SaveContext<'_, '_>) -> Result { let id = Some(self.id); match self.node { ast::ForeignItemKind::Fn(ref decl, ref generics) => { @@ -827,7 +841,7 @@ fn name_and_generics( generics: &ast::Generics, id: NodeId, name: ast::Ident, - scx: &SaveContext, + scx: &SaveContext<'_, '_>, ) -> Result { let name = name.to_string(); let def = SigElement { @@ -848,7 +862,7 @@ fn make_assoc_type_signature( ident: ast::Ident, bounds: Option<&ast::GenericBounds>, default: Option<&ast::Ty>, - scx: &SaveContext, + scx: &SaveContext<'_, '_>, ) -> Result { let mut text = "type ".to_owned(); let name = ident.to_string(); @@ -882,7 +896,7 @@ fn make_assoc_const_signature( ident: ast::Name, ty: &ast::Ty, default: Option<&ast::Expr>, - scx: &SaveContext, + scx: &SaveContext<'_, '_>, ) -> Result { let mut text = "const ".to_owned(); let name = ident.to_string(); @@ -915,7 +929,7 @@ fn make_method_signature( ident: ast::Ident, generics: &ast::Generics, m: &ast::MethodSig, - scx: &SaveContext, + scx: &SaveContext<'_, '_>, ) -> Result { // FIXME code dup with function signature let mut text = String::new(); @@ -928,7 +942,7 @@ fn make_method_signature( if m.header.unsafety == ast::Unsafety::Unsafe { text.push_str("unsafe "); } - if m.header.abi != ::rustc_target::spec::abi::Abi::Rust { + if m.header.abi != rustc_target::spec::abi::Abi::Rust { text.push_str("extern"); text.push_str(&m.header.abi.to_string()); text.push(' '); diff --git a/src/librustc_save_analysis/span_utils.rs b/src/librustc_save_analysis/span_utils.rs index 88c6012f71f..e2c93b6d331 100644 --- a/src/librustc_save_analysis/span_utils.rs +++ b/src/librustc_save_analysis/span_utils.rs @@ -1,6 +1,6 @@ use rustc::session::Session; -use generated_code; +use crate::generated_code; use std::cell::Cell; diff --git a/src/librustc_target/Cargo.toml b/src/librustc_target/Cargo.toml index dfdd7f0ae58..ecea15a9922 100644 --- a/src/librustc_target/Cargo.toml +++ b/src/librustc_target/Cargo.toml @@ -2,6 +2,7 @@ authors = ["The Rust Project Developers"] name = "rustc_target" version = "0.0.0" +edition = "2018" [lib] name = "rustc_target" diff --git a/src/librustc_target/abi/call/aarch64.rs b/src/librustc_target/abi/call/aarch64.rs index 9f9bba14b96..f50ec6c2e7e 100644 --- a/src/librustc_target/abi/call/aarch64.rs +++ b/src/librustc_target/abi/call/aarch64.rs @@ -1,5 +1,5 @@ -use abi::call::{FnType, ArgType, Reg, RegKind, Uniform}; -use abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods}; +use crate::abi::call::{FnType, ArgType, Reg, RegKind, Uniform}; +use crate::abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods}; fn is_homogeneous_aggregate<'a, Ty, C>(cx: &C, arg: &mut ArgType<'a, Ty>) -> Option diff --git a/src/librustc_target/abi/call/amdgpu.rs b/src/librustc_target/abi/call/amdgpu.rs index ea9d4172cbc..6bfd1f43873 100644 --- a/src/librustc_target/abi/call/amdgpu.rs +++ b/src/librustc_target/abi/call/amdgpu.rs @@ -1,5 +1,5 @@ -use abi::call::{ArgType, FnType, }; -use abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods}; +use crate::abi::call::{ArgType, FnType, }; +use crate::abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods}; fn classify_ret_ty<'a, Ty, C>(_cx: &C, ret: &mut ArgType<'a, Ty>) where Ty: TyLayoutMethods<'a, C> + Copy, diff --git a/src/librustc_target/abi/call/arm.rs b/src/librustc_target/abi/call/arm.rs index 228dd362161..52d7f3ac3dc 100644 --- a/src/librustc_target/abi/call/arm.rs +++ b/src/librustc_target/abi/call/arm.rs @@ -1,6 +1,6 @@ -use abi::call::{Conv, FnType, ArgType, Reg, RegKind, Uniform}; -use abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods}; -use spec::HasTargetSpec; +use crate::abi::call::{Conv, FnType, ArgType, Reg, RegKind, Uniform}; +use crate::abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods}; +use crate::spec::HasTargetSpec; fn is_homogeneous_aggregate<'a, Ty, C>(cx: &C, arg: &mut ArgType<'a, Ty>) -> Option diff --git a/src/librustc_target/abi/call/asmjs.rs b/src/librustc_target/abi/call/asmjs.rs index 85444500c5e..92c86372a86 100644 --- a/src/librustc_target/abi/call/asmjs.rs +++ b/src/librustc_target/abi/call/asmjs.rs @@ -1,5 +1,5 @@ -use abi::call::{FnType, ArgType, Uniform}; -use abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods}; +use crate::abi::call::{FnType, ArgType, Uniform}; +use crate::abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods}; // Data layout: e-p:32:32-i64:64-v128:32:128-n32-S128 @@ -26,7 +26,7 @@ fn classify_ret_ty<'a, Ty, C>(cx: &C, ret: &mut ArgType<'a, Ty>) } } -fn classify_arg_ty(arg: &mut ArgType) { +fn classify_arg_ty(arg: &mut ArgType<'_, Ty>) { if arg.layout.is_aggregate() { arg.make_indirect_byval(); } diff --git a/src/librustc_target/abi/call/hexagon.rs b/src/librustc_target/abi/call/hexagon.rs index d538a8068ac..db8c915cdb4 100644 --- a/src/librustc_target/abi/call/hexagon.rs +++ b/src/librustc_target/abi/call/hexagon.rs @@ -1,8 +1,8 @@ #![allow(non_upper_case_globals)] -use abi::call::{FnType, ArgType}; +use crate::abi::call::{FnType, ArgType}; -fn classify_ret_ty(ret: &mut ArgType) { +fn classify_ret_ty(ret: &mut ArgType<'_, Ty>) { if ret.layout.is_aggregate() && ret.layout.size.bits() > 64 { ret.make_indirect(); } else { @@ -10,7 +10,7 @@ fn classify_ret_ty(ret: &mut ArgType) { } } -fn classify_arg_ty(arg: &mut ArgType) { +fn classify_arg_ty(arg: &mut ArgType<'_, Ty>) { if arg.layout.is_aggregate() && arg.layout.size.bits() > 64 { arg.make_indirect(); } else { @@ -18,7 +18,7 @@ fn classify_arg_ty(arg: &mut ArgType) { } } -pub fn compute_abi_info(fty: &mut FnType) { +pub fn compute_abi_info(fty: &mut FnType<'_,Ty>) { if !fty.ret.is_ignore() { classify_ret_ty(&mut fty.ret); } diff --git a/src/librustc_target/abi/call/mips.rs b/src/librustc_target/abi/call/mips.rs index 2335bfbb5b8..d496abf8e8b 100644 --- a/src/librustc_target/abi/call/mips.rs +++ b/src/librustc_target/abi/call/mips.rs @@ -1,7 +1,7 @@ -use abi::call::{ArgType, FnType, Reg, Uniform}; -use abi::{HasDataLayout, LayoutOf, Size, TyLayoutMethods}; +use crate::abi::call::{ArgType, FnType, Reg, Uniform}; +use crate::abi::{HasDataLayout, LayoutOf, Size, TyLayoutMethods}; -fn classify_ret_ty<'a, Ty, C>(cx: &C, ret: &mut ArgType, offset: &mut Size) +fn classify_ret_ty<'a, Ty, C>(cx: &C, ret: &mut ArgType<'_, Ty>, offset: &mut Size) where Ty: TyLayoutMethods<'a, C>, C: LayoutOf + HasDataLayout { if !ret.layout.is_aggregate() { @@ -12,7 +12,7 @@ fn classify_ret_ty<'a, Ty, C>(cx: &C, ret: &mut ArgType, offset: &mut Size) } } -fn classify_arg_ty<'a, Ty, C>(cx: &C, arg: &mut ArgType, offset: &mut Size) +fn classify_arg_ty<'a, Ty, C>(cx: &C, arg: &mut ArgType<'_, Ty>, offset: &mut Size) where Ty: TyLayoutMethods<'a, C>, C: LayoutOf + HasDataLayout { let dl = cx.data_layout(); @@ -34,7 +34,7 @@ fn classify_arg_ty<'a, Ty, C>(cx: &C, arg: &mut ArgType, offset: &mut Size) *offset = offset.align_to(align) + size.align_to(align); } -pub fn compute_abi_info<'a, Ty, C>(cx: &C, fty: &mut FnType) +pub fn compute_abi_info<'a, Ty, C>(cx: &C, fty: &mut FnType<'_, Ty>) where Ty: TyLayoutMethods<'a, C>, C: LayoutOf + HasDataLayout { let mut offset = Size::ZERO; diff --git a/src/librustc_target/abi/call/mips64.rs b/src/librustc_target/abi/call/mips64.rs index 6f3e6494a4a..5ba05c6bcde 100644 --- a/src/librustc_target/abi/call/mips64.rs +++ b/src/librustc_target/abi/call/mips64.rs @@ -1,7 +1,7 @@ -use abi::call::{ArgAttribute, ArgType, CastTarget, FnType, PassMode, Reg, RegKind, Uniform}; -use abi::{self, HasDataLayout, LayoutOf, Size, TyLayout, TyLayoutMethods}; +use crate::abi::call::{ArgAttribute, ArgType, CastTarget, FnType, PassMode, Reg, RegKind, Uniform}; +use crate::abi::{self, HasDataLayout, LayoutOf, Size, TyLayout, TyLayoutMethods}; -fn extend_integer_width_mips(arg: &mut ArgType, bits: u64) { +fn extend_integer_width_mips(arg: &mut ArgType<'_, Ty>, bits: u64) { // Always sign extend u32 values on 64-bit mips if let abi::Abi::Scalar(ref scalar) = arg.layout.abi { if let abi::Int(i, signed) = scalar.value { diff --git a/src/librustc_target/abi/call/mod.rs b/src/librustc_target/abi/call/mod.rs index 0d50439c67e..839c9a857e6 100644 --- a/src/librustc_target/abi/call/mod.rs +++ b/src/librustc_target/abi/call/mod.rs @@ -1,6 +1,6 @@ -use abi::{self, Abi, Align, FieldPlacement, Size}; -use abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods}; -use spec::HasTargetSpec; +use crate::abi::{self, Abi, Align, FieldPlacement, Size}; +use crate::abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods}; +use crate::spec::{self, HasTargetSpec}; mod aarch64; mod amdgpu; @@ -42,13 +42,13 @@ pub enum PassMode { // Hack to disable non_upper_case_globals only for the bitflags! and not for the rest // of this module -pub use self::attr_impl::ArgAttribute; +pub use attr_impl::ArgAttribute; #[allow(non_upper_case_globals)] #[allow(unused)] mod attr_impl { // The subset of llvm::Attribute needed for arguments, packed into a bitfield. - bitflags! { + bitflags::bitflags! { #[derive(Default)] pub struct ArgAttribute: u16 { const ByVal = 1 << 0; @@ -526,22 +526,22 @@ pub struct FnType<'a, Ty> { } impl<'a, Ty> FnType<'a, Ty> { - pub fn adjust_for_cabi(&mut self, cx: &C, abi: ::spec::abi::Abi) -> Result<(), String> + pub fn adjust_for_cabi(&mut self, cx: &C, abi: spec::abi::Abi) -> Result<(), String> where Ty: TyLayoutMethods<'a, C> + Copy, C: LayoutOf> + HasDataLayout + HasTargetSpec { match &cx.target_spec().arch[..] { "x86" => { - let flavor = if abi == ::spec::abi::Abi::Fastcall { + let flavor = if abi == spec::abi::Abi::Fastcall { x86::Flavor::Fastcall } else { x86::Flavor::General }; x86::compute_abi_info(cx, self, flavor); }, - "x86_64" => if abi == ::spec::abi::Abi::SysV64 { + "x86_64" => if abi == spec::abi::Abi::SysV64 { x86_64::compute_abi_info(cx, self); - } else if abi == ::spec::abi::Abi::Win64 || cx.target_spec().options.is_like_windows { + } else if abi == spec::abi::Abi::Win64 || cx.target_spec().options.is_like_windows { x86_win64::compute_abi_info(self); } else { x86_64::compute_abi_info(cx, self); diff --git a/src/librustc_target/abi/call/msp430.rs b/src/librustc_target/abi/call/msp430.rs index d8ba37db53d..7ae1116cba8 100644 --- a/src/librustc_target/abi/call/msp430.rs +++ b/src/librustc_target/abi/call/msp430.rs @@ -1,7 +1,7 @@ // Reference: MSP430 Embedded Application Binary Interface // http://www.ti.com/lit/an/slaa534/slaa534.pdf -use abi::call::{ArgType, FnType}; +use crate::abi::call::{ArgType, FnType}; // 3.5 Structures or Unions Passed and Returned by Reference // @@ -9,7 +9,7 @@ // returned by reference. To pass a structure or union by reference, the caller // places its address in the appropriate location: either in a register or on // the stack, according to its position in the argument list. (..)" -fn classify_ret_ty(ret: &mut ArgType) { +fn classify_ret_ty(ret: &mut ArgType<'_, Ty>) { if ret.layout.is_aggregate() && ret.layout.size.bits() > 32 { ret.make_indirect(); } else { @@ -17,7 +17,7 @@ fn classify_ret_ty(ret: &mut ArgType) { } } -fn classify_arg_ty(arg: &mut ArgType) { +fn classify_arg_ty(arg: &mut ArgType<'_, Ty>) { if arg.layout.is_aggregate() && arg.layout.size.bits() > 32 { arg.make_indirect(); } else { @@ -25,7 +25,7 @@ fn classify_arg_ty(arg: &mut ArgType) { } } -pub fn compute_abi_info(fty: &mut FnType) { +pub fn compute_abi_info(fty: &mut FnType<'_, Ty>) { if !fty.ret.is_ignore() { classify_ret_ty(&mut fty.ret); } diff --git a/src/librustc_target/abi/call/nvptx.rs b/src/librustc_target/abi/call/nvptx.rs index 4cf0f11eb1e..4722249f730 100644 --- a/src/librustc_target/abi/call/nvptx.rs +++ b/src/librustc_target/abi/call/nvptx.rs @@ -1,9 +1,9 @@ // Reference: PTX Writer's Guide to Interoperability // http://docs.nvidia.com/cuda/ptx-writers-guide-to-interoperability -use abi::call::{ArgType, FnType}; +use crate::abi::call::{ArgType, FnType}; -fn classify_ret_ty(ret: &mut ArgType) { +fn classify_ret_ty(ret: &mut ArgType<'_, Ty>) { if ret.layout.is_aggregate() && ret.layout.size.bits() > 32 { ret.make_indirect(); } else { @@ -11,7 +11,7 @@ fn classify_ret_ty(ret: &mut ArgType) { } } -fn classify_arg_ty(arg: &mut ArgType) { +fn classify_arg_ty(arg: &mut ArgType<'_, Ty>) { if arg.layout.is_aggregate() && arg.layout.size.bits() > 32 { arg.make_indirect(); } else { @@ -19,7 +19,7 @@ fn classify_arg_ty(arg: &mut ArgType) { } } -pub fn compute_abi_info(fty: &mut FnType) { +pub fn compute_abi_info(fty: &mut FnType<'_, Ty>) { if !fty.ret.is_ignore() { classify_ret_ty(&mut fty.ret); } diff --git a/src/librustc_target/abi/call/nvptx64.rs b/src/librustc_target/abi/call/nvptx64.rs index 8ccc77598c9..51c00ae007c 100644 --- a/src/librustc_target/abi/call/nvptx64.rs +++ b/src/librustc_target/abi/call/nvptx64.rs @@ -1,9 +1,9 @@ // Reference: PTX Writer's Guide to Interoperability // http://docs.nvidia.com/cuda/ptx-writers-guide-to-interoperability -use abi::call::{ArgType, FnType}; +use crate::abi::call::{ArgType, FnType}; -fn classify_ret_ty(ret: &mut ArgType) { +fn classify_ret_ty(ret: &mut ArgType<'_, Ty>) { if ret.layout.is_aggregate() && ret.layout.size.bits() > 64 { ret.make_indirect(); } else { @@ -11,7 +11,7 @@ fn classify_ret_ty(ret: &mut ArgType) { } } -fn classify_arg_ty(arg: &mut ArgType) { +fn classify_arg_ty(arg: &mut ArgType<'_, Ty>) { if arg.layout.is_aggregate() && arg.layout.size.bits() > 64 { arg.make_indirect(); } else { @@ -19,7 +19,7 @@ fn classify_arg_ty(arg: &mut ArgType) { } } -pub fn compute_abi_info(fty: &mut FnType) { +pub fn compute_abi_info(fty: &mut FnType<'_, Ty>) { if !fty.ret.is_ignore() { classify_ret_ty(&mut fty.ret); } diff --git a/src/librustc_target/abi/call/powerpc.rs b/src/librustc_target/abi/call/powerpc.rs index 2335bfbb5b8..d496abf8e8b 100644 --- a/src/librustc_target/abi/call/powerpc.rs +++ b/src/librustc_target/abi/call/powerpc.rs @@ -1,7 +1,7 @@ -use abi::call::{ArgType, FnType, Reg, Uniform}; -use abi::{HasDataLayout, LayoutOf, Size, TyLayoutMethods}; +use crate::abi::call::{ArgType, FnType, Reg, Uniform}; +use crate::abi::{HasDataLayout, LayoutOf, Size, TyLayoutMethods}; -fn classify_ret_ty<'a, Ty, C>(cx: &C, ret: &mut ArgType, offset: &mut Size) +fn classify_ret_ty<'a, Ty, C>(cx: &C, ret: &mut ArgType<'_, Ty>, offset: &mut Size) where Ty: TyLayoutMethods<'a, C>, C: LayoutOf + HasDataLayout { if !ret.layout.is_aggregate() { @@ -12,7 +12,7 @@ fn classify_ret_ty<'a, Ty, C>(cx: &C, ret: &mut ArgType, offset: &mut Size) } } -fn classify_arg_ty<'a, Ty, C>(cx: &C, arg: &mut ArgType, offset: &mut Size) +fn classify_arg_ty<'a, Ty, C>(cx: &C, arg: &mut ArgType<'_, Ty>, offset: &mut Size) where Ty: TyLayoutMethods<'a, C>, C: LayoutOf + HasDataLayout { let dl = cx.data_layout(); @@ -34,7 +34,7 @@ fn classify_arg_ty<'a, Ty, C>(cx: &C, arg: &mut ArgType, offset: &mut Size) *offset = offset.align_to(align) + size.align_to(align); } -pub fn compute_abi_info<'a, Ty, C>(cx: &C, fty: &mut FnType) +pub fn compute_abi_info<'a, Ty, C>(cx: &C, fty: &mut FnType<'_, Ty>) where Ty: TyLayoutMethods<'a, C>, C: LayoutOf + HasDataLayout { let mut offset = Size::ZERO; diff --git a/src/librustc_target/abi/call/powerpc64.rs b/src/librustc_target/abi/call/powerpc64.rs index 305a2d42250..a9683104d16 100644 --- a/src/librustc_target/abi/call/powerpc64.rs +++ b/src/librustc_target/abi/call/powerpc64.rs @@ -2,16 +2,16 @@ // Alignment of 128 bit types is not currently handled, this will // need to be fixed when PowerPC vector support is added. -use abi::call::{FnType, ArgType, Reg, RegKind, Uniform}; -use abi::{Endian, HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods}; -use spec::HasTargetSpec; +use crate::abi::call::{FnType, ArgType, Reg, RegKind, Uniform}; +use crate::abi::{Endian, HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods}; +use crate::spec::HasTargetSpec; #[derive(Debug, Clone, Copy, PartialEq)] enum ABI { ELFv1, // original ABI used for powerpc64 (big-endian) ELFv2, // newer ABI used for powerpc64le and musl (both endians) } -use self::ABI::*; +use ABI::*; fn is_homogeneous_aggregate<'a, Ty, C>(cx: &C, arg: &mut ArgType<'a, Ty>, abi: ABI) -> Option diff --git a/src/librustc_target/abi/call/riscv.rs b/src/librustc_target/abi/call/riscv.rs index 4950bcd3330..ba82e49ddb0 100644 --- a/src/librustc_target/abi/call/riscv.rs +++ b/src/librustc_target/abi/call/riscv.rs @@ -1,9 +1,9 @@ // Reference: RISC-V ELF psABI specification // https://github.com/riscv/riscv-elf-psabi-doc -use abi::call::{ArgType, FnType}; +use crate::abi::call::{ArgType, FnType}; -fn classify_ret_ty(arg: &mut ArgType, xlen: u64) { +fn classify_ret_ty(arg: &mut ArgType<'_, Ty>, xlen: u64) { // "Scalars wider than 2✕XLEN are passed by reference and are replaced in // the argument list with the address." // "Aggregates larger than 2✕XLEN bits are passed by reference and are @@ -19,7 +19,7 @@ fn classify_ret_ty(arg: &mut ArgType, xlen: u64) { arg.extend_integer_width_to(xlen); // this method only affects integer scalars } -fn classify_arg_ty(arg: &mut ArgType, xlen: u64) { +fn classify_arg_ty(arg: &mut ArgType<'_, Ty>, xlen: u64) { // "Scalars wider than 2✕XLEN are passed by reference and are replaced in // the argument list with the address." // "Aggregates larger than 2✕XLEN bits are passed by reference and are @@ -35,7 +35,7 @@ fn classify_arg_ty(arg: &mut ArgType, xlen: u64) { arg.extend_integer_width_to(xlen); // this method only affects integer scalars } -pub fn compute_abi_info(fty: &mut FnType, xlen: u64) { +pub fn compute_abi_info(fty: &mut FnType<'_, Ty>, xlen: u64) { if !fty.ret.is_ignore() { classify_ret_ty(&mut fty.ret, xlen); } diff --git a/src/librustc_target/abi/call/s390x.rs b/src/librustc_target/abi/call/s390x.rs index 954c37fee42..c2717b1bcb8 100644 --- a/src/librustc_target/abi/call/s390x.rs +++ b/src/librustc_target/abi/call/s390x.rs @@ -1,10 +1,10 @@ // FIXME: The assumes we're using the non-vector ABI, i.e., compiling // for a pre-z13 machine or using -mno-vx. -use abi::call::{FnType, ArgType, Reg}; -use abi::{self, HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods}; +use crate::abi::call::{FnType, ArgType, Reg}; +use crate::abi::{self, HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods}; -fn classify_ret_ty<'a, Ty, C>(ret: &mut ArgType) +fn classify_ret_ty<'a, Ty, C>(ret: &mut ArgType<'_, Ty>) where Ty: TyLayoutMethods<'a, C>, C: LayoutOf + HasDataLayout { if !ret.layout.is_aggregate() && ret.layout.size.bits() <= 64 { diff --git a/src/librustc_target/abi/call/sparc.rs b/src/librustc_target/abi/call/sparc.rs index 2335bfbb5b8..d496abf8e8b 100644 --- a/src/librustc_target/abi/call/sparc.rs +++ b/src/librustc_target/abi/call/sparc.rs @@ -1,7 +1,7 @@ -use abi::call::{ArgType, FnType, Reg, Uniform}; -use abi::{HasDataLayout, LayoutOf, Size, TyLayoutMethods}; +use crate::abi::call::{ArgType, FnType, Reg, Uniform}; +use crate::abi::{HasDataLayout, LayoutOf, Size, TyLayoutMethods}; -fn classify_ret_ty<'a, Ty, C>(cx: &C, ret: &mut ArgType, offset: &mut Size) +fn classify_ret_ty<'a, Ty, C>(cx: &C, ret: &mut ArgType<'_, Ty>, offset: &mut Size) where Ty: TyLayoutMethods<'a, C>, C: LayoutOf + HasDataLayout { if !ret.layout.is_aggregate() { @@ -12,7 +12,7 @@ fn classify_ret_ty<'a, Ty, C>(cx: &C, ret: &mut ArgType, offset: &mut Size) } } -fn classify_arg_ty<'a, Ty, C>(cx: &C, arg: &mut ArgType, offset: &mut Size) +fn classify_arg_ty<'a, Ty, C>(cx: &C, arg: &mut ArgType<'_, Ty>, offset: &mut Size) where Ty: TyLayoutMethods<'a, C>, C: LayoutOf + HasDataLayout { let dl = cx.data_layout(); @@ -34,7 +34,7 @@ fn classify_arg_ty<'a, Ty, C>(cx: &C, arg: &mut ArgType, offset: &mut Size) *offset = offset.align_to(align) + size.align_to(align); } -pub fn compute_abi_info<'a, Ty, C>(cx: &C, fty: &mut FnType) +pub fn compute_abi_info<'a, Ty, C>(cx: &C, fty: &mut FnType<'_, Ty>) where Ty: TyLayoutMethods<'a, C>, C: LayoutOf + HasDataLayout { let mut offset = Size::ZERO; diff --git a/src/librustc_target/abi/call/sparc64.rs b/src/librustc_target/abi/call/sparc64.rs index 150b48a8d02..d8930a875ef 100644 --- a/src/librustc_target/abi/call/sparc64.rs +++ b/src/librustc_target/abi/call/sparc64.rs @@ -1,7 +1,7 @@ // FIXME: This needs an audit for correctness and completeness. -use abi::call::{FnType, ArgType, Reg, RegKind, Uniform}; -use abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods}; +use crate::abi::call::{FnType, ArgType, Reg, RegKind, Uniform}; +use crate::abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods}; fn is_homogeneous_aggregate<'a, Ty, C>(cx: &C, arg: &mut ArgType<'a, Ty>) -> Option diff --git a/src/librustc_target/abi/call/wasm32.rs b/src/librustc_target/abi/call/wasm32.rs index 78f43f8b508..1fdcbb8e39b 100644 --- a/src/librustc_target/abi/call/wasm32.rs +++ b/src/librustc_target/abi/call/wasm32.rs @@ -1,14 +1,14 @@ -use abi::call::{FnType, ArgType}; +use crate::abi::call::{FnType, ArgType}; -fn classify_ret_ty(ret: &mut ArgType) { +fn classify_ret_ty(ret: &mut ArgType<'_, Ty>) { ret.extend_integer_width_to(32); } -fn classify_arg_ty(arg: &mut ArgType) { +fn classify_arg_ty(arg: &mut ArgType<'_, Ty>) { arg.extend_integer_width_to(32); } -pub fn compute_abi_info(fty: &mut FnType) { +pub fn compute_abi_info(fty: &mut FnType<'_, Ty>) { if !fty.ret.is_ignore() { classify_ret_ty(&mut fty.ret); } diff --git a/src/librustc_target/abi/call/x86.rs b/src/librustc_target/abi/call/x86.rs index 648a4b5bb9d..2e809571ab1 100644 --- a/src/librustc_target/abi/call/x86.rs +++ b/src/librustc_target/abi/call/x86.rs @@ -1,6 +1,6 @@ -use abi::call::{ArgAttribute, FnType, PassMode, Reg, RegKind}; -use abi::{self, HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods}; -use spec::HasTargetSpec; +use crate::abi::call::{ArgAttribute, FnType, PassMode, Reg, RegKind}; +use crate::abi::{self, HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods}; +use crate::spec::HasTargetSpec; #[derive(PartialEq)] pub enum Flavor { diff --git a/src/librustc_target/abi/call/x86_64.rs b/src/librustc_target/abi/call/x86_64.rs index 9d8cc19aac5..680e529b108 100644 --- a/src/librustc_target/abi/call/x86_64.rs +++ b/src/librustc_target/abi/call/x86_64.rs @@ -1,8 +1,8 @@ // The classification code for the x86_64 ABI is taken from the clay language // https://github.com/jckarter/clay/blob/master/compiler/src/externals.cpp -use abi::call::{ArgType, CastTarget, FnType, Reg, RegKind}; -use abi::{self, Abi, HasDataLayout, LayoutOf, Size, TyLayout, TyLayoutMethods}; +use crate::abi::call::{ArgType, CastTarget, FnType, Reg, RegKind}; +use crate::abi::{self, Abi, HasDataLayout, LayoutOf, Size, TyLayout, TyLayoutMethods}; /// Classification of "eightbyte" components. // N.B., the order of the variants is from general to specific, diff --git a/src/librustc_target/abi/call/x86_win64.rs b/src/librustc_target/abi/call/x86_win64.rs index c583f7a0a2a..ebdeb63150a 100644 --- a/src/librustc_target/abi/call/x86_win64.rs +++ b/src/librustc_target/abi/call/x86_win64.rs @@ -1,10 +1,10 @@ -use abi::call::{ArgType, FnType, Reg}; -use abi::Abi; +use crate::abi::call::{ArgType, FnType, Reg}; +use crate::abi::Abi; // Win64 ABI: http://msdn.microsoft.com/en-us/library/zthk2dkh.aspx -pub fn compute_abi_info(fty: &mut FnType) { - let fixup = |a: &mut ArgType| { +pub fn compute_abi_info(fty: &mut FnType<'_, Ty>) { + let fixup = |a: &mut ArgType<'_, Ty>| { match a.layout.abi { Abi::Uninhabited => {} Abi::ScalarPair(..) | diff --git a/src/librustc_target/abi/mod.rs b/src/librustc_target/abi/mod.rs index 3f95e666535..bb194d5bb12 100644 --- a/src/librustc_target/abi/mod.rs +++ b/src/librustc_target/abi/mod.rs @@ -1,7 +1,7 @@ -pub use self::Integer::*; -pub use self::Primitive::*; +pub use Integer::*; +pub use Primitive::*; -use spec::Target; +use crate::spec::Target; use std::fmt; use std::ops::{Add, Deref, Sub, Mul, AddAssign, Range, RangeInclusive}; @@ -533,13 +533,13 @@ pub enum FloatTy { } impl fmt::Debug for FloatTy { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(self, f) } } impl fmt::Display for FloatTy { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.ty_to_string()) } } diff --git a/src/librustc_target/lib.rs b/src/librustc_target/lib.rs index 8e9d0851af1..e831eb41410 100644 --- a/src/librustc_target/lib.rs +++ b/src/librustc_target/lib.rs @@ -15,11 +15,11 @@ #![feature(slice_patterns)] #![feature(step_trait)] -#[macro_use] -extern crate bitflags; -extern crate serialize; +#![deny(rust_2018_idioms)] + #[macro_use] extern crate log; +#[allow(unused_extern_crates)] extern crate serialize as rustc_serialize; // used by deriving // See librustc_cratesio_shim/Cargo.toml for a comment explaining this. diff --git a/src/librustc_target/spec/aarch64_apple_ios.rs b/src/librustc_target/spec/aarch64_apple_ios.rs index 2210fd1e9e7..8bdc08c788d 100644 --- a/src/librustc_target/spec/aarch64_apple_ios.rs +++ b/src/librustc_target/spec/aarch64_apple_ios.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; use super::apple_ios_base::{opts, Arch}; pub fn target() -> TargetResult { diff --git a/src/librustc_target/spec/aarch64_fuchsia.rs b/src/librustc_target/spec/aarch64_fuchsia.rs index e39a1c2e106..308954d56f8 100644 --- a/src/librustc_target/spec/aarch64_fuchsia.rs +++ b/src/librustc_target/spec/aarch64_fuchsia.rs @@ -1,4 +1,4 @@ -use spec::{LldFlavor, LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LldFlavor, LinkerFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { let mut base = super::fuchsia_base::opts(); diff --git a/src/librustc_target/spec/aarch64_linux_android.rs b/src/librustc_target/spec/aarch64_linux_android.rs index c05964295d3..65160f6231e 100644 --- a/src/librustc_target/spec/aarch64_linux_android.rs +++ b/src/librustc_target/spec/aarch64_linux_android.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; // See https://developer.android.com/ndk/guides/abis.html#arm64-v8a // for target ABI requirements. diff --git a/src/librustc_target/spec/aarch64_pc_windows_msvc.rs b/src/librustc_target/spec/aarch64_pc_windows_msvc.rs index b33430b59e8..1aee381d604 100644 --- a/src/librustc_target/spec/aarch64_pc_windows_msvc.rs +++ b/src/librustc_target/spec/aarch64_pc_windows_msvc.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult, PanicStrategy}; +use crate::spec::{LinkerFlavor, Target, TargetResult, PanicStrategy}; pub fn target() -> TargetResult { let mut base = super::windows_msvc_base::opts(); diff --git a/src/librustc_target/spec/aarch64_unknown_cloudabi.rs b/src/librustc_target/spec/aarch64_unknown_cloudabi.rs index ac3345ce3f2..71419543067 100644 --- a/src/librustc_target/spec/aarch64_unknown_cloudabi.rs +++ b/src/librustc_target/spec/aarch64_unknown_cloudabi.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::cloudabi_base::opts(); diff --git a/src/librustc_target/spec/aarch64_unknown_freebsd.rs b/src/librustc_target/spec/aarch64_unknown_freebsd.rs index 1fb0a2bcf7c..36860649c53 100644 --- a/src/librustc_target/spec/aarch64_unknown_freebsd.rs +++ b/src/librustc_target/spec/aarch64_unknown_freebsd.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { let mut base = super::freebsd_base::opts(); diff --git a/src/librustc_target/spec/aarch64_unknown_hermit.rs b/src/librustc_target/spec/aarch64_unknown_hermit.rs index 26006d0060d..7b020605102 100644 --- a/src/librustc_target/spec/aarch64_unknown_hermit.rs +++ b/src/librustc_target/spec/aarch64_unknown_hermit.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::hermit_base::opts(); diff --git a/src/librustc_target/spec/aarch64_unknown_linux_gnu.rs b/src/librustc_target/spec/aarch64_unknown_linux_gnu.rs index d30d927b6dd..e772d8b532c 100644 --- a/src/librustc_target/spec/aarch64_unknown_linux_gnu.rs +++ b/src/librustc_target/spec/aarch64_unknown_linux_gnu.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { let mut base = super::linux_base::opts(); diff --git a/src/librustc_target/spec/aarch64_unknown_linux_musl.rs b/src/librustc_target/spec/aarch64_unknown_linux_musl.rs index 258725fed15..8123ee82ed5 100644 --- a/src/librustc_target/spec/aarch64_unknown_linux_musl.rs +++ b/src/librustc_target/spec/aarch64_unknown_linux_musl.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { let mut base = super::linux_musl_base::opts(); diff --git a/src/librustc_target/spec/aarch64_unknown_netbsd.rs b/src/librustc_target/spec/aarch64_unknown_netbsd.rs index 10aef8f923d..47ae08ade9a 100644 --- a/src/librustc_target/spec/aarch64_unknown_netbsd.rs +++ b/src/librustc_target/spec/aarch64_unknown_netbsd.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::netbsd_base::opts(); diff --git a/src/librustc_target/spec/aarch64_unknown_openbsd.rs b/src/librustc_target/spec/aarch64_unknown_openbsd.rs index 815e11a919c..c9cd64c3a84 100644 --- a/src/librustc_target/spec/aarch64_unknown_openbsd.rs +++ b/src/librustc_target/spec/aarch64_unknown_openbsd.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::openbsd_base::opts(); diff --git a/src/librustc_target/spec/abi.rs b/src/librustc_target/spec/abi.rs index 46606e707d7..c9c41f10922 100644 --- a/src/librustc_target/spec/abi.rs +++ b/src/librustc_target/spec/abi.rs @@ -96,7 +96,7 @@ pub fn generic(self) -> bool { } impl fmt::Display for Abi { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "\"{}\"", self.name()) } } diff --git a/src/librustc_target/spec/android_base.rs b/src/librustc_target/spec/android_base.rs index a8f8ad3185f..684c059b414 100644 --- a/src/librustc_target/spec/android_base.rs +++ b/src/librustc_target/spec/android_base.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, TargetOptions}; +use crate::spec::{LinkerFlavor, TargetOptions}; pub fn opts() -> TargetOptions { let mut base = super::linux_base::opts(); diff --git a/src/librustc_target/spec/apple_base.rs b/src/librustc_target/spec/apple_base.rs index a80d1904a74..c21f7f38ca5 100644 --- a/src/librustc_target/spec/apple_base.rs +++ b/src/librustc_target/spec/apple_base.rs @@ -1,6 +1,6 @@ use std::env; -use spec::{LinkArgs, TargetOptions}; +use crate::spec::{LinkArgs, TargetOptions}; pub fn opts() -> TargetOptions { // ELF TLS is only available in macOS 10.7+. If you try to compile for 10.6 diff --git a/src/librustc_target/spec/apple_ios_base.rs b/src/librustc_target/spec/apple_ios_base.rs index 72346ab1f34..3068ed8d206 100644 --- a/src/librustc_target/spec/apple_ios_base.rs +++ b/src/librustc_target/spec/apple_ios_base.rs @@ -1,8 +1,8 @@ use std::io; use std::process::Command; -use spec::{LinkArgs, LinkerFlavor, TargetOptions}; +use crate::spec::{LinkArgs, LinkerFlavor, TargetOptions}; -use self::Arch::*; +use Arch::*; #[allow(non_camel_case_types)] #[derive(Copy, Clone)] diff --git a/src/librustc_target/spec/arm_base.rs b/src/librustc_target/spec/arm_base.rs index 1d51d60c8f2..77e7bfac62d 100644 --- a/src/librustc_target/spec/arm_base.rs +++ b/src/librustc_target/spec/arm_base.rs @@ -1,4 +1,4 @@ -use spec::abi::Abi; +use crate::spec::abi::Abi; // All the calling conventions trigger an assertion(Unsupported calling convention) in llvm on arm pub fn abi_blacklist() -> Vec { diff --git a/src/librustc_target/spec/arm_linux_androideabi.rs b/src/librustc_target/spec/arm_linux_androideabi.rs index 5e4bebfa1c1..bb066dc9ad8 100644 --- a/src/librustc_target/spec/arm_linux_androideabi.rs +++ b/src/librustc_target/spec/arm_linux_androideabi.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { let mut base = super::android_base::opts(); diff --git a/src/librustc_target/spec/arm_unknown_linux_gnueabi.rs b/src/librustc_target/spec/arm_unknown_linux_gnueabi.rs index 0f891dacc6d..f291818ba80 100644 --- a/src/librustc_target/spec/arm_unknown_linux_gnueabi.rs +++ b/src/librustc_target/spec/arm_unknown_linux_gnueabi.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { let mut base = super::linux_base::opts(); diff --git a/src/librustc_target/spec/arm_unknown_linux_gnueabihf.rs b/src/librustc_target/spec/arm_unknown_linux_gnueabihf.rs index 5503bf326cd..32b509d9721 100644 --- a/src/librustc_target/spec/arm_unknown_linux_gnueabihf.rs +++ b/src/librustc_target/spec/arm_unknown_linux_gnueabihf.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { let mut base = super::linux_base::opts(); diff --git a/src/librustc_target/spec/arm_unknown_linux_musleabi.rs b/src/librustc_target/spec/arm_unknown_linux_musleabi.rs index c2162beba26..7637577e7e8 100644 --- a/src/librustc_target/spec/arm_unknown_linux_musleabi.rs +++ b/src/librustc_target/spec/arm_unknown_linux_musleabi.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { let mut base = super::linux_musl_base::opts(); diff --git a/src/librustc_target/spec/arm_unknown_linux_musleabihf.rs b/src/librustc_target/spec/arm_unknown_linux_musleabihf.rs index b3f00331b3c..9def151b3ef 100644 --- a/src/librustc_target/spec/arm_unknown_linux_musleabihf.rs +++ b/src/librustc_target/spec/arm_unknown_linux_musleabihf.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { let mut base = super::linux_musl_base::opts(); diff --git a/src/librustc_target/spec/armebv7r_none_eabi.rs b/src/librustc_target/spec/armebv7r_none_eabi.rs index cd41ffbab4d..86c62daa618 100644 --- a/src/librustc_target/spec/armebv7r_none_eabi.rs +++ b/src/librustc_target/spec/armebv7r_none_eabi.rs @@ -1,7 +1,7 @@ // Targets the Big endian Cortex-R4/R5 processor (ARMv7-R) use std::default::Default; -use spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { Ok(Target { diff --git a/src/librustc_target/spec/armebv7r_none_eabihf.rs b/src/librustc_target/spec/armebv7r_none_eabihf.rs index 05b12dd28ba..50ee76414ef 100644 --- a/src/librustc_target/spec/armebv7r_none_eabihf.rs +++ b/src/librustc_target/spec/armebv7r_none_eabihf.rs @@ -1,7 +1,7 @@ // Targets the Cortex-R4F/R5F processor (ARMv7-R) use std::default::Default; -use spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { Ok(Target { diff --git a/src/librustc_target/spec/armv4t_unknown_linux_gnueabi.rs b/src/librustc_target/spec/armv4t_unknown_linux_gnueabi.rs index 7fe021e5327..7cd4b14cdeb 100644 --- a/src/librustc_target/spec/armv4t_unknown_linux_gnueabi.rs +++ b/src/librustc_target/spec/armv4t_unknown_linux_gnueabi.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { let base = super::linux_base::opts(); diff --git a/src/librustc_target/spec/armv5te_unknown_linux_gnueabi.rs b/src/librustc_target/spec/armv5te_unknown_linux_gnueabi.rs index c85a80f6e8a..15f61482771 100644 --- a/src/librustc_target/spec/armv5te_unknown_linux_gnueabi.rs +++ b/src/librustc_target/spec/armv5te_unknown_linux_gnueabi.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { let base = super::linux_base::opts(); diff --git a/src/librustc_target/spec/armv5te_unknown_linux_musleabi.rs b/src/librustc_target/spec/armv5te_unknown_linux_musleabi.rs index dce767898c0..74915b942ea 100644 --- a/src/librustc_target/spec/armv5te_unknown_linux_musleabi.rs +++ b/src/librustc_target/spec/armv5te_unknown_linux_musleabi.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { let base = super::linux_musl_base::opts(); diff --git a/src/librustc_target/spec/armv6_unknown_netbsd_eabihf.rs b/src/librustc_target/spec/armv6_unknown_netbsd_eabihf.rs index 95cc41e6c98..e460b6c574a 100644 --- a/src/librustc_target/spec/armv6_unknown_netbsd_eabihf.rs +++ b/src/librustc_target/spec/armv6_unknown_netbsd_eabihf.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { let mut base = super::netbsd_base::opts(); diff --git a/src/librustc_target/spec/armv7_apple_ios.rs b/src/librustc_target/spec/armv7_apple_ios.rs index 98018215c80..2052d17403d 100644 --- a/src/librustc_target/spec/armv7_apple_ios.rs +++ b/src/librustc_target/spec/armv7_apple_ios.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; use super::apple_ios_base::{opts, Arch}; pub fn target() -> TargetResult { diff --git a/src/librustc_target/spec/armv7_linux_androideabi.rs b/src/librustc_target/spec/armv7_linux_androideabi.rs index 65c3c7f7057..92f1a55e024 100644 --- a/src/librustc_target/spec/armv7_linux_androideabi.rs +++ b/src/librustc_target/spec/armv7_linux_androideabi.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; // This target if is for the baseline of the Android v7a ABI // in thumb mode. It's named armv7-* instead of thumbv7-* diff --git a/src/librustc_target/spec/armv7_unknown_cloudabi_eabihf.rs b/src/librustc_target/spec/armv7_unknown_cloudabi_eabihf.rs index fa43879dcca..a6c7fb537c7 100644 --- a/src/librustc_target/spec/armv7_unknown_cloudabi_eabihf.rs +++ b/src/librustc_target/spec/armv7_unknown_cloudabi_eabihf.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::cloudabi_base::opts(); diff --git a/src/librustc_target/spec/armv7_unknown_linux_gnueabihf.rs b/src/librustc_target/spec/armv7_unknown_linux_gnueabihf.rs index 864c59b8184..f16215433c7 100644 --- a/src/librustc_target/spec/armv7_unknown_linux_gnueabihf.rs +++ b/src/librustc_target/spec/armv7_unknown_linux_gnueabihf.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; // This target is for glibc Linux on ARMv7 without NEON or // thumb-mode. See the thumbv7neon variant for enabling both. diff --git a/src/librustc_target/spec/armv7_unknown_linux_musleabihf.rs b/src/librustc_target/spec/armv7_unknown_linux_musleabihf.rs index ae0cb2c08b4..45a26966b71 100644 --- a/src/librustc_target/spec/armv7_unknown_linux_musleabihf.rs +++ b/src/librustc_target/spec/armv7_unknown_linux_musleabihf.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; // This target is for musl Linux on ARMv7 without thumb-mode or NEON. diff --git a/src/librustc_target/spec/armv7_unknown_netbsd_eabihf.rs b/src/librustc_target/spec/armv7_unknown_netbsd_eabihf.rs index f9e416fd06e..44e2636e918 100644 --- a/src/librustc_target/spec/armv7_unknown_netbsd_eabihf.rs +++ b/src/librustc_target/spec/armv7_unknown_netbsd_eabihf.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { let base = super::netbsd_base::opts(); diff --git a/src/librustc_target/spec/armv7r_none_eabi.rs b/src/librustc_target/spec/armv7r_none_eabi.rs index 38d115bc85e..19d332467de 100644 --- a/src/librustc_target/spec/armv7r_none_eabi.rs +++ b/src/librustc_target/spec/armv7r_none_eabi.rs @@ -1,7 +1,7 @@ // Targets the Little-endian Cortex-R4/R5 processor (ARMv7-R) use std::default::Default; -use spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { Ok(Target { diff --git a/src/librustc_target/spec/armv7r_none_eabihf.rs b/src/librustc_target/spec/armv7r_none_eabihf.rs index cb707f7183a..06ef9f3ec4e 100644 --- a/src/librustc_target/spec/armv7r_none_eabihf.rs +++ b/src/librustc_target/spec/armv7r_none_eabihf.rs @@ -1,7 +1,7 @@ // Targets the Little-endian Cortex-R4F/R5F processor (ARMv7-R) use std::default::Default; -use spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { Ok(Target { diff --git a/src/librustc_target/spec/armv7s_apple_ios.rs b/src/librustc_target/spec/armv7s_apple_ios.rs index 6d9635b308e..29e290285e4 100644 --- a/src/librustc_target/spec/armv7s_apple_ios.rs +++ b/src/librustc_target/spec/armv7s_apple_ios.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; use super::apple_ios_base::{opts, Arch}; pub fn target() -> TargetResult { diff --git a/src/librustc_target/spec/bitrig_base.rs b/src/librustc_target/spec/bitrig_base.rs index 3b6985fa4c8..9b34119fc00 100644 --- a/src/librustc_target/spec/bitrig_base.rs +++ b/src/librustc_target/spec/bitrig_base.rs @@ -1,4 +1,4 @@ -use spec::{TargetOptions, RelroLevel}; +use crate::spec::{TargetOptions, RelroLevel}; use std::default::Default; pub fn opts() -> TargetOptions { diff --git a/src/librustc_target/spec/cloudabi_base.rs b/src/librustc_target/spec/cloudabi_base.rs index 145de0ebe69..a34122d3e0f 100644 --- a/src/librustc_target/spec/cloudabi_base.rs +++ b/src/librustc_target/spec/cloudabi_base.rs @@ -1,4 +1,4 @@ -use spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel}; +use crate::spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel}; pub fn opts() -> TargetOptions { let mut args = LinkArgs::new(); diff --git a/src/librustc_target/spec/dragonfly_base.rs b/src/librustc_target/spec/dragonfly_base.rs index 6ce2912da75..766030e8015 100644 --- a/src/librustc_target/spec/dragonfly_base.rs +++ b/src/librustc_target/spec/dragonfly_base.rs @@ -1,4 +1,4 @@ -use spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel}; +use crate::spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel}; use std::default::Default; pub fn opts() -> TargetOptions { diff --git a/src/librustc_target/spec/freebsd_base.rs b/src/librustc_target/spec/freebsd_base.rs index 47316f77e63..51f030f5908 100644 --- a/src/librustc_target/spec/freebsd_base.rs +++ b/src/librustc_target/spec/freebsd_base.rs @@ -1,4 +1,4 @@ -use spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel}; +use crate::spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel}; use std::default::Default; pub fn opts() -> TargetOptions { diff --git a/src/librustc_target/spec/fuchsia_base.rs b/src/librustc_target/spec/fuchsia_base.rs index 5d94f308410..4e4f2fa0cf3 100644 --- a/src/librustc_target/spec/fuchsia_base.rs +++ b/src/librustc_target/spec/fuchsia_base.rs @@ -1,4 +1,4 @@ -use spec::{LldFlavor, LinkArgs, LinkerFlavor, TargetOptions}; +use crate::spec::{LldFlavor, LinkArgs, LinkerFlavor, TargetOptions}; use std::default::Default; pub fn opts() -> TargetOptions { diff --git a/src/librustc_target/spec/haiku_base.rs b/src/librustc_target/spec/haiku_base.rs index 00c6bd40dc5..d0710627053 100644 --- a/src/librustc_target/spec/haiku_base.rs +++ b/src/librustc_target/spec/haiku_base.rs @@ -1,4 +1,4 @@ -use spec::{TargetOptions, RelroLevel}; +use crate::spec::{TargetOptions, RelroLevel}; use std::default::Default; pub fn opts() -> TargetOptions { diff --git a/src/librustc_target/spec/hermit_base.rs b/src/librustc_target/spec/hermit_base.rs index d7d8562e055..ee753393ddb 100644 --- a/src/librustc_target/spec/hermit_base.rs +++ b/src/librustc_target/spec/hermit_base.rs @@ -1,4 +1,4 @@ -use spec::{LinkArgs, LinkerFlavor, PanicStrategy, TargetOptions}; +use crate::spec::{LinkArgs, LinkerFlavor, PanicStrategy, TargetOptions}; use std::default::Default; pub fn opts() -> TargetOptions { diff --git a/src/librustc_target/spec/i386_apple_ios.rs b/src/librustc_target/spec/i386_apple_ios.rs index d0e31763001..78e9cbb61ef 100644 --- a/src/librustc_target/spec/i386_apple_ios.rs +++ b/src/librustc_target/spec/i386_apple_ios.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; use super::apple_ios_base::{opts, Arch}; pub fn target() -> TargetResult { diff --git a/src/librustc_target/spec/i586_pc_windows_msvc.rs b/src/librustc_target/spec/i586_pc_windows_msvc.rs index 12a7f98beff..ba712aced84 100644 --- a/src/librustc_target/spec/i586_pc_windows_msvc.rs +++ b/src/librustc_target/spec/i586_pc_windows_msvc.rs @@ -1,4 +1,4 @@ -use spec::TargetResult; +use crate::spec::TargetResult; pub fn target() -> TargetResult { let mut base = super::i686_pc_windows_msvc::target()?; diff --git a/src/librustc_target/spec/i586_unknown_linux_gnu.rs b/src/librustc_target/spec/i586_unknown_linux_gnu.rs index 76f6a4eba38..49f4f2cb6b9 100644 --- a/src/librustc_target/spec/i586_unknown_linux_gnu.rs +++ b/src/librustc_target/spec/i586_unknown_linux_gnu.rs @@ -1,4 +1,4 @@ -use spec::TargetResult; +use crate::spec::TargetResult; pub fn target() -> TargetResult { let mut base = super::i686_unknown_linux_gnu::target()?; diff --git a/src/librustc_target/spec/i586_unknown_linux_musl.rs b/src/librustc_target/spec/i586_unknown_linux_musl.rs index 2b56fd7a7e3..0f2ccebd6da 100644 --- a/src/librustc_target/spec/i586_unknown_linux_musl.rs +++ b/src/librustc_target/spec/i586_unknown_linux_musl.rs @@ -1,4 +1,4 @@ -use spec::TargetResult; +use crate::spec::TargetResult; pub fn target() -> TargetResult { let mut base = super::i686_unknown_linux_musl::target()?; diff --git a/src/librustc_target/spec/i686_apple_darwin.rs b/src/librustc_target/spec/i686_apple_darwin.rs index 40d9588e463..c8a61296d33 100644 --- a/src/librustc_target/spec/i686_apple_darwin.rs +++ b/src/librustc_target/spec/i686_apple_darwin.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::apple_base::opts(); diff --git a/src/librustc_target/spec/i686_linux_android.rs b/src/librustc_target/spec/i686_linux_android.rs index 5b8cb7ac55d..3f73d24ee84 100644 --- a/src/librustc_target/spec/i686_linux_android.rs +++ b/src/librustc_target/spec/i686_linux_android.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; // See https://developer.android.com/ndk/guides/abis.html#x86 // for target ABI requirements. diff --git a/src/librustc_target/spec/i686_pc_windows_gnu.rs b/src/librustc_target/spec/i686_pc_windows_gnu.rs index d7bc38ca172..12214a7d531 100644 --- a/src/librustc_target/spec/i686_pc_windows_gnu.rs +++ b/src/librustc_target/spec/i686_pc_windows_gnu.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::windows_base::opts(); diff --git a/src/librustc_target/spec/i686_pc_windows_msvc.rs b/src/librustc_target/spec/i686_pc_windows_msvc.rs index f0d75ae4e9b..1967834819a 100644 --- a/src/librustc_target/spec/i686_pc_windows_msvc.rs +++ b/src/librustc_target/spec/i686_pc_windows_msvc.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::windows_msvc_base::opts(); diff --git a/src/librustc_target/spec/i686_unknown_cloudabi.rs b/src/librustc_target/spec/i686_unknown_cloudabi.rs index 3a9e4246981..f3b40633b40 100644 --- a/src/librustc_target/spec/i686_unknown_cloudabi.rs +++ b/src/librustc_target/spec/i686_unknown_cloudabi.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::cloudabi_base::opts(); diff --git a/src/librustc_target/spec/i686_unknown_dragonfly.rs b/src/librustc_target/spec/i686_unknown_dragonfly.rs index 9d71c5a8233..20315e7145c 100644 --- a/src/librustc_target/spec/i686_unknown_dragonfly.rs +++ b/src/librustc_target/spec/i686_unknown_dragonfly.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::dragonfly_base::opts(); diff --git a/src/librustc_target/spec/i686_unknown_freebsd.rs b/src/librustc_target/spec/i686_unknown_freebsd.rs index 627dffa89d2..71f05a140f3 100644 --- a/src/librustc_target/spec/i686_unknown_freebsd.rs +++ b/src/librustc_target/spec/i686_unknown_freebsd.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::freebsd_base::opts(); diff --git a/src/librustc_target/spec/i686_unknown_haiku.rs b/src/librustc_target/spec/i686_unknown_haiku.rs index 86c64ce684b..b807e4eee39 100644 --- a/src/librustc_target/spec/i686_unknown_haiku.rs +++ b/src/librustc_target/spec/i686_unknown_haiku.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::haiku_base::opts(); diff --git a/src/librustc_target/spec/i686_unknown_linux_gnu.rs b/src/librustc_target/spec/i686_unknown_linux_gnu.rs index ab388328311..5875cbf78bf 100644 --- a/src/librustc_target/spec/i686_unknown_linux_gnu.rs +++ b/src/librustc_target/spec/i686_unknown_linux_gnu.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::linux_base::opts(); diff --git a/src/librustc_target/spec/i686_unknown_linux_musl.rs b/src/librustc_target/spec/i686_unknown_linux_musl.rs index 81cbf57e577..732949034e8 100644 --- a/src/librustc_target/spec/i686_unknown_linux_musl.rs +++ b/src/librustc_target/spec/i686_unknown_linux_musl.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::linux_musl_base::opts(); diff --git a/src/librustc_target/spec/i686_unknown_netbsd.rs b/src/librustc_target/spec/i686_unknown_netbsd.rs index 1027e240224..e8a9f29ea5f 100644 --- a/src/librustc_target/spec/i686_unknown_netbsd.rs +++ b/src/librustc_target/spec/i686_unknown_netbsd.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::netbsd_base::opts(); diff --git a/src/librustc_target/spec/i686_unknown_openbsd.rs b/src/librustc_target/spec/i686_unknown_openbsd.rs index d2bbc6bb2db..d7c323e0d8a 100644 --- a/src/librustc_target/spec/i686_unknown_openbsd.rs +++ b/src/librustc_target/spec/i686_unknown_openbsd.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::openbsd_base::opts(); diff --git a/src/librustc_target/spec/l4re_base.rs b/src/librustc_target/spec/l4re_base.rs index 951005998be..9317f053efe 100644 --- a/src/librustc_target/spec/l4re_base.rs +++ b/src/librustc_target/spec/l4re_base.rs @@ -1,4 +1,4 @@ -use spec::{LinkArgs, LinkerFlavor, PanicStrategy, TargetOptions}; +use crate::spec::{LinkArgs, LinkerFlavor, PanicStrategy, TargetOptions}; use std::default::Default; //use std::process::Command; diff --git a/src/librustc_target/spec/linux_base.rs b/src/librustc_target/spec/linux_base.rs index b036bf81a75..195fba3915f 100644 --- a/src/librustc_target/spec/linux_base.rs +++ b/src/librustc_target/spec/linux_base.rs @@ -1,4 +1,4 @@ -use spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel}; +use crate::spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel}; use std::default::Default; pub fn opts() -> TargetOptions { diff --git a/src/librustc_target/spec/linux_musl_base.rs b/src/librustc_target/spec/linux_musl_base.rs index 1bc90d1a732..e294e63982d 100644 --- a/src/librustc_target/spec/linux_musl_base.rs +++ b/src/librustc_target/spec/linux_musl_base.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, TargetOptions}; +use crate::spec::{LinkerFlavor, TargetOptions}; pub fn opts() -> TargetOptions { let mut base = super::linux_base::opts(); diff --git a/src/librustc_target/spec/mips64_unknown_linux_gnuabi64.rs b/src/librustc_target/spec/mips64_unknown_linux_gnuabi64.rs index 650f38702b6..3b38e64050f 100644 --- a/src/librustc_target/spec/mips64_unknown_linux_gnuabi64.rs +++ b/src/librustc_target/spec/mips64_unknown_linux_gnuabi64.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { Ok(Target { diff --git a/src/librustc_target/spec/mips64el_unknown_linux_gnuabi64.rs b/src/librustc_target/spec/mips64el_unknown_linux_gnuabi64.rs index cb348d49479..0f6cd86d616 100644 --- a/src/librustc_target/spec/mips64el_unknown_linux_gnuabi64.rs +++ b/src/librustc_target/spec/mips64el_unknown_linux_gnuabi64.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { Ok(Target { diff --git a/src/librustc_target/spec/mips_unknown_linux_gnu.rs b/src/librustc_target/spec/mips_unknown_linux_gnu.rs index 6cc3d30be1f..b4d29c5fbea 100644 --- a/src/librustc_target/spec/mips_unknown_linux_gnu.rs +++ b/src/librustc_target/spec/mips_unknown_linux_gnu.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { Ok(Target { diff --git a/src/librustc_target/spec/mips_unknown_linux_musl.rs b/src/librustc_target/spec/mips_unknown_linux_musl.rs index 152b11b4aee..c56c6e38229 100644 --- a/src/librustc_target/spec/mips_unknown_linux_musl.rs +++ b/src/librustc_target/spec/mips_unknown_linux_musl.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::linux_musl_base::opts(); diff --git a/src/librustc_target/spec/mips_unknown_linux_uclibc.rs b/src/librustc_target/spec/mips_unknown_linux_uclibc.rs index 99cd20e9a52..cb02769c7df 100644 --- a/src/librustc_target/spec/mips_unknown_linux_uclibc.rs +++ b/src/librustc_target/spec/mips_unknown_linux_uclibc.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { Ok(Target { diff --git a/src/librustc_target/spec/mipsel_unknown_linux_gnu.rs b/src/librustc_target/spec/mipsel_unknown_linux_gnu.rs index 476cf152706..ed49ddd4993 100644 --- a/src/librustc_target/spec/mipsel_unknown_linux_gnu.rs +++ b/src/librustc_target/spec/mipsel_unknown_linux_gnu.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { Ok(Target { diff --git a/src/librustc_target/spec/mipsel_unknown_linux_musl.rs b/src/librustc_target/spec/mipsel_unknown_linux_musl.rs index 9df131dbe25..bcc49cf5ffe 100644 --- a/src/librustc_target/spec/mipsel_unknown_linux_musl.rs +++ b/src/librustc_target/spec/mipsel_unknown_linux_musl.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::linux_musl_base::opts(); diff --git a/src/librustc_target/spec/mipsel_unknown_linux_uclibc.rs b/src/librustc_target/spec/mipsel_unknown_linux_uclibc.rs index 37c55d11f25..205f328a24c 100644 --- a/src/librustc_target/spec/mipsel_unknown_linux_uclibc.rs +++ b/src/librustc_target/spec/mipsel_unknown_linux_uclibc.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { Ok(Target { diff --git a/src/librustc_target/spec/mod.rs b/src/librustc_target/spec/mod.rs index aeecce49b0c..107583e4fc0 100644 --- a/src/librustc_target/spec/mod.rs +++ b/src/librustc_target/spec/mod.rs @@ -40,7 +40,7 @@ use std::{fmt, io}; use std::path::{Path, PathBuf}; use std::str::FromStr; -use spec::abi::{Abi, lookup as lookup_abi}; +use crate::spec::abi::{Abi, lookup as lookup_abi}; pub mod abi; mod android_base; @@ -1408,7 +1408,7 @@ pub fn debug_triple(&self) -> String { } impl fmt::Display for TargetTriple { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.debug_triple()) } } diff --git a/src/librustc_target/spec/msp430_none_elf.rs b/src/librustc_target/spec/msp430_none_elf.rs index df564bc924b..90af5898089 100644 --- a/src/librustc_target/spec/msp430_none_elf.rs +++ b/src/librustc_target/spec/msp430_none_elf.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, PanicStrategy, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, PanicStrategy, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { Ok(Target { diff --git a/src/librustc_target/spec/netbsd_base.rs b/src/librustc_target/spec/netbsd_base.rs index b88d360dd37..e9cd98c0e71 100644 --- a/src/librustc_target/spec/netbsd_base.rs +++ b/src/librustc_target/spec/netbsd_base.rs @@ -1,4 +1,4 @@ -use spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel}; +use crate::spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel}; use std::default::Default; pub fn opts() -> TargetOptions { diff --git a/src/librustc_target/spec/nvptx64_nvidia_cuda.rs b/src/librustc_target/spec/nvptx64_nvidia_cuda.rs index e8512415e66..db9d6a7409e 100644 --- a/src/librustc_target/spec/nvptx64_nvidia_cuda.rs +++ b/src/librustc_target/spec/nvptx64_nvidia_cuda.rs @@ -1,5 +1,5 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult, PanicStrategy, MergeFunctions}; -use spec::abi::Abi; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult, PanicStrategy, MergeFunctions}; +use crate::spec::abi::Abi; pub fn target() -> TargetResult { Ok(Target { diff --git a/src/librustc_target/spec/openbsd_base.rs b/src/librustc_target/spec/openbsd_base.rs index 4bdf73fc922..5bcfd62d75b 100644 --- a/src/librustc_target/spec/openbsd_base.rs +++ b/src/librustc_target/spec/openbsd_base.rs @@ -1,4 +1,4 @@ -use spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel}; +use crate::spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel}; use std::default::Default; pub fn opts() -> TargetOptions { diff --git a/src/librustc_target/spec/powerpc64_unknown_freebsd.rs b/src/librustc_target/spec/powerpc64_unknown_freebsd.rs index cc7b87bfdeb..360876b9ff5 100644 --- a/src/librustc_target/spec/powerpc64_unknown_freebsd.rs +++ b/src/librustc_target/spec/powerpc64_unknown_freebsd.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::freebsd_base::opts(); diff --git a/src/librustc_target/spec/powerpc64_unknown_linux_gnu.rs b/src/librustc_target/spec/powerpc64_unknown_linux_gnu.rs index 1f7ae933ced..c16db7583f3 100644 --- a/src/librustc_target/spec/powerpc64_unknown_linux_gnu.rs +++ b/src/librustc_target/spec/powerpc64_unknown_linux_gnu.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult, RelroLevel}; +use crate::spec::{LinkerFlavor, Target, TargetResult, RelroLevel}; pub fn target() -> TargetResult { let mut base = super::linux_base::opts(); diff --git a/src/librustc_target/spec/powerpc64_unknown_linux_musl.rs b/src/librustc_target/spec/powerpc64_unknown_linux_musl.rs index 6fc8be8a5c4..ac0b7431f91 100644 --- a/src/librustc_target/spec/powerpc64_unknown_linux_musl.rs +++ b/src/librustc_target/spec/powerpc64_unknown_linux_musl.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::linux_musl_base::opts(); diff --git a/src/librustc_target/spec/powerpc64le_unknown_linux_gnu.rs b/src/librustc_target/spec/powerpc64le_unknown_linux_gnu.rs index 21791a75d2a..038b925a286 100644 --- a/src/librustc_target/spec/powerpc64le_unknown_linux_gnu.rs +++ b/src/librustc_target/spec/powerpc64le_unknown_linux_gnu.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::linux_base::opts(); diff --git a/src/librustc_target/spec/powerpc64le_unknown_linux_musl.rs b/src/librustc_target/spec/powerpc64le_unknown_linux_musl.rs index 38f7fe887f5..57103345f0a 100644 --- a/src/librustc_target/spec/powerpc64le_unknown_linux_musl.rs +++ b/src/librustc_target/spec/powerpc64le_unknown_linux_musl.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::linux_musl_base::opts(); diff --git a/src/librustc_target/spec/powerpc_unknown_linux_gnu.rs b/src/librustc_target/spec/powerpc_unknown_linux_gnu.rs index 286d177c864..38a801d5ab5 100644 --- a/src/librustc_target/spec/powerpc_unknown_linux_gnu.rs +++ b/src/librustc_target/spec/powerpc_unknown_linux_gnu.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::linux_base::opts(); diff --git a/src/librustc_target/spec/powerpc_unknown_linux_gnuspe.rs b/src/librustc_target/spec/powerpc_unknown_linux_gnuspe.rs index ae144af0472..675b2c749d6 100644 --- a/src/librustc_target/spec/powerpc_unknown_linux_gnuspe.rs +++ b/src/librustc_target/spec/powerpc_unknown_linux_gnuspe.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::linux_base::opts(); diff --git a/src/librustc_target/spec/powerpc_unknown_linux_musl.rs b/src/librustc_target/spec/powerpc_unknown_linux_musl.rs index 3b61889163b..240443aa98d 100644 --- a/src/librustc_target/spec/powerpc_unknown_linux_musl.rs +++ b/src/librustc_target/spec/powerpc_unknown_linux_musl.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::linux_musl_base::opts(); diff --git a/src/librustc_target/spec/powerpc_unknown_netbsd.rs b/src/librustc_target/spec/powerpc_unknown_netbsd.rs index e8662a78519..10e7089cf1c 100644 --- a/src/librustc_target/spec/powerpc_unknown_netbsd.rs +++ b/src/librustc_target/spec/powerpc_unknown_netbsd.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::netbsd_base::opts(); diff --git a/src/librustc_target/spec/redox_base.rs b/src/librustc_target/spec/redox_base.rs index dd32f02e340..dc51aeb5839 100644 --- a/src/librustc_target/spec/redox_base.rs +++ b/src/librustc_target/spec/redox_base.rs @@ -1,4 +1,4 @@ -use spec::{LinkArgs, LinkerFlavor, TargetOptions}; +use crate::spec::{LinkArgs, LinkerFlavor, TargetOptions}; use std::default::Default; pub fn opts() -> TargetOptions { diff --git a/src/librustc_target/spec/riscv32imac_unknown_none_elf.rs b/src/librustc_target/spec/riscv32imac_unknown_none_elf.rs index 8adf562ca7e..5064393d311 100644 --- a/src/librustc_target/spec/riscv32imac_unknown_none_elf.rs +++ b/src/librustc_target/spec/riscv32imac_unknown_none_elf.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, LldFlavor, PanicStrategy, +use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { diff --git a/src/librustc_target/spec/riscv32imc_unknown_none_elf.rs b/src/librustc_target/spec/riscv32imc_unknown_none_elf.rs index 5d8157ee59a..31e74c5920c 100644 --- a/src/librustc_target/spec/riscv32imc_unknown_none_elf.rs +++ b/src/librustc_target/spec/riscv32imc_unknown_none_elf.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, LldFlavor, PanicStrategy, +use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { diff --git a/src/librustc_target/spec/riscv_base.rs b/src/librustc_target/spec/riscv_base.rs index ea7fdc39a9a..ec1dc9b4918 100644 --- a/src/librustc_target/spec/riscv_base.rs +++ b/src/librustc_target/spec/riscv_base.rs @@ -1,4 +1,4 @@ -use spec::abi::Abi; +use crate::spec::abi::Abi; // All the calling conventions trigger an assertion(Unsupported calling // convention) in llvm on RISCV diff --git a/src/librustc_target/spec/s390x_unknown_linux_gnu.rs b/src/librustc_target/spec/s390x_unknown_linux_gnu.rs index c18c94511f8..f259787e1d5 100644 --- a/src/librustc_target/spec/s390x_unknown_linux_gnu.rs +++ b/src/librustc_target/spec/s390x_unknown_linux_gnu.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::linux_base::opts(); diff --git a/src/librustc_target/spec/solaris_base.rs b/src/librustc_target/spec/solaris_base.rs index f5f85092105..0dfbb13b773 100644 --- a/src/librustc_target/spec/solaris_base.rs +++ b/src/librustc_target/spec/solaris_base.rs @@ -1,4 +1,4 @@ -use spec::TargetOptions; +use crate::spec::TargetOptions; use std::default::Default; pub fn opts() -> TargetOptions { diff --git a/src/librustc_target/spec/sparc64_unknown_linux_gnu.rs b/src/librustc_target/spec/sparc64_unknown_linux_gnu.rs index e5e3752be7f..c842b22d4e1 100644 --- a/src/librustc_target/spec/sparc64_unknown_linux_gnu.rs +++ b/src/librustc_target/spec/sparc64_unknown_linux_gnu.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::linux_base::opts(); diff --git a/src/librustc_target/spec/sparc64_unknown_netbsd.rs b/src/librustc_target/spec/sparc64_unknown_netbsd.rs index 62efd41dbb8..78d53e69e8b 100644 --- a/src/librustc_target/spec/sparc64_unknown_netbsd.rs +++ b/src/librustc_target/spec/sparc64_unknown_netbsd.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::netbsd_base::opts(); diff --git a/src/librustc_target/spec/sparc_unknown_linux_gnu.rs b/src/librustc_target/spec/sparc_unknown_linux_gnu.rs index b6468993790..162cd311a38 100644 --- a/src/librustc_target/spec/sparc_unknown_linux_gnu.rs +++ b/src/librustc_target/spec/sparc_unknown_linux_gnu.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::linux_base::opts(); diff --git a/src/librustc_target/spec/sparcv9_sun_solaris.rs b/src/librustc_target/spec/sparcv9_sun_solaris.rs index f1c5c5ac44f..acc03fd0d79 100644 --- a/src/librustc_target/spec/sparcv9_sun_solaris.rs +++ b/src/librustc_target/spec/sparcv9_sun_solaris.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::solaris_base::opts(); diff --git a/src/librustc_target/spec/thumb_base.rs b/src/librustc_target/spec/thumb_base.rs index 06cb6a8d823..ed0dbb766a8 100644 --- a/src/librustc_target/spec/thumb_base.rs +++ b/src/librustc_target/spec/thumb_base.rs @@ -28,7 +28,7 @@ // build scripts / gcc flags. use std::default::Default; -use spec::{PanicStrategy, TargetOptions}; +use crate::spec::{PanicStrategy, TargetOptions}; pub fn opts() -> TargetOptions { // See rust-lang/rfcs#1645 for a discussion about these defaults diff --git a/src/librustc_target/spec/thumbv6m_none_eabi.rs b/src/librustc_target/spec/thumbv6m_none_eabi.rs index 98c46e9c600..2ab61b57f6b 100644 --- a/src/librustc_target/spec/thumbv6m_none_eabi.rs +++ b/src/librustc_target/spec/thumbv6m_none_eabi.rs @@ -1,6 +1,6 @@ // Targets the Cortex-M0, Cortex-M0+ and Cortex-M1 processors (ARMv6-M architecture) -use spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { Ok(Target { diff --git a/src/librustc_target/spec/thumbv7a_pc_windows_msvc.rs b/src/librustc_target/spec/thumbv7a_pc_windows_msvc.rs index eaa08fadbc0..310fac31c0c 100644 --- a/src/librustc_target/spec/thumbv7a_pc_windows_msvc.rs +++ b/src/librustc_target/spec/thumbv7a_pc_windows_msvc.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult, PanicStrategy}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult, PanicStrategy}; pub fn target() -> TargetResult { let mut base = super::windows_msvc_base::opts(); diff --git a/src/librustc_target/spec/thumbv7em_none_eabi.rs b/src/librustc_target/spec/thumbv7em_none_eabi.rs index 8a1fe09cdb0..97114c342cd 100644 --- a/src/librustc_target/spec/thumbv7em_none_eabi.rs +++ b/src/librustc_target/spec/thumbv7em_none_eabi.rs @@ -9,7 +9,7 @@ // To opt-in to hardware accelerated floating point operations, you can use, for example, // `-C target-feature=+vfp4` or `-C target-cpu=cortex-m4`. -use spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { Ok(Target { diff --git a/src/librustc_target/spec/thumbv7em_none_eabihf.rs b/src/librustc_target/spec/thumbv7em_none_eabihf.rs index 0c9aa1c5149..e4358bdd799 100644 --- a/src/librustc_target/spec/thumbv7em_none_eabihf.rs +++ b/src/librustc_target/spec/thumbv7em_none_eabihf.rs @@ -8,7 +8,7 @@ // // To opt into double precision hardware support, use the `-C target-feature=-fp-only-sp` flag. -use spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { Ok(Target { diff --git a/src/librustc_target/spec/thumbv7m_none_eabi.rs b/src/librustc_target/spec/thumbv7m_none_eabi.rs index 9bff3473c58..daf25b16d58 100644 --- a/src/librustc_target/spec/thumbv7m_none_eabi.rs +++ b/src/librustc_target/spec/thumbv7m_none_eabi.rs @@ -1,6 +1,6 @@ // Targets the Cortex-M3 processor (ARMv7-M) -use spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { Ok(Target { diff --git a/src/librustc_target/spec/thumbv7neon_linux_androideabi.rs b/src/librustc_target/spec/thumbv7neon_linux_androideabi.rs index 2d92e29c09d..e248b930e6e 100644 --- a/src/librustc_target/spec/thumbv7neon_linux_androideabi.rs +++ b/src/librustc_target/spec/thumbv7neon_linux_androideabi.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; // This target if is for the Android v7a ABI in thumb mode with // NEON unconditionally enabled and, therefore, with 32 FPU registers diff --git a/src/librustc_target/spec/thumbv7neon_unknown_linux_gnueabihf.rs b/src/librustc_target/spec/thumbv7neon_unknown_linux_gnueabihf.rs index bdf57969154..bef62b0a2eb 100644 --- a/src/librustc_target/spec/thumbv7neon_unknown_linux_gnueabihf.rs +++ b/src/librustc_target/spec/thumbv7neon_unknown_linux_gnueabihf.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; // This target is for glibc Linux on ARMv7 with thumb mode enabled // (for consistency with Android and Debian-based distributions) diff --git a/src/librustc_target/spec/thumbv8m_base_none_eabi.rs b/src/librustc_target/spec/thumbv8m_base_none_eabi.rs index 0e0e73efd45..be8a476db4d 100644 --- a/src/librustc_target/spec/thumbv8m_base_none_eabi.rs +++ b/src/librustc_target/spec/thumbv8m_base_none_eabi.rs @@ -1,6 +1,6 @@ // Targets the Cortex-M23 processor (Baseline ARMv8-M) -use spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { Ok(Target { diff --git a/src/librustc_target/spec/thumbv8m_main_none_eabi.rs b/src/librustc_target/spec/thumbv8m_main_none_eabi.rs index dc2454d7497..49ab643d484 100644 --- a/src/librustc_target/spec/thumbv8m_main_none_eabi.rs +++ b/src/librustc_target/spec/thumbv8m_main_none_eabi.rs @@ -1,7 +1,7 @@ // Targets the Cortex-M33 processor (Armv8-M Mainline architecture profile), // without the Floating Point extension. -use spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { Ok(Target { diff --git a/src/librustc_target/spec/thumbv8m_main_none_eabihf.rs b/src/librustc_target/spec/thumbv8m_main_none_eabihf.rs index 5fa1f42288d..6a3d8e61d7f 100644 --- a/src/librustc_target/spec/thumbv8m_main_none_eabihf.rs +++ b/src/librustc_target/spec/thumbv8m_main_none_eabihf.rs @@ -1,7 +1,7 @@ // Targets the Cortex-M33 processor (Armv8-M Mainline architecture profile), // with the Floating Point extension. -use spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult}; pub fn target() -> TargetResult { Ok(Target { diff --git a/src/librustc_target/spec/uefi_base.rs b/src/librustc_target/spec/uefi_base.rs index 4628089ffe1..5078d500679 100644 --- a/src/librustc_target/spec/uefi_base.rs +++ b/src/librustc_target/spec/uefi_base.rs @@ -9,7 +9,7 @@ // the timer-interrupt. Device-drivers are required to use polling-based models. Furthermore, all // code runs in the same environment, no process separation is supported. -use spec::{LinkArgs, LinkerFlavor, LldFlavor, PanicStrategy, TargetOptions}; +use crate::spec::{LinkArgs, LinkerFlavor, LldFlavor, PanicStrategy, TargetOptions}; use std::default::Default; pub fn opts() -> TargetOptions { diff --git a/src/librustc_target/spec/windows_base.rs b/src/librustc_target/spec/windows_base.rs index 65d618232a2..38db9cd356c 100644 --- a/src/librustc_target/spec/windows_base.rs +++ b/src/librustc_target/spec/windows_base.rs @@ -1,4 +1,4 @@ -use spec::{LinkArgs, LinkerFlavor, TargetOptions}; +use crate::spec::{LinkArgs, LinkerFlavor, TargetOptions}; use std::default::Default; pub fn opts() -> TargetOptions { diff --git a/src/librustc_target/spec/windows_msvc_base.rs b/src/librustc_target/spec/windows_msvc_base.rs index 89f6b1bcc71..fdd747cdb86 100644 --- a/src/librustc_target/spec/windows_msvc_base.rs +++ b/src/librustc_target/spec/windows_msvc_base.rs @@ -1,4 +1,4 @@ -use spec::{LinkArgs, LinkerFlavor, TargetOptions}; +use crate::spec::{LinkArgs, LinkerFlavor, TargetOptions}; use std::default::Default; pub fn opts() -> TargetOptions { diff --git a/src/librustc_target/spec/x86_64_apple_darwin.rs b/src/librustc_target/spec/x86_64_apple_darwin.rs index 7de33fe8ac5..0911ce06c13 100644 --- a/src/librustc_target/spec/x86_64_apple_darwin.rs +++ b/src/librustc_target/spec/x86_64_apple_darwin.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::apple_base::opts(); diff --git a/src/librustc_target/spec/x86_64_apple_ios.rs b/src/librustc_target/spec/x86_64_apple_ios.rs index 286a73d4804..1f9594b9062 100644 --- a/src/librustc_target/spec/x86_64_apple_ios.rs +++ b/src/librustc_target/spec/x86_64_apple_ios.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult}; use super::apple_ios_base::{opts, Arch}; pub fn target() -> TargetResult { diff --git a/src/librustc_target/spec/x86_64_fuchsia.rs b/src/librustc_target/spec/x86_64_fuchsia.rs index 00fb7066ca2..a24d432c591 100644 --- a/src/librustc_target/spec/x86_64_fuchsia.rs +++ b/src/librustc_target/spec/x86_64_fuchsia.rs @@ -1,4 +1,4 @@ -use spec::{LldFlavor, LinkerFlavor, Target, TargetResult}; +use crate::spec::{LldFlavor, LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::fuchsia_base::opts(); diff --git a/src/librustc_target/spec/x86_64_linux_android.rs b/src/librustc_target/spec/x86_64_linux_android.rs index 29d5dfa5790..c3c6c7bf56f 100644 --- a/src/librustc_target/spec/x86_64_linux_android.rs +++ b/src/librustc_target/spec/x86_64_linux_android.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::android_base::opts(); diff --git a/src/librustc_target/spec/x86_64_pc_windows_gnu.rs b/src/librustc_target/spec/x86_64_pc_windows_gnu.rs index c3c36d22cef..35e0d55cd04 100644 --- a/src/librustc_target/spec/x86_64_pc_windows_gnu.rs +++ b/src/librustc_target/spec/x86_64_pc_windows_gnu.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::windows_base::opts(); diff --git a/src/librustc_target/spec/x86_64_pc_windows_msvc.rs b/src/librustc_target/spec/x86_64_pc_windows_msvc.rs index 178d67784e6..073d49be5a9 100644 --- a/src/librustc_target/spec/x86_64_pc_windows_msvc.rs +++ b/src/librustc_target/spec/x86_64_pc_windows_msvc.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::windows_msvc_base::opts(); diff --git a/src/librustc_target/spec/x86_64_rumprun_netbsd.rs b/src/librustc_target/spec/x86_64_rumprun_netbsd.rs index 37c7925c698..a2c706c4c72 100644 --- a/src/librustc_target/spec/x86_64_rumprun_netbsd.rs +++ b/src/librustc_target/spec/x86_64_rumprun_netbsd.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::netbsd_base::opts(); diff --git a/src/librustc_target/spec/x86_64_sun_solaris.rs b/src/librustc_target/spec/x86_64_sun_solaris.rs index 3534f9e6436..3bf3f51ae25 100644 --- a/src/librustc_target/spec/x86_64_sun_solaris.rs +++ b/src/librustc_target/spec/x86_64_sun_solaris.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::solaris_base::opts(); diff --git a/src/librustc_target/spec/x86_64_unknown_bitrig.rs b/src/librustc_target/spec/x86_64_unknown_bitrig.rs index fa539217560..999d93a7e60 100644 --- a/src/librustc_target/spec/x86_64_unknown_bitrig.rs +++ b/src/librustc_target/spec/x86_64_unknown_bitrig.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::bitrig_base::opts(); diff --git a/src/librustc_target/spec/x86_64_unknown_cloudabi.rs b/src/librustc_target/spec/x86_64_unknown_cloudabi.rs index c1253a3b272..d48120c5401 100644 --- a/src/librustc_target/spec/x86_64_unknown_cloudabi.rs +++ b/src/librustc_target/spec/x86_64_unknown_cloudabi.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::cloudabi_base::opts(); diff --git a/src/librustc_target/spec/x86_64_unknown_dragonfly.rs b/src/librustc_target/spec/x86_64_unknown_dragonfly.rs index 815aa572525..f55ee696909 100644 --- a/src/librustc_target/spec/x86_64_unknown_dragonfly.rs +++ b/src/librustc_target/spec/x86_64_unknown_dragonfly.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::dragonfly_base::opts(); diff --git a/src/librustc_target/spec/x86_64_unknown_freebsd.rs b/src/librustc_target/spec/x86_64_unknown_freebsd.rs index 8d43883f33b..1d9c5cce3f7 100644 --- a/src/librustc_target/spec/x86_64_unknown_freebsd.rs +++ b/src/librustc_target/spec/x86_64_unknown_freebsd.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::freebsd_base::opts(); diff --git a/src/librustc_target/spec/x86_64_unknown_haiku.rs b/src/librustc_target/spec/x86_64_unknown_haiku.rs index 608354732d9..4ab15fa4e90 100644 --- a/src/librustc_target/spec/x86_64_unknown_haiku.rs +++ b/src/librustc_target/spec/x86_64_unknown_haiku.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::haiku_base::opts(); diff --git a/src/librustc_target/spec/x86_64_unknown_hermit.rs b/src/librustc_target/spec/x86_64_unknown_hermit.rs index de5992cbf5e..a696ee16d7c 100644 --- a/src/librustc_target/spec/x86_64_unknown_hermit.rs +++ b/src/librustc_target/spec/x86_64_unknown_hermit.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::hermit_base::opts(); diff --git a/src/librustc_target/spec/x86_64_unknown_l4re_uclibc.rs b/src/librustc_target/spec/x86_64_unknown_l4re_uclibc.rs index cf04cc1bdc2..e5fdb386ef3 100644 --- a/src/librustc_target/spec/x86_64_unknown_l4re_uclibc.rs +++ b/src/librustc_target/spec/x86_64_unknown_l4re_uclibc.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::l4re_base::opts(); diff --git a/src/librustc_target/spec/x86_64_unknown_linux_gnu.rs b/src/librustc_target/spec/x86_64_unknown_linux_gnu.rs index c6ec8de5b73..cb279e86f14 100644 --- a/src/librustc_target/spec/x86_64_unknown_linux_gnu.rs +++ b/src/librustc_target/spec/x86_64_unknown_linux_gnu.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::linux_base::opts(); diff --git a/src/librustc_target/spec/x86_64_unknown_linux_gnux32.rs b/src/librustc_target/spec/x86_64_unknown_linux_gnux32.rs index e4dfb8d05cd..0b2d7aacc4d 100644 --- a/src/librustc_target/spec/x86_64_unknown_linux_gnux32.rs +++ b/src/librustc_target/spec/x86_64_unknown_linux_gnux32.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::linux_base::opts(); diff --git a/src/librustc_target/spec/x86_64_unknown_linux_musl.rs b/src/librustc_target/spec/x86_64_unknown_linux_musl.rs index 95321fe2f78..2e1bc839873 100644 --- a/src/librustc_target/spec/x86_64_unknown_linux_musl.rs +++ b/src/librustc_target/spec/x86_64_unknown_linux_musl.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::linux_musl_base::opts(); diff --git a/src/librustc_target/spec/x86_64_unknown_netbsd.rs b/src/librustc_target/spec/x86_64_unknown_netbsd.rs index fbd07ecce1a..ffc4f1d5c49 100644 --- a/src/librustc_target/spec/x86_64_unknown_netbsd.rs +++ b/src/librustc_target/spec/x86_64_unknown_netbsd.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::netbsd_base::opts(); diff --git a/src/librustc_target/spec/x86_64_unknown_openbsd.rs b/src/librustc_target/spec/x86_64_unknown_openbsd.rs index 68496247b15..f2abd107122 100644 --- a/src/librustc_target/spec/x86_64_unknown_openbsd.rs +++ b/src/librustc_target/spec/x86_64_unknown_openbsd.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::openbsd_base::opts(); diff --git a/src/librustc_target/spec/x86_64_unknown_redox.rs b/src/librustc_target/spec/x86_64_unknown_redox.rs index d04bc5cc6ec..f0a4519f595 100644 --- a/src/librustc_target/spec/x86_64_unknown_redox.rs +++ b/src/librustc_target/spec/x86_64_unknown_redox.rs @@ -1,4 +1,4 @@ -use spec::{LinkerFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::redox_base::opts(); diff --git a/src/librustc_target/spec/x86_64_unknown_uefi.rs b/src/librustc_target/spec/x86_64_unknown_uefi.rs index 0d7b4fc060b..9ac17a1693f 100644 --- a/src/librustc_target/spec/x86_64_unknown_uefi.rs +++ b/src/librustc_target/spec/x86_64_unknown_uefi.rs @@ -5,7 +5,7 @@ // The win64 ABI is used. It differs from the sysv64 ABI, so we must use a windows target with // LLVM. "x86_64-unknown-windows" is used to get the minimal subset of windows-specific features. -use spec::{LinkerFlavor, LldFlavor, Target, TargetResult}; +use crate::spec::{LinkerFlavor, LldFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::uefi_base::opts(); diff --git a/src/librustc_traits/Cargo.toml b/src/librustc_traits/Cargo.toml index bf946d39806..da19cc95eb9 100644 --- a/src/librustc_traits/Cargo.toml +++ b/src/librustc_traits/Cargo.toml @@ -2,6 +2,7 @@ authors = ["The Rust Project Developers"] name = "rustc_traits" version = "0.0.0" +edition = "2018" [lib] name = "rustc_traits" diff --git a/src/librustc_traits/chalk_context/mod.rs b/src/librustc_traits/chalk_context/mod.rs index 303920b5842..ffa696c9080 100644 --- a/src/librustc_traits/chalk_context/mod.rs +++ b/src/librustc_traits/chalk_context/mod.rs @@ -502,13 +502,13 @@ fn into_ex_clause( type ChalkExClause<'tcx> = ExClause>; impl Debug for ChalkContext<'cx, 'gcx> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "ChalkContext") } } impl Debug for ChalkInferenceContext<'cx, 'gcx, 'tcx> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "ChalkInferenceContext") } } @@ -658,7 +658,7 @@ fn upcast(&self) -> Self::Upcasted { } } -crate fn provide(p: &mut Providers) { +crate fn provide(p: &mut Providers<'_>) { *p = Providers { evaluate_goal, ..*p diff --git a/src/librustc_traits/chalk_context/program_clauses.rs b/src/librustc_traits/chalk_context/program_clauses.rs index 71f4945fd64..adfd26814db 100644 --- a/src/librustc_traits/chalk_context/program_clauses.rs +++ b/src/librustc_traits/chalk_context/program_clauses.rs @@ -220,7 +220,7 @@ fn wf_clause_for_slice<'tcx>(tcx: ty::TyCtxt<'_, '_, 'tcx>) -> Clauses<'tcx> { def_id: sized_trait, substs: tcx.mk_substs_trait(ty, ty::List::empty()), }; - let sized_implemented: DomainGoal = ty::TraitPredicate { + let sized_implemented: DomainGoal<'_> = ty::TraitPredicate { trait_ref: sized_implemented }.lower(); @@ -252,7 +252,7 @@ fn wf_clause_for_array<'tcx>( def_id: sized_trait, substs: tcx.mk_substs_trait(ty, ty::List::empty()), }; - let sized_implemented: DomainGoal = ty::TraitPredicate { + let sized_implemented: DomainGoal<'_> = ty::TraitPredicate { trait_ref: sized_implemented }.lower(); @@ -326,7 +326,7 @@ fn wf_clause_for_ref<'tcx>( mutbl, }); - let _outlives: DomainGoal = ty::OutlivesPredicate(ty, region).lower(); + let _outlives: DomainGoal<'_> = ty::OutlivesPredicate(ty, region).lower(); let wf_clause = ProgramClause { goal: DomainGoal::WellFormed(WellFormed::Ty(ref_ty)), hypotheses: ty::List::empty(), diff --git a/src/librustc_traits/dropck_outlives.rs b/src/librustc_traits/dropck_outlives.rs index 7979fe4a750..45b19e1dc06 100644 --- a/src/librustc_traits/dropck_outlives.rs +++ b/src/librustc_traits/dropck_outlives.rs @@ -10,7 +10,7 @@ use rustc_data_structures::sync::Lrc; use syntax::source_map::{Span, DUMMY_SP}; -crate fn provide(p: &mut Providers) { +crate fn provide(p: &mut Providers<'_>) { *p = Providers { dropck_outlives, adt_dtorck_constraint, @@ -305,7 +305,7 @@ fn dtorck_constraint_for_ty<'a, 'gcx, 'tcx>( let mut result = def.all_fields() .map(|field| tcx.type_of(field.did)) .map(|fty| dtorck_constraint_for_ty(tcx, span, fty, 0, fty)) - .collect::>()?; + .collect::, NoSolution>>()?; result.outlives.extend(tcx.destructor_constraints(def)); dedup_dtorck_constraint(&mut result); diff --git a/src/librustc_traits/evaluate_obligation.rs b/src/librustc_traits/evaluate_obligation.rs index c5b6de27935..83aebd16e24 100644 --- a/src/librustc_traits/evaluate_obligation.rs +++ b/src/librustc_traits/evaluate_obligation.rs @@ -6,7 +6,7 @@ use rustc::ty::{ParamEnvAnd, TyCtxt}; use syntax::source_map::DUMMY_SP; -crate fn provide(p: &mut Providers) { +crate fn provide(p: &mut Providers<'_>) { *p = Providers { evaluate_obligation, ..*p diff --git a/src/librustc_traits/implied_outlives_bounds.rs b/src/librustc_traits/implied_outlives_bounds.rs index a3fb9699054..e4a032aaf7b 100644 --- a/src/librustc_traits/implied_outlives_bounds.rs +++ b/src/librustc_traits/implied_outlives_bounds.rs @@ -17,7 +17,7 @@ use rustc_data_structures::sync::Lrc; -crate fn provide(p: &mut Providers) { +crate fn provide(p: &mut Providers<'_>) { *p = Providers { implied_outlives_bounds, ..*p diff --git a/src/librustc_traits/lib.rs b/src/librustc_traits/lib.rs index a220b921913..d52a976981d 100644 --- a/src/librustc_traits/lib.rs +++ b/src/librustc_traits/lib.rs @@ -1,22 +1,18 @@ //! New recursive solver modeled on Chalk's recursive solver. Most of //! the guts are broken up into modules; see the comments in those modules. +#![deny(rust_2018_idioms)] + #![feature(crate_visibility_modifier)] #![feature(in_band_lifetimes)] #![feature(nll)] #![recursion_limit="256"] -extern crate chalk_engine; #[macro_use] extern crate log; #[macro_use] extern crate rustc; -extern crate rustc_data_structures; -extern crate rustc_target; -extern crate syntax; -extern crate syntax_pos; -extern crate smallvec; mod chalk_context; mod dropck_outlives; @@ -30,7 +26,7 @@ use rustc::ty::query::Providers; -pub fn provide(p: &mut Providers) { +pub fn provide(p: &mut Providers<'_>) { dropck_outlives::provide(p); evaluate_obligation::provide(p); implied_outlives_bounds::provide(p); diff --git a/src/librustc_traits/lowering/mod.rs b/src/librustc_traits/lowering/mod.rs index 9bdef3051e5..908fdcfe743 100644 --- a/src/librustc_traits/lowering/mod.rs +++ b/src/librustc_traits/lowering/mod.rs @@ -23,7 +23,7 @@ use std::iter; -crate fn provide(p: &mut Providers) { +crate fn provide(p: &mut Providers<'_>) { *p = Providers { program_clauses_for, program_clauses_for_env: environment::program_clauses_for_env, @@ -193,7 +193,7 @@ fn program_clauses_for_trait<'a, 'tcx>( }; // `Implemented(Self: Trait)` - let impl_trait: DomainGoal = trait_pred.lower(); + let impl_trait: DomainGoal<'_> = trait_pred.lower(); // `FromEnv(Self: Trait)` let from_env_goal = tcx.mk_goal(impl_trait.into_from_env_goal().into_goal()); @@ -575,7 +575,7 @@ pub fn program_clauses_for_associated_type_value<'a, 'tcx>( let ty = tcx.type_of(item_id); // `Implemented(A0: Trait)` - let trait_implemented: DomainGoal = ty::TraitPredicate { trait_ref }.lower(); + let trait_implemented: DomainGoal<'_> = ty::TraitPredicate { trait_ref }.lower(); // `>::AssocType` let projection_ty = ty::ProjectionTy::from_ref_and_name(tcx, trait_ref, item.ident); diff --git a/src/librustc_traits/normalize_erasing_regions.rs b/src/librustc_traits/normalize_erasing_regions.rs index c06cdbd0928..412d2ca6dfc 100644 --- a/src/librustc_traits/normalize_erasing_regions.rs +++ b/src/librustc_traits/normalize_erasing_regions.rs @@ -4,7 +4,7 @@ use rustc::ty::{self, ParamEnvAnd, Ty, TyCtxt}; use std::sync::atomic::Ordering; -crate fn provide(p: &mut Providers) { +crate fn provide(p: &mut Providers<'_>) { *p = Providers { normalize_ty_after_erasing_regions, ..*p diff --git a/src/librustc_traits/normalize_projection_ty.rs b/src/librustc_traits/normalize_projection_ty.rs index b31e9c15d03..6fe9e316cf3 100644 --- a/src/librustc_traits/normalize_projection_ty.rs +++ b/src/librustc_traits/normalize_projection_ty.rs @@ -8,7 +8,7 @@ use syntax::ast::DUMMY_NODE_ID; use syntax_pos::DUMMY_SP; -crate fn provide(p: &mut Providers) { +crate fn provide(p: &mut Providers<'_>) { *p = Providers { normalize_projection_ty, ..*p diff --git a/src/librustc_traits/type_op.rs b/src/librustc_traits/type_op.rs index 526637e108d..3cc2f77187a 100644 --- a/src/librustc_traits/type_op.rs +++ b/src/librustc_traits/type_op.rs @@ -21,7 +21,7 @@ use syntax::ast; use syntax_pos::DUMMY_SP; -crate fn provide(p: &mut Providers) { +crate fn provide(p: &mut Providers<'_>) { *p = Providers { type_op_ascribe_user_type, type_op_eq, diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 8da0b6dcbea..757385aeb3e 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -1793,7 +1793,7 @@ pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> { let length_def_id = tcx.hir().local_def_id(length.id); let substs = Substs::identity_for_item(tcx, length_def_id); let length = ty::LazyConst::Unevaluated(length_def_id, substs); - let length = tcx.intern_lazy_const(length); + let length = tcx.mk_lazy_const(length); let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length)); self.normalize_ty(ast_ty.span, array_ty) } diff --git a/src/librustc_typeck/check/method/probe.rs b/src/librustc_typeck/check/method/probe.rs index 623677482db..ada4a95ed7a 100644 --- a/src/librustc_typeck/check/method/probe.rs +++ b/src/librustc_typeck/check/method/probe.rs @@ -85,6 +85,37 @@ fn deref(&self) -> &Self::Target { #[derive(Debug)] struct Candidate<'tcx> { + // Candidates are (I'm not quite sure, but they are mostly) basically + // some metadata on top of a `ty::AssociatedItem` (without substs). + // + // However, method probing wants to be able to evaluate the predicates + // for a function with the substs applied - for example, if a function + // has `where Self: Sized`, we don't want to consider it unless `Self` + // is actually `Sized`, and similarly, return-type suggestions want + // to consider the "actual" return type. + // + // The way this is handled is through `xform_self_ty`. It contains + // the receiver type of this candidate, but `xform_self_ty`, + // `xform_ret_ty` and `kind` (which contains the predicates) have the + // generic parameters of this candidate substituted with the *same set* + // of inference variables, which acts as some weird sort of "query". + // + // When we check out a candidate, we require `xform_self_ty` to be + // a subtype of the passed-in self-type, and this equates the type + // variables in the rest of the fields. + // + // For example, if we have this candidate: + // ``` + // trait Foo { + // fn foo(&self) where Self: Sized; + // } + // ``` + // + // Then `xform_self_ty` will be `&'erased ?X` and `kind` will contain + // the predicate `?X: Sized`, so if we are evaluating `Foo` for a + // the receiver `&T`, we'll do the subtyping which will make `?X` + // get the right value, then when we evaluate the predicate we'll check + // if `T: Sized`. xform_self_ty: Ty<'tcx>, xform_ret_ty: Option>, item: ty::AssociatedItem, @@ -506,13 +537,28 @@ fn assemble_probe(&mut self, self_ty: &Canonical<'gcx, QueryResponse<'gcx, Ty<'g match self_ty.value.value.sty { ty::Dynamic(ref data, ..) => { if let Some(p) = data.principal() { - let InferOk { value: instantiated_self_ty, obligations: _ } = - self.fcx.probe_instantiate_query_response( - self.span, &self.orig_steps_var_values, self_ty) - .unwrap_or_else(|_| { - span_bug!(self.span, "{:?} was applicable but now isn't?", self_ty) - }); - self.assemble_inherent_candidates_from_object(instantiated_self_ty); + // Subtle: we can't use `instantiate_query_response` here: using it will + // commit to all of the type equalities assumed by inference going through + // autoderef (see the `method-probe-no-guessing` test). + // + // However, in this code, it is OK if we end up with an object type that is + // "more general" than the object type that we are evaluating. For *every* + // object type `MY_OBJECT`, a function call that goes through a trait-ref + // of the form `::func` is a valid + // `ObjectCandidate`, and it should be discoverable "exactly" through one + // of the iterations in the autoderef loop, so there is no problem with it + // being discoverable in another one of these iterations. + // + // Using `instantiate_canonical_with_fresh_inference_vars` on our + // `Canonical>>` and then *throwing away* the + // `CanonicalVarValues` will exactly give us such a generalization - it + // will still match the original object type, but it won't pollute our + // type variables in any form, so just do that! + let (QueryResponse { value: generalized_self_ty, .. }, _ignored_var_values) = + self.fcx.instantiate_canonical_with_fresh_inference_vars( + self.span, &self_ty); + + self.assemble_inherent_candidates_from_object(generalized_self_ty); self.assemble_inherent_impl_candidates_for_type(p.def_id()); } } diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 3e2a9d720f1..fb8f6088121 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -4597,7 +4597,7 @@ fn check_expr_kind( if element_ty.references_error() { tcx.types.err } else if let Ok(count) = count { - tcx.mk_ty(ty::Array(t, tcx.intern_lazy_const(ty::LazyConst::Evaluated(count)))) + tcx.mk_ty(ty::Array(t, tcx.mk_lazy_const(ty::LazyConst::Evaluated(count)))) } else { tcx.types.err } diff --git a/src/librustc_typeck/diagnostics.rs b/src/librustc_typeck/diagnostics.rs index 3ed09dfe992..e6533ac4b75 100644 --- a/src/librustc_typeck/diagnostics.rs +++ b/src/librustc_typeck/diagnostics.rs @@ -348,13 +348,14 @@ fn main() { "##, E0044: r##" -You can't use type parameters on foreign items. Example of erroneous code: +You can't use type or const parameters on foreign items. +Example of erroneous code: ```compile_fail,E0044 extern { fn some_func(x: T); } ``` -To fix this, replace the type parameter with the specializations that you +To fix this, replace the generic parameter with the specializations that you need: ``` diff --git a/src/librustdoc/html/static/main.js b/src/librustdoc/html/static/main.js index d6c05de0df6..877ac9a62bb 100644 --- a/src/librustdoc/html/static/main.js +++ b/src/librustdoc/html/static/main.js @@ -2026,7 +2026,7 @@ if (!DOMTokenList.prototype.remove) { } else if (action === "hide") { addClass(relatedDoc, "fns-now-collapsed"); addClass(docblock, "hidden-by-usual-hider"); - onEachLazy(toggle.childNodes, adjustToggle(true, dontApplyBlockRule); + onEachLazy(toggle.childNodes, adjustToggle(true, dontApplyBlockRule)); onEachLazy(relatedDoc.childNodes, implHider(true, dontApplyBlockRule)); } } diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 2cfe2cc896c..681d8eeaa0d 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -167,6 +167,17 @@ pub fn span(&self) -> Span { pub enum GenericArg { Lifetime(Lifetime), Type(P), + Const(AnonConst), +} + +impl GenericArg { + pub fn span(&self) -> Span { + match self { + GenericArg::Lifetime(lt) => lt.ident.span, + GenericArg::Type(ty) => ty.span, + GenericArg::Const(ct) => ct.value.span, + } + } } /// A path like `Foo<'a, T>` @@ -296,13 +307,32 @@ pub fn span(&self) -> Span { pub type GenericBounds = Vec; +/// Specifies the enforced ordering for generic parameters. In the future, +/// if we wanted to relax this order, we could override `PartialEq` and +/// `PartialOrd`, to allow the kinds to be unordered. +#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)] +pub enum ParamKindOrd { + Lifetime, + Type, + Const, +} + +impl fmt::Display for ParamKindOrd { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ParamKindOrd::Lifetime => "lifetime".fmt(f), + ParamKindOrd::Type => "type".fmt(f), + ParamKindOrd::Const => "const".fmt(f), + } + } +} + #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum GenericParamKind { /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`). Lifetime, - Type { - default: Option>, - }, + Type { default: Option> }, + Const { ty: P }, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] diff --git a/src/libsyntax/early_buffered_lints.rs b/src/libsyntax/early_buffered_lints.rs index 977e6d45877..29cb9cd7f30 100644 --- a/src/libsyntax/early_buffered_lints.rs +++ b/src/libsyntax/early_buffered_lints.rs @@ -12,6 +12,8 @@ pub enum BufferedEarlyLintId { /// Usage of `?` as a macro separator is deprecated. QuestionMarkMacroSep, IllFormedAttributeInput, + /// Usage of a duplicate macro matcher binding name. + DuplicateMacroMatcherBindingName, } /// Stores buffered lint info which can later be passed to `librustc`. diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index 1e83f6c03ec..6708e3c12a0 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -38,12 +38,14 @@ fn qpath_all(&self, self_type: P, bindings: Vec) -> (ast::QSelf, ast::Path); - // types + // types and consts fn ty_mt(&self, ty: P, mutbl: ast::Mutability) -> ast::MutTy; fn ty(&self, span: Span, ty: ast::TyKind) -> P; fn ty_path(&self, path: ast::Path) -> P; fn ty_ident(&self, span: Span, idents: ast::Ident) -> P; + fn anon_const(&self, span: Span, expr: ast::ExprKind) -> ast::AnonConst; + fn const_ident(&self, span: Span, idents: ast::Ident) -> ast::AnonConst; fn ty_rptr(&self, span: Span, ty: P, @@ -394,6 +396,22 @@ fn ty_ident(&self, span: Span, ident: ast::Ident) self.ty_path(self.path_ident(span, ident)) } + fn anon_const(&self, span: Span, expr: ast::ExprKind) -> ast::AnonConst { + ast::AnonConst { + id: ast::DUMMY_NODE_ID, + value: P(ast::Expr { + id: ast::DUMMY_NODE_ID, + node: expr, + span, + attrs: ThinVec::new(), + }) + } + } + + fn const_ident(&self, span: Span, ident: ast::Ident) -> ast::AnonConst { + self.anon_const(span, ast::ExprKind::Path(None, self.path_ident(span, ident))) + } + fn ty_rptr(&self, span: Span, ty: P, diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index b3ecaeaedbb..33ea675f9d1 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -17,10 +17,10 @@ use crate::symbol::Symbol; use crate::tokenstream::{DelimSpan, TokenStream, TokenTree}; -use syntax_pos::{Span, DUMMY_SP}; +use syntax_pos::{Span, DUMMY_SP, symbol::Ident}; use log::debug; -use rustc_data_structures::fx::FxHashMap; +use rustc_data_structures::fx::{FxHashMap}; use std::borrow::Cow; use std::collections::hash_map::Entry; @@ -246,8 +246,12 @@ fn generic_extension<'cx>(cx: &'cx mut ExtCtxt<'_>, // Holy self-referential! /// Converts a `macro_rules!` invocation into a syntax extension. -pub fn compile(sess: &ParseSess, features: &Features, def: &ast::Item, edition: Edition) - -> SyntaxExtension { +pub fn compile( + sess: &ParseSess, + features: &Features, + def: &ast::Item, + edition: Edition +) -> SyntaxExtension { let lhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("lhs")); let rhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("rhs")); @@ -355,7 +359,13 @@ pub fn compile(sess: &ParseSess, features: &Features, def: &ast::Item, edition: // don't abort iteration early, so that errors for multiple lhses can be reported for lhs in &lhses { - valid &= check_lhs_no_empty_seq(sess, &[lhs.clone()]) + valid &= check_lhs_no_empty_seq(sess, &[lhs.clone()]); + valid &= check_lhs_duplicate_matcher_bindings( + sess, + &[lhs.clone()], + &mut FxHashMap::default(), + def.id + ); } let expander: Box<_> = Box::new(MacroRulesMacroExpander { @@ -456,6 +466,53 @@ fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[quoted::TokenTree]) -> bool { true } +/// Check that the LHS contains no duplicate matcher bindings. e.g. `$a:expr, $a:expr` would be +/// illegal, since it would be ambiguous which `$a` to use if we ever needed to. +fn check_lhs_duplicate_matcher_bindings( + sess: &ParseSess, + tts: &[quoted::TokenTree], + metavar_names: &mut FxHashMap, + node_id: ast::NodeId, +) -> bool { + use self::quoted::TokenTree; + use crate::early_buffered_lints::BufferedEarlyLintId; + for tt in tts { + match *tt { + TokenTree::MetaVarDecl(span, name, _kind) => { + if let Some(&prev_span) = metavar_names.get(&name) { + // FIXME(mark-i-m): in a few cycles, make this a hard error. + // sess.span_diagnostic + // .struct_span_err(span, "duplicate matcher binding") + // .span_note(prev_span, "previous declaration was here") + // .emit(); + sess.buffer_lint( + BufferedEarlyLintId::DuplicateMacroMatcherBindingName, + crate::source_map::MultiSpan::from(vec![prev_span, span]), + node_id, + "duplicate matcher binding" + ); + return false; + } else { + metavar_names.insert(name, span); + } + } + TokenTree::Delimited(_, ref del) => { + if !check_lhs_duplicate_matcher_bindings(sess, &del.tts, metavar_names, node_id) { + return false; + } + }, + TokenTree::Sequence(_, ref seq) => { + if !check_lhs_duplicate_matcher_bindings(sess, &seq.tts, metavar_names, node_id) { + return false; + } + } + _ => {} + } + } + + true +} + fn check_rhs(sess: &ParseSess, rhs: "ed::TokenTree) -> bool { match *rhs { quoted::TokenTree::Delimited(..) => return true, diff --git a/src/libsyntax/feature_gate.rs b/src/libsyntax/feature_gate.rs index e7b9a884b5e..0853b4399d2 100644 --- a/src/libsyntax/feature_gate.rs +++ b/src/libsyntax/feature_gate.rs @@ -15,7 +15,7 @@ use AttributeType::*; use AttributeGate::*; -use crate::ast::{self, NodeId, PatKind, RangeEnd}; +use crate::ast::{self, NodeId, GenericParam, GenericParamKind, PatKind, RangeEnd}; use crate::attr; use crate::early_buffered_lints::BufferedEarlyLintId; use crate::source_map::Spanned; @@ -462,6 +462,9 @@ pub fn walk_feature_fields(&self, mut f: F) // Re-Rebalance coherence (active, re_rebalance_coherence, "1.32.0", Some(55437), None), + // Const generic types. + (active, const_generics, "1.34.0", Some(44580), None), + // #[optimize(X)] (active, optimize_attribute, "1.34.0", Some(54882), None), @@ -1899,6 +1902,14 @@ fn visit_fn(&mut self, visit::walk_fn(self, fn_kind, fn_decl, span); } + fn visit_generic_param(&mut self, param: &'a GenericParam) { + if let GenericParamKind::Const { .. } = param.kind { + gate_feature_post!(&self, const_generics, param.ident.span, + "const generics are unstable"); + } + visit::walk_generic_param(self, param); + } + fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) { match ti.node { ast::TraitItemKind::Method(ref sig, ref block) => { @@ -1984,7 +1995,7 @@ fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) { // Some features are known to be incomplete and using them is likely to have // unanticipated results, such as compiler crashes. We warn the user about these // to alert them. - let incomplete_features = ["generic_associated_types"]; + let incomplete_features = ["generic_associated_types", "const_generics"]; let mut features = Features::new(); let mut edition_enabled_features = FxHashMap::default(); diff --git a/src/libsyntax/mut_visit.rs b/src/libsyntax/mut_visit.rs index 0fd8bbf100f..1e5eb0992bd 100644 --- a/src/libsyntax/mut_visit.rs +++ b/src/libsyntax/mut_visit.rs @@ -480,6 +480,7 @@ pub fn noop_visit_generic_arg(arg: &mut GenericArg, vis: &mut T) match arg { GenericArg::Lifetime(lt) => vis.visit_lifetime(lt), GenericArg::Type(ty) => vis.visit_ty(ty), + GenericArg::Const(ct) => vis.visit_anon_const(ct), } } @@ -698,6 +699,9 @@ pub fn noop_visit_generic_param(param: &mut GenericParam, vis: &m GenericParamKind::Type { default } => { visit_opt(default, |default| vis.visit_ty(default)); } + GenericParamKind::Const { ty } => { + vis.visit_ty(ty); + } } } diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index 2e3233c8ed8..d3fc1c03634 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -33,6 +33,15 @@ fn default() -> Self { } } +#[derive(Clone, Debug)] +pub struct UnmatchedBrace { + pub expected_delim: token::DelimToken, + pub found_delim: token::DelimToken, + pub found_span: Span, + pub unclosed_span: Option, + pub candidate_span: Option, +} + pub struct StringReader<'a> { pub sess: &'a ParseSess, /// The absolute offset within the source_map of the next character to read @@ -58,6 +67,7 @@ pub struct StringReader<'a> { span_src_raw: Span, /// Stack of open delimiters and their spans. Used for error message. open_braces: Vec<(token::DelimToken, Span)>, + crate unmatched_braces: Vec, /// The type and spans for all braces /// /// Used only for error recovery when arriving to EOF with mismatched braces. @@ -222,6 +232,7 @@ fn new_raw_internal(sess: &'a ParseSess, source_file: Lrc PResult<'a, TreeAndJoint> { } // Incorrect delimiter. token::CloseDelim(other) => { - let token_str = token_to_string(&self.token); + let mut unclosed_delimiter = None; + let mut candidate = None; if self.last_unclosed_found_span != Some(self.span) { // do not complain about the same unclosed delimiter multiple times self.last_unclosed_found_span = Some(self.span); - let msg = format!("incorrect close delimiter: `{}`", token_str); - let mut err = self.sess.span_diagnostic.struct_span_err( - self.span, - &msg, - ); - err.span_label(self.span, "incorrect close delimiter"); // This is a conservative error: only report the last unclosed // delimiter. The previous unclosed delimiters could actually be // closed! The parser just hasn't gotten to them yet. if let Some(&(_, sp)) = self.open_braces.last() { - err.span_label(sp, "un-closed delimiter"); + unclosed_delimiter = Some(sp); }; if let Some(current_padding) = sm.span_to_margin(self.span) { for (brace, brace_span) in &self.open_braces { if let Some(padding) = sm.span_to_margin(*brace_span) { // high likelihood of these two corresponding if current_padding == padding && brace == &other { - err.span_label( - *brace_span, - "close delimiter possibly meant for this", - ); + candidate = Some(*brace_span); } } } } - err.emit(); + let (tok, _) = self.open_braces.pop().unwrap(); + self.unmatched_braces.push(UnmatchedBrace { + expected_delim: tok, + found_delim: other, + found_span: self.span, + unclosed_span: unclosed_delimiter, + candidate_span: candidate, + }); + } else { + self.open_braces.pop(); } - self.open_braces.pop().unwrap(); // If the incorrect delimiter matches an earlier opening // delimiter, then don't consume it (it can be used to diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index c723d591f2f..317d6933207 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -9,6 +9,7 @@ use crate::symbol::Symbol; use crate::tokenstream::{TokenStream, TokenTree}; use crate::diagnostics::plugin::ErrorMap; +use crate::print::pprust::token_to_string; use rustc_data_structures::sync::{Lrc, Lock}; use syntax_pos::{Span, SourceFile, FileName, MultiSpan}; @@ -136,15 +137,17 @@ pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: & new_parser_from_source_str(sess, name, source).parse_inner_attributes() } -pub fn parse_stream_from_source_str(name: FileName, source: String, sess: &ParseSess, - override_span: Option) - -> TokenStream { +pub fn parse_stream_from_source_str( + name: FileName, + source: String, + sess: &ParseSess, + override_span: Option, +) -> (TokenStream, Vec) { source_file_to_stream(sess, sess.source_map().new_source_file(name, source), override_span) } /// Create a new parser from a source string -pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) - -> Parser<'_> { +pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> { panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source)) } @@ -195,12 +198,14 @@ fn source_file_to_parser(sess: &ParseSess, source_file: Lrc) -> Pars /// Given a source_file and config, return a parser. Returns any buffered errors from lexing the /// initial token stream. -fn maybe_source_file_to_parser(sess: &ParseSess, source_file: Lrc) - -> Result, Vec> -{ +fn maybe_source_file_to_parser( + sess: &ParseSess, + source_file: Lrc, +) -> Result, Vec> { let end_pos = source_file.end_pos; - let mut parser = stream_to_parser(sess, maybe_file_to_stream(sess, source_file, None)?); - + let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?; + let mut parser = stream_to_parser(sess, stream); + parser.unclosed_delims = unclosed_delims; if parser.token == token::Eof && parser.span.is_dummy() { parser.span = Span::new(end_pos, end_pos, parser.span.ctxt()); } @@ -247,25 +252,44 @@ fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option) } /// Given a source_file, produce a sequence of token-trees -pub fn source_file_to_stream(sess: &ParseSess, - source_file: Lrc, - override_span: Option) -> TokenStream { +pub fn source_file_to_stream( + sess: &ParseSess, + source_file: Lrc, + override_span: Option, +) -> (TokenStream, Vec) { panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span)) } /// Given a source file, produce a sequence of token-trees. Returns any buffered errors from /// parsing the token tream. -pub fn maybe_file_to_stream(sess: &ParseSess, - source_file: Lrc, - override_span: Option) -> Result> { +pub fn maybe_file_to_stream( + sess: &ParseSess, + source_file: Lrc, + override_span: Option, +) -> Result<(TokenStream, Vec), Vec> { let mut srdr = lexer::StringReader::new_or_buffered_errs(sess, source_file, override_span)?; srdr.real_token(); match srdr.parse_all_token_trees() { - Ok(stream) => Ok(stream), + Ok(stream) => Ok((stream, srdr.unmatched_braces)), Err(err) => { let mut buffer = Vec::with_capacity(1); err.buffer(&mut buffer); + // Not using `emit_unclosed_delims` to use `db.buffer` + for unmatched in srdr.unmatched_braces { + let mut db = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!( + "incorrect close delimiter: `{}`", + token_to_string(&token::Token::CloseDelim(unmatched.found_delim)), + )); + db.span_label(unmatched.found_span, "incorrect close delimiter"); + if let Some(sp) = unmatched.candidate_span { + db.span_label(sp, "close delimiter possibly meant for this"); + } + if let Some(sp) = unmatched.unclosed_span { + db.span_label(sp, "un-closed delimiter"); + } + db.buffer(&mut buffer); + } Err(buffer) } } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index cacdab980fa..69d6407d506 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -35,7 +35,7 @@ use crate::source_map::{self, SourceMap, Spanned, respan}; use crate::errors::{self, Applicability, DiagnosticBuilder, DiagnosticId}; use crate::parse::{self, SeqSep, classify, token}; -use crate::parse::lexer::TokenAndSpan; +use crate::parse::lexer::{TokenAndSpan, UnmatchedBrace}; use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration}; use crate::parse::token::DelimToken; use crate::parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership}; @@ -251,6 +251,11 @@ pub struct Parser<'a> { /// /// See the comments in the `parse_path_segment` function for more details. crate unmatched_angle_bracket_count: u32, + crate max_angle_bracket_count: u32, + /// List of all unclosed delimiters found by the lexer. If an entry is used for error recovery + /// it gets removed from here. Every entry left at the end gets emitted as an independent + /// error. + crate unclosed_delims: Vec, } @@ -397,6 +402,7 @@ fn next_desugared(&mut self) -> TokenAndSpan { Ident, Path, Type, + Const, } impl TokenType { @@ -409,6 +415,7 @@ fn to_string(&self) -> String { TokenType::Ident => "identifier".to_string(), TokenType::Path => "path".to_string(), TokenType::Type => "type".to_string(), + TokenType::Const => "const".to_string(), } } } @@ -573,6 +580,8 @@ pub fn new(sess: &'a ParseSess, desugar_doc_comments, cfg_mods: true, unmatched_angle_bracket_count: 0, + max_angle_bracket_count: 0, + unclosed_delims: Vec::new(), }; let tok = parser.next_tok(); @@ -642,11 +651,11 @@ fn unexpected_last(&self, t: &token::Token) -> PResult<'a, T> { /// Expect and consume the token t. Signal an error if /// the next token is not t. - pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> { + pub fn expect(&mut self, t: &token::Token) -> PResult<'a, bool /* recovered */> { if self.expected_tokens.is_empty() { if self.token == *t { self.bump(); - Ok(()) + Ok(false) } else { let token_str = pprust::token_to_string(t); let this_token_str = self.this_token_descr(); @@ -661,6 +670,12 @@ pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> { self.sess.source_map().next_point(self.prev_span) }; let label_exp = format!("expected `{}`", token_str); + match self.recover_closing_delimiter(&[t.clone()], err) { + Err(e) => err = e, + Ok(recovered) => { + return Ok(recovered); + } + } let cm = self.sess.source_map(); match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) { (Ok(ref a), Ok(ref b)) if a.line == b.line => { @@ -680,12 +695,64 @@ pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> { } } + fn recover_closing_delimiter( + &mut self, + tokens: &[token::Token], + mut err: DiagnosticBuilder<'a>, + ) -> PResult<'a, bool> { + let mut pos = None; + // we want to use the last closing delim that would apply + for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() { + if tokens.contains(&token::CloseDelim(unmatched.expected_delim)) + && Some(self.span) > unmatched.unclosed_span + { + pos = Some(i); + } + } + match pos { + Some(pos) => { + // Recover and assume that the detected unclosed delimiter was meant for + // this location. Emit the diagnostic and act as if the delimiter was + // present for the parser's sake. + + // Don't attempt to recover from this unclosed delimiter more than once. + let unmatched = self.unclosed_delims.remove(pos); + let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim)); + + // We want to suggest the inclusion of the closing delimiter where it makes + // the most sense, which is immediately after the last token: + // + // {foo(bar {}} + // - ^ + // | | + // | help: `)` may belong here (FIXME: #58270) + // | + // unclosed delimiter + if let Some(sp) = unmatched.unclosed_span { + err.span_label(sp, "unclosed delimiter"); + } + err.span_suggestion_short( + self.sess.source_map().next_point(self.prev_span), + &format!("{} may belong here", delim.to_string()), + delim.to_string(), + Applicability::MaybeIncorrect, + ); + err.emit(); + self.expected_tokens.clear(); // reduce errors + Ok(true) + } + _ => Err(err), + } + } + /// Expect next token to be edible or inedible token. If edible, /// then consume it; if inedible, then return without consuming /// anything. Signal a fatal error if next token is unexpected. - pub fn expect_one_of(&mut self, - edible: &[token::Token], - inedible: &[token::Token]) -> PResult<'a, ()>{ + pub fn expect_one_of( + &mut self, + edible: &[token::Token], + inedible: &[token::Token], + ) -> PResult<'a, bool /* recovered */> { fn tokens_to_string(tokens: &[TokenType]) -> String { let mut i = tokens.iter(); // This might be a sign we need a connect method on Iterator. @@ -705,10 +772,10 @@ fn tokens_to_string(tokens: &[TokenType]) -> String { } if edible.contains(&self.token) { self.bump(); - Ok(()) + Ok(false) } else if inedible.contains(&self.token) { // leave it in the input - Ok(()) + Ok(false) } else { let mut expected = edible.iter() .map(|x| TokenType::Token(x.clone())) @@ -759,6 +826,15 @@ fn tokens_to_string(tokens: &[TokenType]) -> String { } else { label_sp }; + match self.recover_closing_delimiter(&expected.iter().filter_map(|tt| match tt { + TokenType::Token(t) => Some(t.clone()), + _ => None, + }).collect::>(), err) { + Err(e) => err = e, + Ok(recovered) => { + return Ok(recovered); + } + } let cm = self.sess.source_map(); match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) { @@ -946,6 +1022,15 @@ fn check_type(&mut self) -> bool { } } + fn check_const_arg(&mut self) -> bool { + if self.token.can_begin_const_arg() { + true + } else { + self.expected_tokens.push(TokenType::Const); + false + } + } + /// Expect and consume a `+`. if `+=` is seen, replace it with a `=` /// and continue. If a `+` is not seen, return false. /// @@ -1031,7 +1116,8 @@ fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option) { } /// Attempt to consume a `<`. If `<<` is seen, replace it with a single - /// `<` and continue. If a `<` is not seen, return false. + /// `<` and continue. If `<-` is seen, replace it with a single `<` + /// and continue. If a `<` is not seen, return false. /// /// This is meant to be used when parsing generics on a path to get the /// starting token. @@ -1047,12 +1133,18 @@ fn eat_lt(&mut self) -> bool { self.bump_with(token::Lt, span); true } + token::LArrow => { + let span = self.span.with_lo(self.span.lo() + BytePos(1)); + self.bump_with(token::BinOp(token::Minus), span); + true + } _ => false, }; if ate { // See doc comment for `unmatched_angle_bracket_count`. self.unmatched_angle_bracket_count += 1; + self.max_angle_bracket_count += 1; debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count); } @@ -1093,12 +1185,12 @@ fn expect_gt(&mut self) -> PResult<'a, ()> { }; match ate { - Some(x) => { + Some(_) => { // See doc comment for `unmatched_angle_bracket_count`. self.unmatched_angle_bracket_count -= 1; debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count); - Ok(x) + Ok(()) }, None => self.unexpected(), } @@ -1127,19 +1219,22 @@ pub fn parse_seq_to_end(&mut self, -> PResult<'a, Vec> where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>, { - let val = self.parse_seq_to_before_end(ket, sep, f)?; - self.bump(); + let (val, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; + if !recovered { + self.bump(); + } Ok(val) } /// Parse a sequence, not including the closing delimiter. The function /// f must consume tokens until reaching the next separator or /// closing bracket. - pub fn parse_seq_to_before_end(&mut self, - ket: &token::Token, - sep: SeqSep, - f: F) - -> PResult<'a, Vec> + pub fn parse_seq_to_before_end( + &mut self, + ket: &token::Token, + sep: SeqSep, + f: F, + ) -> PResult<'a, (Vec, bool)> where F: FnMut(&mut Parser<'a>) -> PResult<'a, T> { self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f) @@ -1151,10 +1246,11 @@ fn parse_seq_to_before_tokens( sep: SeqSep, expect: TokenExpectType, mut f: F, - ) -> PResult<'a, Vec> + ) -> PResult<'a, (Vec, bool /* recovered */)> where F: FnMut(&mut Parser<'a>) -> PResult<'a, T> { - let mut first: bool = true; + let mut first = true; + let mut recovered = false; let mut v = vec![]; while !kets.iter().any(|k| { match expect { @@ -1170,23 +1266,30 @@ fn parse_seq_to_before_tokens( if first { first = false; } else { - if let Err(mut e) = self.expect(t) { - // Attempt to keep parsing if it was a similar separator - if let Some(ref tokens) = t.similar_tokens() { - if tokens.contains(&self.token) { - self.bump(); - } + match self.expect(t) { + Ok(false) => {} + Ok(true) => { + recovered = true; + break; } - e.emit(); - // Attempt to keep parsing if it was an omitted separator - match f(self) { - Ok(t) => { - v.push(t); - continue; - }, - Err(mut e) => { - e.cancel(); - break; + Err(mut e) => { + // Attempt to keep parsing if it was a similar separator + if let Some(ref tokens) = t.similar_tokens() { + if tokens.contains(&self.token) { + self.bump(); + } + } + e.emit(); + // Attempt to keep parsing if it was an omitted separator + match f(self) { + Ok(t) => { + v.push(t); + continue; + }, + Err(mut e) => { + e.cancel(); + break; + } } } } @@ -1205,23 +1308,26 @@ fn parse_seq_to_before_tokens( v.push(t); } - Ok(v) + Ok((v, recovered)) } /// Parse a sequence, including the closing delimiter. The function /// f must consume tokens until reaching the next separator or /// closing bracket. - fn parse_unspanned_seq(&mut self, - bra: &token::Token, - ket: &token::Token, - sep: SeqSep, - f: F) - -> PResult<'a, Vec> where + fn parse_unspanned_seq( + &mut self, + bra: &token::Token, + ket: &token::Token, + sep: SeqSep, + f: F, + ) -> PResult<'a, Vec> where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>, { self.expect(bra)?; - let result = self.parse_seq_to_before_end(ket, sep, f)?; - self.eat(ket); + let (result, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; + if !recovered { + self.eat(ket); + } Ok(result) } @@ -2273,7 +2379,10 @@ fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool) // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If // it isn't, then we reset the unmatched angle bracket count as we're about to start // parsing a new path. - if style == PathStyle::Expr { self.unmatched_angle_bracket_count = 0; } + if style == PathStyle::Expr { + self.unmatched_angle_bracket_count = 0; + self.max_angle_bracket_count = 0; + } let args = if self.eat_lt() { // `<'a, T, A = U>` @@ -2285,12 +2394,14 @@ fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool) } else { // `(T, U) -> R` self.bump(); // `(` - let inputs = self.parse_seq_to_before_tokens( + let (inputs, recovered) = self.parse_seq_to_before_tokens( &[&token::CloseDelim(token::Paren)], SeqSep::trailing_allowed(token::Comma), TokenExpectType::Expect, |p| p.parse_ty())?; - self.bump(); // `)` + if !recovered { + self.bump(); // `)` + } let span = lo.to(self.prev_span); let output = if self.eat(&token::RArrow) { Some(self.parse_ty_common(false, false)?) @@ -2496,9 +2607,13 @@ fn parse_bottom_expr(&mut self) -> PResult<'a, P> { // (e,) is a tuple with only one field, e let mut es = vec![]; let mut trailing_comma = false; + let mut recovered = false; while self.token != token::CloseDelim(token::Paren) { es.push(self.parse_expr()?); - self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?; + recovered = self.expect_one_of( + &[], + &[token::Comma, token::CloseDelim(token::Paren)], + )?; if self.eat(&token::Comma) { trailing_comma = true; } else { @@ -2506,7 +2621,9 @@ fn parse_bottom_expr(&mut self) -> PResult<'a, P> { break; } } - self.bump(); + if !recovered { + self.bump(); + } hi = self.prev_span; ex = if es.len() == 1 && !trailing_comma { @@ -2703,6 +2820,21 @@ fn parse_bottom_expr(&mut self) -> PResult<'a, P> { hi = pth.span; ex = ExprKind::Path(None, pth); } else { + if !self.unclosed_delims.is_empty() && self.check(&token::Semi) { + // Don't complain about bare semicolons after unclosed braces + // recovery in order to keep the error count down. Fixing the + // delimiters will possibly also fix the bare semicolon found in + // expression context. For example, silence the following error: + // ``` + // error: expected expression, found `;` + // --> file.rs:2:13 + // | + // 2 | foo(bar(; + // | ^ expected expression + // ``` + self.bump(); + return Ok(self.mk_expr(self.span, ExprKind::Err, ThinVec::new())); + } match self.parse_literal_maybe_minus() { Ok(expr) => { hi = expr.span; @@ -2802,7 +2934,7 @@ fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec if let Some(f) = parsed_field.or(recovery_field) { + Ok(_) => if let Some(f) = parsed_field.or(recovery_field) { // only include the field if there's no parse error for the field name fields.push(f); } @@ -5482,15 +5614,27 @@ fn parse_trait_item_assoc_ty(&mut self) Ok((ident, TraitItemKind::Type(bounds, default), generics)) } + fn parse_const_param(&mut self, preceding_attrs: Vec) -> PResult<'a, GenericParam> { + self.expect_keyword(keywords::Const)?; + let ident = self.parse_ident()?; + self.expect(&token::Colon)?; + let ty = self.parse_ty()?; + + Ok(GenericParam { + ident, + id: ast::DUMMY_NODE_ID, + attrs: preceding_attrs.into(), + bounds: Vec::new(), + kind: GenericParamKind::Const { + ty, + } + }) + } + /// Parses (possibly empty) list of lifetime and type parameters, possibly including /// trailing comma and erroneous trailing attributes. crate fn parse_generic_params(&mut self) -> PResult<'a, Vec> { - let mut lifetimes = Vec::new(); let mut params = Vec::new(); - let mut seen_ty_param: Option = None; - let mut last_comma_span = None; - let mut bad_lifetime_pos = vec![]; - let mut suggestions = vec![]; loop { let attrs = self.parse_outer_attributes()?; if self.check_lifetime() { @@ -5501,39 +5645,40 @@ fn parse_trait_item_assoc_ty(&mut self) } else { Vec::new() }; - lifetimes.push(ast::GenericParam { + params.push(ast::GenericParam { ident: lifetime.ident, id: lifetime.id, attrs: attrs.into(), bounds, kind: ast::GenericParamKind::Lifetime, }); - if let Some(sp) = seen_ty_param { - let remove_sp = last_comma_span.unwrap_or(self.prev_span).to(self.prev_span); - bad_lifetime_pos.push(self.prev_span); - if let Ok(snippet) = self.sess.source_map().span_to_snippet(self.prev_span) { - suggestions.push((remove_sp, String::new())); - suggestions.push(( - sp.shrink_to_lo(), - format!("{}, ", snippet))); - } - } + } else if self.check_keyword(keywords::Const) { + // Parse const parameter. + params.push(self.parse_const_param(attrs)?); } else if self.check_ident() { // Parse type parameter. params.push(self.parse_ty_param(attrs)?); - if seen_ty_param.is_none() { - seen_ty_param = Some(self.prev_span); - } } else { // Check for trailing attributes and stop parsing. if !attrs.is_empty() { - let param_kind = if seen_ty_param.is_some() { "type" } else { "lifetime" }; - self.struct_span_err( - attrs[0].span, - &format!("trailing attribute after {} parameters", param_kind), - ) - .span_label(attrs[0].span, "attributes must go before parameters") - .emit(); + if !params.is_empty() { + self.struct_span_err( + attrs[0].span, + &format!("trailing attribute after generic parameter"), + ) + .span_label(attrs[0].span, "attributes must go before parameters") + .emit(); + } else { + self.struct_span_err( + attrs[0].span, + &format!("attribute without generic parameters"), + ) + .span_label( + attrs[0].span, + "attributes are only permitted when preceding parameters", + ) + .emit(); + } } break } @@ -5541,24 +5686,8 @@ fn parse_trait_item_assoc_ty(&mut self) if !self.eat(&token::Comma) { break } - last_comma_span = Some(self.prev_span); - } - if !bad_lifetime_pos.is_empty() { - let mut err = self.struct_span_err( - bad_lifetime_pos, - "lifetime parameters must be declared prior to type parameters", - ); - if !suggestions.is_empty() { - err.multipart_suggestion( - "move the lifetime parameter prior to the first type parameter", - suggestions, - Applicability::MachineApplicable, - ); - } - err.emit(); } - lifetimes.extend(params); // ensure the correct order of lifetimes and type params - Ok(lifetimes) + Ok(params) } /// Parse a set of optional generic type parameter declarations. Where @@ -5740,35 +5869,16 @@ fn parse_generic_args_with_leaning_angle_bracket_recovery( fn parse_generic_args(&mut self) -> PResult<'a, (Vec, Vec)> { let mut args = Vec::new(); let mut bindings = Vec::new(); + let mut misplaced_assoc_ty_bindings: Vec = Vec::new(); + let mut assoc_ty_bindings: Vec = Vec::new(); - let mut seen_type = false; - let mut seen_binding = false; - - let mut last_comma_span = None; - let mut first_type_or_binding_span: Option = None; - let mut first_binding_span: Option = None; - - let mut bad_lifetime_pos = vec![]; - let mut bad_type_pos = vec![]; + let args_lo = self.span; - let mut lifetime_suggestions = vec![]; - let mut type_suggestions = vec![]; loop { if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) { // Parse lifetime argument. args.push(GenericArg::Lifetime(self.expect_lifetime())); - - if seen_type || seen_binding { - let remove_sp = last_comma_span.unwrap_or(self.prev_span).to(self.prev_span); - bad_lifetime_pos.push(self.prev_span); - - if let Ok(snippet) = self.sess.source_map().span_to_snippet(self.prev_span) { - lifetime_suggestions.push((remove_sp, String::new())); - lifetime_suggestions.push(( - first_type_or_binding_span.unwrap().shrink_to_lo(), - format!("{}, ", snippet))); - } - } + misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings); } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) { // Parse associated type binding. let lo = self.span; @@ -5782,131 +5892,64 @@ fn parse_generic_args(&mut self) -> PResult<'a, (Vec, Vec, - bad_type_pos: Vec, - lifetime_suggestions: Vec<(Span, String)>, - type_suggestions: Vec<(Span, String)>, - ) { - let mut err = if !bad_lifetime_pos.is_empty() && !bad_type_pos.is_empty() { - let mut positions = bad_lifetime_pos.clone(); - positions.extend_from_slice(&bad_type_pos); - - self.struct_span_err( - positions, - "generic arguments must declare lifetimes, types and associated type bindings in \ - that order", - ) - } else if !bad_lifetime_pos.is_empty() { - self.struct_span_err( - bad_lifetime_pos.clone(), - "lifetime parameters must be declared prior to type parameters" - ) - } else if !bad_type_pos.is_empty() { - self.struct_span_err( - bad_type_pos.clone(), - "type parameters must be declared prior to associated type bindings" - ) - } else { - return; - }; - - if !bad_lifetime_pos.is_empty() { - for sp in &bad_lifetime_pos { - err.span_label(*sp, "must be declared prior to type parameters"); } } - if !bad_type_pos.is_empty() { - for sp in &bad_type_pos { - err.span_label(*sp, "must be declared prior to associated type bindings"); - } - } - - if !lifetime_suggestions.is_empty() && !type_suggestions.is_empty() { - let mut suggestions = lifetime_suggestions; - suggestions.extend_from_slice(&type_suggestions); - - let plural = bad_lifetime_pos.len() + bad_type_pos.len() > 1; - err.multipart_suggestion( - &format!( - "move the parameter{}", - if plural { "s" } else { "" }, - ), - suggestions, - Applicability::MachineApplicable, - ); - } else if !lifetime_suggestions.is_empty() { - err.multipart_suggestion( - &format!( - "move the lifetime parameter{} prior to the first type parameter", - if bad_lifetime_pos.len() > 1 { "s" } else { "" }, - ), - lifetime_suggestions, - Applicability::MachineApplicable, - ); - } else if !type_suggestions.is_empty() { - err.multipart_suggestion( - &format!( - "move the type parameter{} prior to the first associated type binding", - if bad_type_pos.len() > 1 { "s" } else { "" }, - ), - type_suggestions, - Applicability::MachineApplicable, + // FIXME: we would like to report this in ast_validation instead, but we currently do not + // preserve ordering of generic parameters with respect to associated type binding, so we + // lose that information after parsing. + if misplaced_assoc_ty_bindings.len() > 0 { + let mut err = self.struct_span_err( + args_lo.to(self.prev_span), + "associated type bindings must be declared after generic parameters", ); + for span in misplaced_assoc_ty_bindings { + err.span_label( + span, + "this associated type binding should be moved after the generic parameters", + ); + } + err.emit(); } - err.emit(); + Ok((args, bindings)) } /// Parses an optional `where` clause and places it in `generics`. @@ -6011,7 +6054,7 @@ fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool) let sp = self.span; let mut variadic = false; - let args: Vec> = + let (args, recovered): (Vec>, bool) = self.parse_seq_to_before_end( &token::CloseDelim(token::Paren), SeqSep::trailing_allowed(token::Comma), @@ -6059,7 +6102,9 @@ fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool) } )?; - self.eat(&token::CloseDelim(token::Paren)); + if !recovered { + self.eat(&token::CloseDelim(token::Paren)); + } let args: Vec<_> = args.into_iter().filter_map(|x| x).collect(); @@ -6204,15 +6249,15 @@ fn parse_fn_decl_with_self(&mut self, parse_arg_fn: F) -> PResult<'a, P(&mut self, parse_arg_fn: F) -> PResult<'a, P PResult<'a, P> { SeqSep::trailing_allowed(token::Comma), TokenExpectType::NoExpect, |p| p.parse_fn_block_arg() - )?; + )?.0; self.expect_or()?; args } @@ -6526,6 +6573,7 @@ fn choose_generics_over_qpath(&self) -> bool { // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds // `<` (LIFETIME|IDENT) `=` - generic parameter with a default + // `<` const - generic const parameter // The only truly ambiguous case is // `<` IDENT `>` `::` IDENT ... // we disambiguate it in favor of generics (`impl ::absolute::Path { ... }`) @@ -6535,7 +6583,8 @@ fn choose_generics_over_qpath(&self) -> bool { (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) || self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) && self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma || - t == &token::Colon || t == &token::Eq)) + t == &token::Colon || t == &token::Eq) || + self.look_ahead(1, |t| t.is_keyword(keywords::Const))) } fn parse_impl_body(&mut self) -> PResult<'a, (Vec, Vec)> { @@ -8238,7 +8287,7 @@ fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>, // eat a matched-delimiter token tree: let (delim, tts) = self.expect_delimited_token_tree()?; if delim != MacDelimiter::Brace { - self.expect(&token::Semi)? + self.expect(&token::Semi)?; } Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim }))) @@ -8383,11 +8432,14 @@ fn parse_rename(&mut self) -> PResult<'a, Option> { /// entry point for the parser. pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> { let lo = self.span; - Ok(ast::Crate { + let krate = Ok(ast::Crate { attrs: self.parse_inner_attributes()?, module: self.parse_mod_items(&token::Eof, lo)?, span: lo.to(self.span), - }) + }); + emit_unclosed_delims(&self.unclosed_delims, self.diagnostic()); + self.unclosed_delims.clear(); + krate } pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option)> { @@ -8416,3 +8468,20 @@ pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> { } } } + +pub fn emit_unclosed_delims(unclosed_delims: &[UnmatchedBrace], handler: &errors::Handler) { + for unmatched in unclosed_delims { + let mut err = handler.struct_span_err(unmatched.found_span, &format!( + "incorrect close delimiter: `{}`", + pprust::token_to_string(&token::Token::CloseDelim(unmatched.found_delim)), + )); + err.span_label(unmatched.found_span, "incorrect close delimiter"); + if let Some(sp) = unmatched.candidate_span { + err.span_label(sp, "close delimiter possibly meant for this"); + } + if let Some(sp) = unmatched.unclosed_span { + err.span_label(sp, "un-closed delimiter"); + } + err.emit(); + } +} diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index 3b1fa5ea01f..09924e304cf 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -10,6 +10,7 @@ use crate::ptr::P; use crate::symbol::keywords; use crate::syntax::parse::parse_stream_from_source_str; +use crate::syntax::parse::parser::emit_unclosed_delims; use crate::tokenstream::{self, DelimSpan, TokenStream, TokenTree}; use serialize::{Decodable, Decoder, Encodable, Encoder}; @@ -279,6 +280,20 @@ pub fn from_ast_ident(ident: ast::Ident) -> Token { } } + /// Returns `true` if the token can appear at the start of a const param. + pub fn can_begin_const_arg(&self) -> bool { + match self { + OpenDelim(Brace) => true, + Interpolated(ref nt) => match nt.0 { + NtExpr(..) => true, + NtBlock(..) => true, + NtLiteral(..) => true, + _ => false, + } + _ => self.can_begin_literal_or_bool(), + } + } + /// Returns `true` if the token can appear at the start of a generic bound. crate fn can_begin_bound(&self) -> bool { self.is_path_start() || self.is_lifetime() || self.is_keyword(keywords::For) || @@ -293,7 +308,7 @@ pub fn from_ast_ident(ident: ast::Ident) -> Token { } } - /// Returns `true` if the token is any literal, a minus (which can follow a literal, + /// Returns `true` if the token is any literal, a minus (which can prefix a literal, /// for example a '-42', or one of the boolean idents). crate fn can_begin_literal_or_bool(&self) -> bool { match *self { @@ -487,8 +502,8 @@ pub fn is_reserved_ident(&self) -> bool { /// Enables better error recovery when the wrong token is found. crate fn similar_tokens(&self) -> Option> { match *self { - Comma => Some(vec![Dot, Lt]), - Semi => Some(vec![Colon]), + Comma => Some(vec![Dot, Lt, Semi]), + Semi => Some(vec![Colon, Comma]), _ => None } } @@ -545,7 +560,10 @@ pub fn interpolated_to_tokenstream(&self, sess: &ParseSess, span: Span) // FIXME(#43081): Avoid this pretty-print + reparse hack let source = pprust::token_to_string(self); let filename = FileName::macro_expansion_source_code(&source); - parse_stream_from_source_str(filename, source, sess, Some(span)) + let (tokens, errors) = parse_stream_from_source_str( + filename, source, sess, Some(span)); + emit_unclosed_delims(&errors, &sess.span_diagnostic); + tokens }); // During early phases of the compiler the AST could get modified @@ -786,12 +804,13 @@ fn prepend_attrs(sess: &ParseSess, let source = pprust::attr_to_string(attr); let macro_filename = FileName::macro_expansion_source_code(&source); if attr.is_sugared_doc { - let stream = parse_stream_from_source_str( + let (stream, errors) = parse_stream_from_source_str( macro_filename, source, sess, Some(span), ); + emit_unclosed_delims(&errors, &sess.span_diagnostic); builder.push(stream); continue } @@ -808,12 +827,13 @@ fn prepend_attrs(sess: &ParseSess, // ... and for more complicated paths, fall back to a reparse hack that // should eventually be removed. } else { - let stream = parse_stream_from_source_str( + let (stream, errors) = parse_stream_from_source_str( macro_filename, source, sess, Some(span), ); + emit_unclosed_delims(&errors, &sess.span_diagnostic); brackets.push(stream); } diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index c7c4c4f1620..c670f47b597 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -1025,6 +1025,7 @@ pub fn print_generic_arg(&mut self, generic_arg: &GenericArg) -> io::Result<()> match generic_arg { GenericArg::Lifetime(lt) => self.print_lifetime(*lt), GenericArg::Type(ty) => self.print_type(ty), + GenericArg::Const(ct) => self.print_expr(&ct.value), } } @@ -2929,7 +2930,7 @@ pub fn print_generic_params( s.print_outer_attributes_inline(¶m.attrs)?; let lt = ast::Lifetime { id: param.id, ident: param.ident }; s.print_lifetime_bounds(lt, ¶m.bounds) - }, + } ast::GenericParamKind::Type { ref default } => { s.print_outer_attributes_inline(¶m.attrs)?; s.print_ident(param.ident)?; @@ -2943,6 +2944,15 @@ pub fn print_generic_params( _ => Ok(()) } } + ast::GenericParamKind::Const { ref ty } => { + s.print_outer_attributes_inline(¶m.attrs)?; + s.word_space("const")?; + s.print_ident(param.ident)?; + s.s.space()?; + s.word_space(":")?; + s.print_type(ty)?; + s.print_type_bounds(":", ¶m.bounds) + } } })?; diff --git a/src/libsyntax/util/parser_testing.rs b/src/libsyntax/util/parser_testing.rs index dbe2b8d39f2..bcf1da66c04 100644 --- a/src/libsyntax/util/parser_testing.rs +++ b/src/libsyntax/util/parser_testing.rs @@ -12,8 +12,11 @@ /// Map a string to tts, using a made-up filename: pub fn string_to_stream(source_str: String) -> TokenStream { let ps = ParseSess::new(FilePathMapping::empty()); - source_file_to_stream(&ps, ps.source_map() - .new_source_file(PathBuf::from("bogofile").into(), source_str), None) + source_file_to_stream( + &ps, + ps.source_map().new_source_file(PathBuf::from("bogofile").into(), + source_str, + ), None).0 } /// Map string to parser (via tts) diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index acbb58a66b6..bb3b0ea7359 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -126,6 +126,7 @@ fn visit_generic_arg(&mut self, generic_arg: &'ast GenericArg) { match generic_arg { GenericArg::Lifetime(lt) => self.visit_lifetime(lt), GenericArg::Type(ty) => self.visit_ty(ty), + GenericArg::Const(ct) => self.visit_anon_const(ct), } } fn visit_assoc_type_binding(&mut self, type_binding: &'ast TypeBinding) { @@ -486,6 +487,7 @@ pub fn walk_generic_param<'a, V: Visitor<'a>>(visitor: &mut V, param: &'a Generi match param.kind { GenericParamKind::Lifetime => {} GenericParamKind::Type { ref default } => walk_list!(visitor, visit_ty, default), + GenericParamKind::Const { ref ty, .. } => visitor.visit_ty(ty), } } diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs index e6fe125da9f..4678c752045 100644 --- a/src/libsyntax_ext/deriving/generic/mod.rs +++ b/src/libsyntax_ext/deriving/generic/mod.rs @@ -560,6 +560,7 @@ fn create_derived_impl(&self, cx.typaram(self.span, param.ident, vec![], bounds, None) } + GenericParamKind::Const { .. } => param.clone(), })); // and similarly for where clauses @@ -657,6 +658,9 @@ fn create_derived_impl(&self, GenericParamKind::Type { .. } => { GenericArg::Type(cx.ty_ident(self.span, param.ident)) } + GenericParamKind::Const { .. } => { + GenericArg::Const(cx.const_ident(self.span, param.ident)) + } }).collect(); // Create the type of `self`. diff --git a/src/libsyntax_ext/deriving/generic/ty.rs b/src/libsyntax_ext/deriving/generic/ty.rs index ea6e07922b2..100ec0057ee 100644 --- a/src/libsyntax_ext/deriving/generic/ty.rs +++ b/src/libsyntax_ext/deriving/generic/ty.rs @@ -94,7 +94,7 @@ pub fn to_path(&self, } } -/// A type. Supports pointers, Self, and literals +/// A type. Supports pointers, Self, and literals. #[derive(Clone)] pub enum Ty<'a> { Self_, @@ -107,6 +107,13 @@ pub enum Ty<'a> { Tuple(Vec>), } +/// A const expression. Supports literals and blocks. +#[derive(Clone, Eq, PartialEq)] +pub enum Const { + Literal, + Block, +} + pub fn borrowed_ptrty<'r>() -> PtrTy<'r> { Borrowed(None, ast::Mutability::Immutable) } @@ -180,6 +187,9 @@ pub fn to_path(&self, GenericParamKind::Type { .. } => { GenericArg::Type(cx.ty_ident(span, param.ident)) } + GenericParamKind::Const { .. } => { + GenericArg::Const(cx.const_ident(span, param.ident)) + } }).collect(); cx.path_all(span, false, vec![self_ty], params, vec![]) diff --git a/src/libsyntax_ext/proc_macro_server.rs b/src/libsyntax_ext/proc_macro_server.rs index 730262683c0..2158cfc089b 100644 --- a/src/libsyntax_ext/proc_macro_server.rs +++ b/src/libsyntax_ext/proc_macro_server.rs @@ -12,6 +12,7 @@ use syntax::ext::base::ExtCtxt; use syntax::parse::lexer::comments; use syntax::parse::{self, token, ParseSess}; +use syntax::parse::parser::emit_unclosed_delims; use syntax::tokenstream::{self, DelimSpan, IsJoint::*, TokenStream, TreeAndJoint}; use syntax_pos::hygiene::{SyntaxContext, Transparency}; use syntax_pos::symbol::{keywords, Symbol}; @@ -409,12 +410,14 @@ fn is_empty(&mut self, stream: &Self::TokenStream) -> bool { stream.is_empty() } fn from_str(&mut self, src: &str) -> Self::TokenStream { - parse::parse_stream_from_source_str( + let (tokens, errors) = parse::parse_stream_from_source_str( FileName::proc_macro_source_code(src.clone()), src.to_string(), self.sess, Some(self.call_site), - ) + ); + emit_unclosed_delims(&errors, &self.sess.span_diagnostic); + tokens } fn to_string(&mut self, stream: &Self::TokenStream) -> String { stream.to_string() diff --git a/src/test/run-pass/macros/macro-follow.rs b/src/test/run-pass/macros/macro-follow.rs index f90afce90ee..488339b025d 100644 --- a/src/test/run-pass/macros/macro-follow.rs +++ b/src/test/run-pass/macros/macro-follow.rs @@ -73,7 +73,7 @@ macro_rules! follow_block { ($b:block $t:ty) => {}; ($b:block $s:stmt) => {}; ($b:block $p:path) => {}; - ($b:block $b:block) => {}; + ($b:block $c:block) => {}; ($b:block $i:ident) => {}; ($b:block $t:tt) => {}; ($b:block $i:item) => {}; @@ -99,9 +99,9 @@ macro_rules! follow_ident { ($i:ident $s:stmt) => {}; ($i:ident $p:path) => {}; ($i:ident $b:block) => {}; - ($i:ident $i:ident) => {}; + ($i:ident $j:ident) => {}; ($i:ident $t:tt) => {}; - ($i:ident $i:item) => {}; + ($i:ident $j:item) => {}; ($i:ident $m:meta) => {}; } // FOLLOW(tt) = any token @@ -120,12 +120,12 @@ macro_rules! follow_tt { ($t:tt ident) => {}; ($t:tt $p:pat) => {}; ($t:tt $e:expr) => {}; - ($t:tt $t:ty) => {}; + ($t:tt $v:ty) => {}; ($t:tt $s:stmt) => {}; ($t:tt $p:path) => {}; ($t:tt $b:block) => {}; ($t:tt $i:ident) => {}; - ($t:tt $t:tt) => {}; + ($t:tt $v:tt) => {}; ($t:tt $i:item) => {}; ($t:tt $m:meta) => {}; } @@ -149,9 +149,9 @@ macro_rules! follow_item { ($i:item $s:stmt) => {}; ($i:item $p:path) => {}; ($i:item $b:block) => {}; - ($i:item $i:ident) => {}; + ($i:item $j:ident) => {}; ($i:item $t:tt) => {}; - ($i:item $i:item) => {}; + ($i:item $j:item) => {}; ($i:item $m:meta) => {}; } // FOLLOW(meta) = any token @@ -177,7 +177,7 @@ macro_rules! follow_meta { ($m:meta $i:ident) => {}; ($m:meta $t:tt) => {}; ($m:meta $i:item) => {}; - ($m:meta $m:meta) => {}; + ($m:meta $n:meta) => {}; } fn main() {} diff --git a/src/test/run-pass/methods/method-probe-no-guessing-dyn-trait.rs b/src/test/run-pass/methods/method-probe-no-guessing-dyn-trait.rs new file mode 100644 index 00000000000..8c8165a1004 --- /dev/null +++ b/src/test/run-pass/methods/method-probe-no-guessing-dyn-trait.rs @@ -0,0 +1,59 @@ +// Check that method matching does not make "guesses" depending on +// Deref impls that don't eventually end up being picked. + +use std::ops::Deref; + +// An impl with less derefs will get called over an impl with more derefs, +// so `(t: Foo<_>).my_fn()` will use ` as MyTrait1>::my_fn(t)`, +// and does *not* force the `_` to equal `()`, because the Deref impl +// was *not* used. + +trait MyTrait1 { + fn my_fn(&self) {} +} + +impl MyTrait1 for Foo {} + +struct Foo(T); + +impl Deref for Foo<()> { + type Target = dyn MyTrait1 + 'static; + fn deref(&self) -> &(dyn MyTrait1 + 'static) { + panic!() + } +} + +// ...but if there is no impl with less derefs, the "guess" will be +// forced, so `(t: Bar<_>).my_fn2()` is `::my_fn2(*t)`, +// and because the deref impl is used, the `_` is forced to equal `u8`. + +trait MyTrait2 { + fn my_fn2(&self) {} +} + +impl MyTrait2 for u32 {} +struct Bar(T, u32); +impl Deref for Bar { + type Target = dyn MyTrait2 + 'static; + fn deref(&self) -> &(dyn MyTrait2 + 'static) { + &self.1 + } +} + +// actually invoke things + +fn main() { + let mut foo: Option> = None; + let mut bar: Option> = None; + let mut first_iter = true; + loop { + if !first_iter { + foo.as_ref().unwrap().my_fn(); + bar.as_ref().unwrap().my_fn2(); + break; + } + foo = Some(Foo(0)); + bar = Some(Bar(Default::default(), 0)); + first_iter = false; + } +} diff --git a/src/test/ui/attribute-with-no-generics-in-parameter-list.rs b/src/test/ui/attribute-with-no-generics-in-parameter-list.rs new file mode 100644 index 00000000000..c2cc91d8f77 --- /dev/null +++ b/src/test/ui/attribute-with-no-generics-in-parameter-list.rs @@ -0,0 +1,3 @@ +fn foo<#[attr]>() {} //~ ERROR attribute without generic parameters + +fn main() {} diff --git a/src/test/ui/attribute-with-no-generics-in-parameter-list.stderr b/src/test/ui/attribute-with-no-generics-in-parameter-list.stderr new file mode 100644 index 00000000000..f08f107a62f --- /dev/null +++ b/src/test/ui/attribute-with-no-generics-in-parameter-list.stderr @@ -0,0 +1,8 @@ +error: attribute without generic parameters + --> $DIR/attribute-with-no-generics-in-parameter-list.rs:1:8 + | +LL | fn foo<#[attr]>() {} //~ ERROR attribute without generic parameters + | ^^^^^^^ attributes are only permitted when preceding parameters + +error: aborting due to previous error + diff --git a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-1.rs b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-1.rs index d7feb038530..ca5fdd9da85 100644 --- a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-1.rs +++ b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-1.rs @@ -7,7 +7,7 @@ struct RefIntPair<'a, 'b>(&'a u32, &'b u32); impl<#[rustc_1] 'a, 'b, #[oops]> RefIntPair<'a, 'b> { - //~^ ERROR trailing attribute after lifetime parameters + //~^ ERROR trailing attribute after generic parameter } fn main() { diff --git a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-1.stderr b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-1.stderr index c4c0cee5ccc..55e7a987784 100644 --- a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-1.stderr +++ b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-1.stderr @@ -1,4 +1,4 @@ -error: trailing attribute after lifetime parameters +error: trailing attribute after generic parameter --> $DIR/attrs-with-no-formal-in-generics-1.rs:9:25 | LL | impl<#[rustc_1] 'a, 'b, #[oops]> RefIntPair<'a, 'b> { diff --git a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-2.rs b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-2.rs index f9db6a5f72a..c795612acf0 100644 --- a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-2.rs +++ b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-2.rs @@ -7,6 +7,6 @@ struct RefAny<'a, T>(&'a T); impl<#[rustc_1] 'a, #[rustc_2] T, #[oops]> RefAny<'a, T> {} -//~^ ERROR trailing attribute after type parameters +//~^ ERROR trailing attribute after generic parameter fn main() {} diff --git a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-2.stderr b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-2.stderr index 9099d74ce1b..acd0ae3678a 100644 --- a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-2.stderr +++ b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-2.stderr @@ -1,4 +1,4 @@ -error: trailing attribute after type parameters +error: trailing attribute after generic parameter --> $DIR/attrs-with-no-formal-in-generics-2.rs:9:35 | LL | impl<#[rustc_1] 'a, #[rustc_2] T, #[oops]> RefAny<'a, T> {} diff --git a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-3.rs b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-3.rs index e9f908d479f..3cfc70b4185 100644 --- a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-3.rs +++ b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-3.rs @@ -6,7 +6,7 @@ fn hof_lt(_: Q) where Q: for <#[allow(unused)] 'a, 'b, #[oops]> Fn(RefIntPair<'a,'b>) -> &'b u32 - //~^ ERROR trailing attribute after lifetime parameters + //~^ ERROR trailing attribute after generic parameter {} fn main() {} diff --git a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-3.stderr b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-3.stderr index 452f0ea5e17..b9ca0097467 100644 --- a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-3.stderr +++ b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-3.stderr @@ -1,4 +1,4 @@ -error: trailing attribute after lifetime parameters +error: trailing attribute after generic parameter --> $DIR/attrs-with-no-formal-in-generics-3.rs:8:44 | LL | where Q: for <#[allow(unused)] 'a, 'b, #[oops]> Fn(RefIntPair<'a,'b>) -> &'b u32 diff --git a/src/test/ui/augmented-assignments.nll.stderr b/src/test/ui/augmented-assignments.nll.stderr index 840b377263d..33c94d6e3a5 100644 --- a/src/test/ui/augmented-assignments.nll.stderr +++ b/src/test/ui/augmented-assignments.nll.stderr @@ -9,7 +9,7 @@ LL | x //~ error: use of moved value: `x` LL | | //~^ value used here after move LL | | += LL | | x; //~ value moved here - | | - + | | ^ | | | | |_____move out of `x` occurs here | borrow later used here diff --git a/src/test/ui/bad/bad-type-env-capture.rs b/src/test/ui/bad/bad-type-env-capture.rs index d2e6dff1252..53dfb13139a 100644 --- a/src/test/ui/bad/bad-type-env-capture.rs +++ b/src/test/ui/bad/bad-type-env-capture.rs @@ -1,4 +1,4 @@ fn foo() { - fn bar(b: T) { } //~ ERROR can't use type parameters from outer + fn bar(b: T) { } //~ ERROR can't use generic parameters from outer } fn main() { } diff --git a/src/test/ui/bad/bad-type-env-capture.stderr b/src/test/ui/bad/bad-type-env-capture.stderr index 5558a440061..ce803e96801 100644 --- a/src/test/ui/bad/bad-type-env-capture.stderr +++ b/src/test/ui/bad/bad-type-env-capture.stderr @@ -1,12 +1,12 @@ -error[E0401]: can't use type parameters from outer function +error[E0401]: can't use generic parameters from outer function --> $DIR/bad-type-env-capture.rs:2:15 | LL | fn foo() { | - type variable from outer function -LL | fn bar(b: T) { } //~ ERROR can't use type parameters from outer - | --- ^ use of type variable from outer function +LL | fn bar(b: T) { } //~ ERROR can't use generic parameters from outer + | --- ^ use of generic parameter from outer function | | - | help: try using a local type parameter instead: `bar` + | help: try using a local generic parameter instead: `bar` error: aborting due to previous error diff --git a/src/test/ui/const-generics/const-expression-parameter.rs b/src/test/ui/const-generics/const-expression-parameter.rs new file mode 100644 index 00000000000..f4e9008dbd0 --- /dev/null +++ b/src/test/ui/const-generics/const-expression-parameter.rs @@ -0,0 +1,23 @@ +#![feature(const_generics)] +//~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash + +fn u32_identity() -> u32 { + //~^ ERROR const generics in any position are currently unsupported + 5 +} + +fn foo_a() { + u32_identity::<-1>(); //~ ERROR expected identifier, found `<-` +} + +fn foo_b() { + u32_identity::<1 + 2>(); //~ ERROR expected one of `,` or `>`, found `+` +} + +fn foo_c() { + u32_identity::< -1 >(); // ok +} + +fn main() { + u32_identity::<5>(); // ok +} diff --git a/src/test/ui/const-generics/const-expression-parameter.stderr b/src/test/ui/const-generics/const-expression-parameter.stderr new file mode 100644 index 00000000000..1dd3a960316 --- /dev/null +++ b/src/test/ui/const-generics/const-expression-parameter.stderr @@ -0,0 +1,26 @@ +error: expected identifier, found `<-` + --> $DIR/const-expression-parameter.rs:10:19 + | +LL | u32_identity::<-1>(); //~ ERROR expected identifier, found `<-` + | ^^ expected identifier + +error: expected one of `,` or `>`, found `+` + --> $DIR/const-expression-parameter.rs:14:22 + | +LL | u32_identity::<1 + 2>(); //~ ERROR expected one of `,` or `>`, found `+` + | ^ expected one of `,` or `>` here + +warning: the feature `const_generics` is incomplete and may cause the compiler to crash + --> $DIR/const-expression-parameter.rs:1:12 + | +LL | #![feature(const_generics)] + | ^^^^^^^^^^^^^^ + +error: const generics in any position are currently unsupported + --> $DIR/const-expression-parameter.rs:4:23 + | +LL | fn u32_identity() -> u32 { + | ^ + +error: aborting due to 3 previous errors + diff --git a/src/test/ui/const-generics/const-fn-with-const-param.rs b/src/test/ui/const-generics/const-fn-with-const-param.rs new file mode 100644 index 00000000000..052d723d96e --- /dev/null +++ b/src/test/ui/const-generics/const-fn-with-const-param.rs @@ -0,0 +1,12 @@ +#![feature(const_generics)] +//~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash + +const fn const_u32_identity() -> u32 { + //~^ ERROR const parameters are not permitted in `const fn` + //~^^ ERROR const generics in any position are currently unsupported + X +} + +fn main() { + println!("{:?}", const_u32_identity::<18>()); +} diff --git a/src/test/ui/const-generics/const-fn-with-const-param.stderr b/src/test/ui/const-generics/const-fn-with-const-param.stderr new file mode 100644 index 00000000000..a08ebfb0d97 --- /dev/null +++ b/src/test/ui/const-generics/const-fn-with-const-param.stderr @@ -0,0 +1,24 @@ +warning: the feature `const_generics` is incomplete and may cause the compiler to crash + --> $DIR/const-fn-with-const-param.rs:1:12 + | +LL | #![feature(const_generics)] + | ^^^^^^^^^^^^^^ + +error: const parameters are not permitted in `const fn` + --> $DIR/const-fn-with-const-param.rs:4:1 + | +LL | / const fn const_u32_identity() -> u32 { +LL | | //~^ ERROR const parameters are not permitted in `const fn` +LL | | //~^^ ERROR const generics in any position are currently unsupported +LL | | X +LL | | } + | |_^ + +error: const generics in any position are currently unsupported + --> $DIR/const-fn-with-const-param.rs:4:35 + | +LL | const fn const_u32_identity() -> u32 { + | ^ + +error: aborting due to 2 previous errors + diff --git a/src/test/ui/const-generics/const-param-before-other-params.rs b/src/test/ui/const-generics/const-param-before-other-params.rs new file mode 100644 index 00000000000..3f120cbc4d3 --- /dev/null +++ b/src/test/ui/const-generics/const-param-before-other-params.rs @@ -0,0 +1,13 @@ +#![feature(const_generics)] +//~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash + +fn foo(_: T) { + //~^ ERROR type parameters must be declared prior to const parameters + //~^^ ERROR const generics in any position are currently unsupported +} + +fn bar(_: &'a ()) { + //~^ ERROR lifetime parameters must be declared prior to const parameters +} + +fn main() {} diff --git a/src/test/ui/const-generics/const-param-before-other-params.stderr b/src/test/ui/const-generics/const-param-before-other-params.stderr new file mode 100644 index 00000000000..aedcaf52e26 --- /dev/null +++ b/src/test/ui/const-generics/const-param-before-other-params.stderr @@ -0,0 +1,26 @@ +warning: the feature `const_generics` is incomplete and may cause the compiler to crash + --> $DIR/const-param-before-other-params.rs:1:12 + | +LL | #![feature(const_generics)] + | ^^^^^^^^^^^^^^ + +error: type parameters must be declared prior to const parameters + --> $DIR/const-param-before-other-params.rs:4:21 + | +LL | fn foo(_: T) { + | --------------^- help: reorder the parameters: lifetimes, then types, then consts: `` + +error: lifetime parameters must be declared prior to const parameters + --> $DIR/const-param-before-other-params.rs:9:21 + | +LL | fn bar(_: &'a ()) { + | --------------^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, const X: ()>` + +error: const generics in any position are currently unsupported + --> $DIR/const-param-before-other-params.rs:4:14 + | +LL | fn foo(_: T) { + | ^ + +error: aborting due to 3 previous errors + diff --git a/src/test/ui/const-generics/const-param-from-outer-fn.rs b/src/test/ui/const-generics/const-param-from-outer-fn.rs new file mode 100644 index 00000000000..5a8dd92086f --- /dev/null +++ b/src/test/ui/const-generics/const-param-from-outer-fn.rs @@ -0,0 +1,11 @@ +#![feature(const_generics)] +//~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash + +fn foo() { + //~^ ERROR const generics in any position are currently unsupported + fn bar() -> u32 { + X //~ ERROR can't use generic parameters from outer function + } +} + +fn main() {} diff --git a/src/test/ui/const-generics/const-param-from-outer-fn.stderr b/src/test/ui/const-generics/const-param-from-outer-fn.stderr new file mode 100644 index 00000000000..b238b3a2aa4 --- /dev/null +++ b/src/test/ui/const-generics/const-param-from-outer-fn.stderr @@ -0,0 +1,26 @@ +warning: the feature `const_generics` is incomplete and may cause the compiler to crash + --> $DIR/const-param-from-outer-fn.rs:1:12 + | +LL | #![feature(const_generics)] + | ^^^^^^^^^^^^^^ + +error[E0401]: can't use generic parameters from outer function + --> $DIR/const-param-from-outer-fn.rs:7:9 + | +LL | fn foo() { + | - const variable from outer function +LL | //~^ ERROR const generics in any position are currently unsupported +LL | fn bar() -> u32 { + | --- try adding a local generic parameter in this method instead +LL | X //~ ERROR can't use generic parameters from outer function + | ^ use of generic parameter from outer function + +error: const generics in any position are currently unsupported + --> $DIR/const-param-from-outer-fn.rs:4:14 + | +LL | fn foo() { + | ^ + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0401`. diff --git a/src/test/ui/duplicate/duplicate-type-parameter.stderr b/src/test/ui/duplicate/duplicate-type-parameter.stderr index 41750d4bb36..17d48edc35c 100644 --- a/src/test/ui/duplicate/duplicate-type-parameter.stderr +++ b/src/test/ui/duplicate/duplicate-type-parameter.stderr @@ -1,4 +1,4 @@ -error[E0403]: the name `T` is already used for a type parameter in this type parameter list +error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters --> $DIR/duplicate-type-parameter.rs:1:12 | LL | type Foo = Option; @@ -6,7 +6,7 @@ LL | type Foo = Option; | | | first use of `T` -error[E0403]: the name `T` is already used for a type parameter in this type parameter list +error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters --> $DIR/duplicate-type-parameter.rs:4:14 | LL | struct Bar(T); @@ -14,7 +14,7 @@ LL | struct Bar(T); | | | first use of `T` -error[E0403]: the name `T` is already used for a type parameter in this type parameter list +error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters --> $DIR/duplicate-type-parameter.rs:7:14 | LL | struct Baz { @@ -22,7 +22,7 @@ LL | struct Baz { | | | first use of `T` -error[E0403]: the name `T` is already used for a type parameter in this type parameter list +error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters --> $DIR/duplicate-type-parameter.rs:12:12 | LL | enum Boo { @@ -30,7 +30,7 @@ LL | enum Boo { | | | first use of `T` -error[E0403]: the name `T` is already used for a type parameter in this type parameter list +error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters --> $DIR/duplicate-type-parameter.rs:18:11 | LL | fn quux(x: T) {} @@ -38,7 +38,7 @@ LL | fn quux(x: T) {} | | | first use of `T` -error[E0403]: the name `T` is already used for a type parameter in this type parameter list +error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters --> $DIR/duplicate-type-parameter.rs:21:13 | LL | trait Qux {} @@ -46,7 +46,7 @@ LL | trait Qux {} | | | first use of `T` -error[E0403]: the name `T` is already used for a type parameter in this type parameter list +error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters --> $DIR/duplicate-type-parameter.rs:24:8 | LL | impl Qux for Option {} diff --git a/src/test/ui/error-codes/E0401.stderr b/src/test/ui/error-codes/E0401.stderr index c94fa497678..27f281ee437 100644 --- a/src/test/ui/error-codes/E0401.stderr +++ b/src/test/ui/error-codes/E0401.stderr @@ -1,26 +1,26 @@ -error[E0401]: can't use type parameters from outer function +error[E0401]: can't use generic parameters from outer function --> $DIR/E0401.rs:4:39 | LL | fn foo(x: T) { | - type variable from outer function LL | fn bfnr, W: Fn()>(y: T) { //~ ERROR E0401 - | --------------------------- ^ use of type variable from outer function + | --------------------------- ^ use of generic parameter from outer function | | - | help: try using a local type parameter instead: `bfnr, W: Fn(), T>` + | help: try using a local generic parameter instead: `bfnr, W: Fn(), T>` -error[E0401]: can't use type parameters from outer function +error[E0401]: can't use generic parameters from outer function --> $DIR/E0401.rs:9:16 | LL | fn foo(x: T) { | - type variable from outer function ... LL | fn baz $DIR/E0401.rs:22:25 | LL | impl Iterator for A { @@ -29,7 +29,7 @@ LL | impl Iterator for A { LL | fn helper(sel: &Self) -> u8 { //~ ERROR E0401 | ^^^^ | | - | use of type variable from outer function + | use of generic parameter from outer function | use a type here instead error: aborting due to 3 previous errors diff --git a/src/test/ui/error-codes/E0403.stderr b/src/test/ui/error-codes/E0403.stderr index 919a82dbe1a..b9246475029 100644 --- a/src/test/ui/error-codes/E0403.stderr +++ b/src/test/ui/error-codes/E0403.stderr @@ -1,4 +1,4 @@ -error[E0403]: the name `T` is already used for a type parameter in this type parameter list +error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters --> $DIR/E0403.rs:1:11 | LL | fn foo(s: T, u: T) {} //~ ERROR E0403 diff --git a/src/test/ui/feature-gates/feature-gate-const_generics.rs b/src/test/ui/feature-gates/feature-gate-const_generics.rs new file mode 100644 index 00000000000..a8a4ed57722 --- /dev/null +++ b/src/test/ui/feature-gates/feature-gate-const_generics.rs @@ -0,0 +1,6 @@ +fn foo() {} //~ ERROR const generics are unstable +//~^ const generics in any position are currently unsupported + +struct Foo([(); X]); //~ ERROR const generics are unstable + +fn main() {} diff --git a/src/test/ui/feature-gates/feature-gate-const_generics.stderr b/src/test/ui/feature-gates/feature-gate-const_generics.stderr new file mode 100644 index 00000000000..905cc07b6a1 --- /dev/null +++ b/src/test/ui/feature-gates/feature-gate-const_generics.stderr @@ -0,0 +1,25 @@ +error[E0658]: const generics are unstable (see issue #44580) + --> $DIR/feature-gate-const_generics.rs:1:14 + | +LL | fn foo() {} //~ ERROR const generics are unstable + | ^ + | + = help: add #![feature(const_generics)] to the crate attributes to enable + +error[E0658]: const generics are unstable (see issue #44580) + --> $DIR/feature-gate-const_generics.rs:4:18 + | +LL | struct Foo([(); X]); //~ ERROR const generics are unstable + | ^ + | + = help: add #![feature(const_generics)] to the crate attributes to enable + +error: const generics in any position are currently unsupported + --> $DIR/feature-gate-const_generics.rs:1:14 + | +LL | fn foo() {} //~ ERROR const generics are unstable + | ^ + +error: aborting due to 3 previous errors + +For more information about this error, try `rustc --explain E0658`. diff --git a/src/test/ui/impl-trait/bindings.rs b/src/test/ui/impl-trait/bindings.rs index 899303646d6..91d092634a9 100644 --- a/src/test/ui/impl-trait/bindings.rs +++ b/src/test/ui/impl-trait/bindings.rs @@ -2,27 +2,27 @@ fn a(x: T) { const foo: impl Clone = x; -//~^ ERROR can't capture dynamic environment in a fn item + //~^ ERROR attempt to use a non-constant value in a constant } fn b(x: T) { let _ = move || { const foo: impl Clone = x; -//~^ ERROR can't capture dynamic environment in a fn item + //~^ ERROR attempt to use a non-constant value in a constant }; } trait Foo { fn a(x: T) { const foo: impl Clone = x; -//~^ ERROR can't capture dynamic environment in a fn item + //~^ ERROR attempt to use a non-constant value in a constant } } impl Foo for i32 { fn a(x: T) { const foo: impl Clone = x; -//~^ ERROR can't capture dynamic environment in a fn item + //~^ ERROR attempt to use a non-constant value in a constant } } diff --git a/src/test/ui/impl-trait/bindings.stderr b/src/test/ui/impl-trait/bindings.stderr index 2a9be7a270a..a5bf583afea 100644 --- a/src/test/ui/impl-trait/bindings.stderr +++ b/src/test/ui/impl-trait/bindings.stderr @@ -1,35 +1,27 @@ -error[E0434]: can't capture dynamic environment in a fn item +error[E0435]: attempt to use a non-constant value in a constant --> $DIR/bindings.rs:4:29 | LL | const foo: impl Clone = x; - | ^ - | - = help: use the `|| { ... }` closure form instead + | ^ non-constant value -error[E0434]: can't capture dynamic environment in a fn item +error[E0435]: attempt to use a non-constant value in a constant --> $DIR/bindings.rs:10:33 | LL | const foo: impl Clone = x; - | ^ - | - = help: use the `|| { ... }` closure form instead + | ^ non-constant value -error[E0434]: can't capture dynamic environment in a fn item +error[E0435]: attempt to use a non-constant value in a constant --> $DIR/bindings.rs:17:33 | LL | const foo: impl Clone = x; - | ^ - | - = help: use the `|| { ... }` closure form instead + | ^ non-constant value -error[E0434]: can't capture dynamic environment in a fn item +error[E0435]: attempt to use a non-constant value in a constant --> $DIR/bindings.rs:24:33 | LL | const foo: impl Clone = x; - | ^ - | - = help: use the `|| { ... }` closure form instead + | ^ non-constant value error: aborting due to 4 previous errors -For more information about this error, try `rustc --explain E0434`. +For more information about this error, try `rustc --explain E0435`. diff --git a/src/test/ui/inner-static-type-parameter.rs b/src/test/ui/inner-static-type-parameter.rs index 60b4c5b8131..c08ccd29d80 100644 --- a/src/test/ui/inner-static-type-parameter.rs +++ b/src/test/ui/inner-static-type-parameter.rs @@ -4,7 +4,7 @@ enum Bar { What } //~ ERROR parameter `T` is never used fn foo() { static a: Bar = Bar::What; -//~^ ERROR can't use type parameters from outer function +//~^ ERROR can't use generic parameters from outer function } fn main() { diff --git a/src/test/ui/inner-static-type-parameter.stderr b/src/test/ui/inner-static-type-parameter.stderr index 2f2856edb0c..87fb364954d 100644 --- a/src/test/ui/inner-static-type-parameter.stderr +++ b/src/test/ui/inner-static-type-parameter.stderr @@ -1,12 +1,12 @@ -error[E0401]: can't use type parameters from outer function +error[E0401]: can't use generic parameters from outer function --> $DIR/inner-static-type-parameter.rs:6:19 | LL | fn foo() { | --- - type variable from outer function | | - | try adding a local type parameter in this method instead + | try adding a local generic parameter in this method instead LL | static a: Bar = Bar::What; - | ^ use of type variable from outer function + | ^ use of generic parameter from outer function error[E0392]: parameter `T` is never used --> $DIR/inner-static-type-parameter.rs:3:10 diff --git a/src/test/ui/issues/issue-12796.rs b/src/test/ui/issues/issue-12796.rs index acd4584c737..942d6b9a568 100644 --- a/src/test/ui/issues/issue-12796.rs +++ b/src/test/ui/issues/issue-12796.rs @@ -1,7 +1,7 @@ trait Trait { fn outer(&self) { fn inner(_: &Self) { - //~^ ERROR can't use type parameters from outer function + //~^ ERROR can't use generic parameters from outer function } } } diff --git a/src/test/ui/issues/issue-12796.stderr b/src/test/ui/issues/issue-12796.stderr index 4bc29fd37dc..a01fd2d6542 100644 --- a/src/test/ui/issues/issue-12796.stderr +++ b/src/test/ui/issues/issue-12796.stderr @@ -1,10 +1,10 @@ -error[E0401]: can't use type parameters from outer function +error[E0401]: can't use generic parameters from outer function --> $DIR/issue-12796.rs:3:22 | LL | fn inner(_: &Self) { | ^^^^ | | - | use of type variable from outer function + | use of generic parameter from outer function | can't use `Self` here error: aborting due to previous error diff --git a/src/test/ui/issues/issue-20616-3.rs b/src/test/ui/issues/issue-20616-3.rs index e84506ee249..9bfd5bf2313 100644 --- a/src/test/ui/issues/issue-20616-3.rs +++ b/src/test/ui/issues/issue-20616-3.rs @@ -1,8 +1,6 @@ // We need all these 9 issue-20616-N.rs files // because we can only catch one parsing error at a time - - type Type_1_<'a, T> = &'a T; @@ -12,7 +10,8 @@ //type Type_2 = Type_1_<'static ()>; // error: expected `,` or `>` after lifetime name, found `(` -type Type_3 = Box; //~ error: expected one of `>`, identifier, lifetime, or type, found `,` +type Type_3 = Box; +//~^ error: expected one of `>`, const, identifier, lifetime, or type, found `,` //type Type_4 = Type_1_<'static,, T>; // error: expected type, found `,` diff --git a/src/test/ui/issues/issue-20616-3.stderr b/src/test/ui/issues/issue-20616-3.stderr index 5247298b7cc..f51fb949c74 100644 --- a/src/test/ui/issues/issue-20616-3.stderr +++ b/src/test/ui/issues/issue-20616-3.stderr @@ -1,8 +1,8 @@ -error: expected one of `>`, identifier, lifetime, or type, found `,` - --> $DIR/issue-20616-3.rs:15:24 +error: expected one of `>`, const, identifier, lifetime, or type, found `,` + --> $DIR/issue-20616-3.rs:13:24 | -LL | type Type_3 = Box; //~ error: expected one of `>`, identifier, lifetime, or type, found `,` - | ^ expected one of `>`, identifier, lifetime, or type here +LL | type Type_3 = Box; + | ^ expected one of `>`, const, identifier, lifetime, or type here error: aborting due to previous error diff --git a/src/test/ui/issues/issue-20616-4.rs b/src/test/ui/issues/issue-20616-4.rs index 785a6fa7d9a..e9a34a04667 100644 --- a/src/test/ui/issues/issue-20616-4.rs +++ b/src/test/ui/issues/issue-20616-4.rs @@ -1,8 +1,6 @@ // We need all these 9 issue-20616-N.rs files // because we can only catch one parsing error at a time - - type Type_1_<'a, T> = &'a T; @@ -16,7 +14,7 @@ type Type_4 = Type_1_<'static,, T>; -//~^ error: expected one of `>`, identifier, lifetime, or type, found `,` +//~^ error: expected one of `>`, const, identifier, lifetime, or type, found `,` type Type_5_<'a> = Type_1_<'a, ()>; diff --git a/src/test/ui/issues/issue-20616-4.stderr b/src/test/ui/issues/issue-20616-4.stderr index 74c38d9e97d..22a655465e8 100644 --- a/src/test/ui/issues/issue-20616-4.stderr +++ b/src/test/ui/issues/issue-20616-4.stderr @@ -1,8 +1,8 @@ -error: expected one of `>`, identifier, lifetime, or type, found `,` - --> $DIR/issue-20616-4.rs:18:34 +error: expected one of `>`, const, identifier, lifetime, or type, found `,` + --> $DIR/issue-20616-4.rs:16:34 | LL | type Type_4 = Type_1_<'static,, T>; - | ^ expected one of `>`, identifier, lifetime, or type here + | ^ expected one of `>`, const, identifier, lifetime, or type here error: aborting due to previous error diff --git a/src/test/ui/issues/issue-20616-5.rs b/src/test/ui/issues/issue-20616-5.rs index 71dcc1f3a02..23862516d2c 100644 --- a/src/test/ui/issues/issue-20616-5.rs +++ b/src/test/ui/issues/issue-20616-5.rs @@ -1,8 +1,6 @@ // We need all these 9 issue-20616-N.rs files // because we can only catch one parsing error at a time - - type Type_1_<'a, T> = &'a T; @@ -22,7 +20,7 @@ type Type_5<'a> = Type_1_<'a, (),,>; -//~^ error: expected one of `>`, identifier, lifetime, or type, found `,` +//~^ error: expected one of `>`, const, identifier, lifetime, or type, found `,` //type Type_6 = Type_5_<'a,,>; // error: expected type, found `,` diff --git a/src/test/ui/issues/issue-20616-5.stderr b/src/test/ui/issues/issue-20616-5.stderr index 38457beadc4..d83fc41f43e 100644 --- a/src/test/ui/issues/issue-20616-5.stderr +++ b/src/test/ui/issues/issue-20616-5.stderr @@ -1,8 +1,8 @@ -error: expected one of `>`, identifier, lifetime, or type, found `,` - --> $DIR/issue-20616-5.rs:24:34 +error: expected one of `>`, const, identifier, lifetime, or type, found `,` + --> $DIR/issue-20616-5.rs:22:34 | LL | type Type_5<'a> = Type_1_<'a, (),,>; - | ^ expected one of `>`, identifier, lifetime, or type here + | ^ expected one of `>`, const, identifier, lifetime, or type here error: aborting due to previous error diff --git a/src/test/ui/issues/issue-20616-6.rs b/src/test/ui/issues/issue-20616-6.rs index da32da48852..dc327f3f788 100644 --- a/src/test/ui/issues/issue-20616-6.rs +++ b/src/test/ui/issues/issue-20616-6.rs @@ -1,8 +1,6 @@ // We need all these 9 issue-20616-N.rs files // because we can only catch one parsing error at a time - - type Type_1_<'a, T> = &'a T; @@ -25,7 +23,7 @@ type Type_6 = Type_5_<'a,,>; -//~^ error: expected one of `>`, identifier, lifetime, or type, found `,` +//~^ error: expected one of `>`, const, identifier, lifetime, or type, found `,` //type Type_7 = Box<(),,>; // error: expected type, found `,` diff --git a/src/test/ui/issues/issue-20616-6.stderr b/src/test/ui/issues/issue-20616-6.stderr index 55b1d031a39..0740df59523 100644 --- a/src/test/ui/issues/issue-20616-6.stderr +++ b/src/test/ui/issues/issue-20616-6.stderr @@ -1,8 +1,8 @@ -error: expected one of `>`, identifier, lifetime, or type, found `,` - --> $DIR/issue-20616-6.rs:27:26 +error: expected one of `>`, const, identifier, lifetime, or type, found `,` + --> $DIR/issue-20616-6.rs:25:26 | LL | type Type_6 = Type_5_<'a,,>; - | ^ expected one of `>`, identifier, lifetime, or type here + | ^ expected one of `>`, const, identifier, lifetime, or type here error: aborting due to previous error diff --git a/src/test/ui/issues/issue-20616-7.rs b/src/test/ui/issues/issue-20616-7.rs index feaaff2c890..ffd1620c1d3 100644 --- a/src/test/ui/issues/issue-20616-7.rs +++ b/src/test/ui/issues/issue-20616-7.rs @@ -1,8 +1,6 @@ // We need all these 9 issue-20616-N.rs files // because we can only catch one parsing error at a time - - type Type_1_<'a, T> = &'a T; @@ -27,7 +25,8 @@ //type Type_6 = Type_5_<'a,,>; // error: expected type, found `,` -type Type_7 = Box<(),,>; //~ error: expected one of `>`, identifier, lifetime, or type, found `,` +type Type_7 = Box<(),,>; +//~^ error: expected one of `>`, const, identifier, lifetime, or type, found `,` //type Type_8<'a,,> = &'a (); // error: expected ident, found `,` diff --git a/src/test/ui/issues/issue-20616-7.stderr b/src/test/ui/issues/issue-20616-7.stderr index 8b5f67c703f..c0e108375be 100644 --- a/src/test/ui/issues/issue-20616-7.stderr +++ b/src/test/ui/issues/issue-20616-7.stderr @@ -1,8 +1,8 @@ -error: expected one of `>`, identifier, lifetime, or type, found `,` - --> $DIR/issue-20616-7.rs:30:22 +error: expected one of `>`, const, identifier, lifetime, or type, found `,` + --> $DIR/issue-20616-7.rs:28:22 | -LL | type Type_7 = Box<(),,>; //~ error: expected one of `>`, identifier, lifetime, or type, found `,` - | ^ expected one of `>`, identifier, lifetime, or type here +LL | type Type_7 = Box<(),,>; + | ^ expected one of `>`, const, identifier, lifetime, or type here error: aborting due to previous error diff --git a/src/test/ui/issues/issue-20616-8.rs b/src/test/ui/issues/issue-20616-8.rs index 2fc7243559a..c9e8b61e50b 100644 --- a/src/test/ui/issues/issue-20616-8.rs +++ b/src/test/ui/issues/issue-20616-8.rs @@ -1,8 +1,6 @@ // We need all these 9 issue-20616-N.rs files // because we can only catch one parsing error at a time - - type Type_1_<'a, T> = &'a T; @@ -30,7 +28,8 @@ //type Type_7 = Box<(),,>; // error: expected type, found `,` -type Type_8<'a,,> = &'a (); //~ error: expected one of `>`, identifier, or lifetime, found `,` +type Type_8<'a,,> = &'a (); +//~^ error: expected one of `>`, `const`, identifier, or lifetime, found `,` //type Type_9 = Box; // error: expected identifier, found `,` diff --git a/src/test/ui/issues/issue-20616-8.stderr b/src/test/ui/issues/issue-20616-8.stderr index cdeb544f07c..0ef9192f1e7 100644 --- a/src/test/ui/issues/issue-20616-8.stderr +++ b/src/test/ui/issues/issue-20616-8.stderr @@ -1,8 +1,8 @@ -error: expected one of `>`, identifier, or lifetime, found `,` - --> $DIR/issue-20616-8.rs:33:16 +error: expected one of `>`, `const`, identifier, or lifetime, found `,` + --> $DIR/issue-20616-8.rs:31:16 | -LL | type Type_8<'a,,> = &'a (); //~ error: expected one of `>`, identifier, or lifetime, found `,` - | ^ expected one of `>`, identifier, or lifetime here +LL | type Type_8<'a,,> = &'a (); + | ^ expected one of `>`, `const`, identifier, or lifetime here error: aborting due to previous error diff --git a/src/test/ui/issues/issue-20616-9.rs b/src/test/ui/issues/issue-20616-9.rs index b14a5b0ff36..1c509f26fd6 100644 --- a/src/test/ui/issues/issue-20616-9.rs +++ b/src/test/ui/issues/issue-20616-9.rs @@ -1,8 +1,6 @@ // We need all these 9 issue-20616-N.rs files // because we can only catch one parsing error at a time - - type Type_1_<'a, T> = &'a T; @@ -33,4 +31,5 @@ //type Type_8<'a,,> = &'a (); // error: expected identifier, found `,` -type Type_9 = Box; //~ error: expected one of `>`, identifier, or lifetime, found `,` +type Type_9 = Box; +//~^ error: expected one of `>`, `const`, identifier, or lifetime, found `,` diff --git a/src/test/ui/issues/issue-20616-9.stderr b/src/test/ui/issues/issue-20616-9.stderr index dfe705c6f12..5fd1400a2e8 100644 --- a/src/test/ui/issues/issue-20616-9.stderr +++ b/src/test/ui/issues/issue-20616-9.stderr @@ -1,8 +1,8 @@ -error: expected one of `>`, identifier, or lifetime, found `,` - --> $DIR/issue-20616-9.rs:36:15 +error: expected one of `>`, `const`, identifier, or lifetime, found `,` + --> $DIR/issue-20616-9.rs:34:15 | -LL | type Type_9 = Box; //~ error: expected one of `>`, identifier, or lifetime, found `,` - | ^ expected one of `>`, identifier, or lifetime here +LL | type Type_9 = Box; + | ^ expected one of `>`, `const`, identifier, or lifetime here error: aborting due to previous error diff --git a/src/test/ui/issues/issue-27433.rs b/src/test/ui/issues/issue-27433.rs index 2cc7d05e7c6..156ae68efe2 100644 --- a/src/test/ui/issues/issue-27433.rs +++ b/src/test/ui/issues/issue-27433.rs @@ -1,5 +1,5 @@ fn main() { let foo = 42u32; const FOO : u32 = foo; - //~^ ERROR can't capture dynamic environment + //~^ ERROR attempt to use a non-constant value in a constant } diff --git a/src/test/ui/issues/issue-27433.stderr b/src/test/ui/issues/issue-27433.stderr index 78a193dd99a..e232d17e6d7 100644 --- a/src/test/ui/issues/issue-27433.stderr +++ b/src/test/ui/issues/issue-27433.stderr @@ -1,11 +1,9 @@ -error[E0434]: can't capture dynamic environment in a fn item +error[E0435]: attempt to use a non-constant value in a constant --> $DIR/issue-27433.rs:3:23 | LL | const FOO : u32 = foo; - | ^^^ - | - = help: use the `|| { ... }` closure form instead + | ^^^ non-constant value error: aborting due to previous error -For more information about this error, try `rustc --explain E0434`. +For more information about this error, try `rustc --explain E0435`. diff --git a/src/test/ui/issues/issue-3021-c.rs b/src/test/ui/issues/issue-3021-c.rs index 491336206ca..94ed1fdf781 100644 --- a/src/test/ui/issues/issue-3021-c.rs +++ b/src/test/ui/issues/issue-3021-c.rs @@ -1,8 +1,8 @@ fn siphash() { trait U { - fn g(&self, x: T) -> T; //~ ERROR can't use type parameters from outer function - //~^ ERROR can't use type parameters from outer function + fn g(&self, x: T) -> T; //~ ERROR can't use generic parameters from outer function + //~^ ERROR can't use generic parameters from outer function } } diff --git a/src/test/ui/issues/issue-3021-c.stderr b/src/test/ui/issues/issue-3021-c.stderr index 323ce4fa306..5eadf7837c7 100644 --- a/src/test/ui/issues/issue-3021-c.stderr +++ b/src/test/ui/issues/issue-3021-c.stderr @@ -1,24 +1,24 @@ -error[E0401]: can't use type parameters from outer function +error[E0401]: can't use generic parameters from outer function --> $DIR/issue-3021-c.rs:4:24 | LL | fn siphash() { | - type variable from outer function ... -LL | fn g(&self, x: T) -> T; //~ ERROR can't use type parameters from outer function - | - ^ use of type variable from outer function +LL | fn g(&self, x: T) -> T; //~ ERROR can't use generic parameters from outer function + | - ^ use of generic parameter from outer function | | - | help: try using a local type parameter instead: `g` + | help: try using a local generic parameter instead: `g` -error[E0401]: can't use type parameters from outer function +error[E0401]: can't use generic parameters from outer function --> $DIR/issue-3021-c.rs:4:30 | LL | fn siphash() { | - type variable from outer function ... -LL | fn g(&self, x: T) -> T; //~ ERROR can't use type parameters from outer function - | - ^ use of type variable from outer function +LL | fn g(&self, x: T) -> T; //~ ERROR can't use generic parameters from outer function + | - ^ use of generic parameter from outer function | | - | help: try using a local type parameter instead: `g` + | help: try using a local generic parameter instead: `g` error: aborting due to 2 previous errors diff --git a/src/test/ui/issues/issue-3214.rs b/src/test/ui/issues/issue-3214.rs index 85eae2686e6..9a727aa3057 100644 --- a/src/test/ui/issues/issue-3214.rs +++ b/src/test/ui/issues/issue-3214.rs @@ -1,6 +1,6 @@ fn foo() { struct Foo { - x: T, //~ ERROR can't use type parameters from outer function + x: T, //~ ERROR can't use generic parameters from outer function } impl Drop for Foo { diff --git a/src/test/ui/issues/issue-3214.stderr b/src/test/ui/issues/issue-3214.stderr index 4ecea4f9800..e6526bad3e0 100644 --- a/src/test/ui/issues/issue-3214.stderr +++ b/src/test/ui/issues/issue-3214.stderr @@ -1,13 +1,13 @@ -error[E0401]: can't use type parameters from outer function +error[E0401]: can't use generic parameters from outer function --> $DIR/issue-3214.rs:3:12 | LL | fn foo() { | --- - type variable from outer function | | - | try adding a local type parameter in this method instead + | try adding a local generic parameter in this method instead LL | struct Foo { -LL | x: T, //~ ERROR can't use type parameters from outer function - | ^ use of type variable from outer function +LL | x: T, //~ ERROR can't use generic parameters from outer function + | ^ use of generic parameter from outer function error[E0107]: wrong number of type arguments: expected 0, found 1 --> $DIR/issue-3214.rs:6:26 diff --git a/src/test/ui/issues/issue-3521-2.rs b/src/test/ui/issues/issue-3521-2.rs index 39f7fcb8337..871394f9eae 100644 --- a/src/test/ui/issues/issue-3521-2.rs +++ b/src/test/ui/issues/issue-3521-2.rs @@ -2,7 +2,7 @@ fn main() { let foo = 100; static y: isize = foo + 1; - //~^ ERROR can't capture dynamic environment + //~^ ERROR attempt to use a non-constant value in a constant println!("{}", y); } diff --git a/src/test/ui/issues/issue-3521-2.stderr b/src/test/ui/issues/issue-3521-2.stderr index 1464fd74bba..d54bbbcdc33 100644 --- a/src/test/ui/issues/issue-3521-2.stderr +++ b/src/test/ui/issues/issue-3521-2.stderr @@ -1,11 +1,9 @@ -error[E0434]: can't capture dynamic environment in a fn item +error[E0435]: attempt to use a non-constant value in a constant --> $DIR/issue-3521-2.rs:4:23 | LL | static y: isize = foo + 1; - | ^^^ - | - = help: use the `|| { ... }` closure form instead + | ^^^ non-constant value error: aborting due to previous error -For more information about this error, try `rustc --explain E0434`. +For more information about this error, try `rustc --explain E0435`. diff --git a/src/test/ui/issues/issue-3668-2.rs b/src/test/ui/issues/issue-3668-2.rs index 265a884ded7..525f6f5684e 100644 --- a/src/test/ui/issues/issue-3668-2.rs +++ b/src/test/ui/issues/issue-3668-2.rs @@ -1,6 +1,6 @@ fn f(x:isize) { static child: isize = x + 1; - //~^ ERROR can't capture dynamic environment + //~^ ERROR attempt to use a non-constant value in a constant } fn main() {} diff --git a/src/test/ui/issues/issue-3668-2.stderr b/src/test/ui/issues/issue-3668-2.stderr index 8dd6f49d8de..d6a6e837960 100644 --- a/src/test/ui/issues/issue-3668-2.stderr +++ b/src/test/ui/issues/issue-3668-2.stderr @@ -1,11 +1,9 @@ -error[E0434]: can't capture dynamic environment in a fn item +error[E0435]: attempt to use a non-constant value in a constant --> $DIR/issue-3668-2.rs:2:27 | LL | static child: isize = x + 1; - | ^ - | - = help: use the `|| { ... }` closure form instead + | ^ non-constant value error: aborting due to previous error -For more information about this error, try `rustc --explain E0434`. +For more information about this error, try `rustc --explain E0435`. diff --git a/src/test/ui/issues/issue-3668.rs b/src/test/ui/issues/issue-3668.rs index 3f61b1b02e7..0e1f19a75ba 100644 --- a/src/test/ui/issues/issue-3668.rs +++ b/src/test/ui/issues/issue-3668.rs @@ -6,7 +6,7 @@ trait PTrait { impl PTrait for P { fn getChildOption(&self) -> Option> { static childVal: Box

= self.child.get(); - //~^ ERROR can't capture dynamic environment + //~^ ERROR attempt to use a non-constant value in a constant panic!(); } } diff --git a/src/test/ui/issues/issue-3668.stderr b/src/test/ui/issues/issue-3668.stderr index 7f974de9da8..98cd3631a53 100644 --- a/src/test/ui/issues/issue-3668.stderr +++ b/src/test/ui/issues/issue-3668.stderr @@ -1,11 +1,9 @@ -error[E0434]: can't capture dynamic environment in a fn item +error[E0435]: attempt to use a non-constant value in a constant --> $DIR/issue-3668.rs:8:34 | LL | static childVal: Box

= self.child.get(); - | ^^^^ - | - = help: use the `|| { ... }` closure form instead + | ^^^^ non-constant value error: aborting due to previous error -For more information about this error, try `rustc --explain E0434`. +For more information about this error, try `rustc --explain E0435`. diff --git a/src/test/ui/issues/issue-52891.stderr b/src/test/ui/issues/issue-52891.stderr index 55d611070d9..65b2b9460bc 100644 --- a/src/test/ui/issues/issue-52891.stderr +++ b/src/test/ui/issues/issue-52891.stderr @@ -90,7 +90,7 @@ LL | use issue_52891::a; LL | m, | ______- LL | | a}; //~ ERROR `a` is defined multiple times - | | - + | | ^ | | | | |_____`a` reimported here | help: remove unnecessary import diff --git a/src/test/ui/issues/issue-5997-enum.rs b/src/test/ui/issues/issue-5997-enum.rs index 0987117ecd4..3ff4e036c60 100644 --- a/src/test/ui/issues/issue-5997-enum.rs +++ b/src/test/ui/issues/issue-5997-enum.rs @@ -1,6 +1,6 @@ fn f() -> bool { enum E { V(Z) } - //~^ ERROR can't use type parameters from outer function + //~^ ERROR can't use generic parameters from outer function true } diff --git a/src/test/ui/issues/issue-5997-enum.stderr b/src/test/ui/issues/issue-5997-enum.stderr index 5c26dc92c85..5c778143e13 100644 --- a/src/test/ui/issues/issue-5997-enum.stderr +++ b/src/test/ui/issues/issue-5997-enum.stderr @@ -1,12 +1,12 @@ -error[E0401]: can't use type parameters from outer function +error[E0401]: can't use generic parameters from outer function --> $DIR/issue-5997-enum.rs:2:16 | LL | fn f() -> bool { | - - type variable from outer function | | - | try adding a local type parameter in this method instead + | try adding a local generic parameter in this method instead LL | enum E { V(Z) } - | ^ use of type variable from outer function + | ^ use of generic parameter from outer function error: aborting due to previous error diff --git a/src/test/ui/issues/issue-5997-struct.rs b/src/test/ui/issues/issue-5997-struct.rs index 04ac489a55c..6cf510b0a9d 100644 --- a/src/test/ui/issues/issue-5997-struct.rs +++ b/src/test/ui/issues/issue-5997-struct.rs @@ -1,5 +1,5 @@ fn f() -> bool { - struct S(T); //~ ERROR can't use type parameters from outer function + struct S(T); //~ ERROR can't use generic parameters from outer function true } diff --git a/src/test/ui/issues/issue-5997-struct.stderr b/src/test/ui/issues/issue-5997-struct.stderr index 1d05d13242e..a60987b3f98 100644 --- a/src/test/ui/issues/issue-5997-struct.stderr +++ b/src/test/ui/issues/issue-5997-struct.stderr @@ -1,12 +1,12 @@ -error[E0401]: can't use type parameters from outer function +error[E0401]: can't use generic parameters from outer function --> $DIR/issue-5997-struct.rs:2:14 | LL | fn f() -> bool { | - - type variable from outer function | | - | try adding a local type parameter in this method instead -LL | struct S(T); //~ ERROR can't use type parameters from outer function - | ^ use of type variable from outer function + | try adding a local generic parameter in this method instead +LL | struct S(T); //~ ERROR can't use generic parameters from outer function + | ^ use of generic parameter from outer function error: aborting due to previous error diff --git a/src/test/ui/lifetime-before-type-params.stderr b/src/test/ui/lifetime-before-type-params.stderr index 7ac8dffdfbe..3cef5db66c6 100644 --- a/src/test/ui/lifetime-before-type-params.stderr +++ b/src/test/ui/lifetime-before-type-params.stderr @@ -2,41 +2,25 @@ error: lifetime parameters must be declared prior to type parameters --> $DIR/lifetime-before-type-params.rs:2:13 | LL | fn first() {} - | ^^ ^^ -help: move the lifetime parameter prior to the first type parameter - | -LL | fn first<'a, 'b, T>() {} - | ^^^ ^^^ -- + | ----^^--^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, 'b, T>` error: lifetime parameters must be declared prior to type parameters --> $DIR/lifetime-before-type-params.rs:4:18 | LL | fn second<'a, T, 'b>() {} - | ^^ -help: move the lifetime parameter prior to the first type parameter - | -LL | fn second<'a, 'b, T>() {} - | ^^^ -- + | --------^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, 'b, T>` error: lifetime parameters must be declared prior to type parameters --> $DIR/lifetime-before-type-params.rs:6:16 | LL | fn third() {} - | ^^ -help: move the lifetime parameter prior to the first type parameter - | -LL | fn third<'a, T, U>() {} - | ^^^ -- + | -------^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, T, U>` error: lifetime parameters must be declared prior to type parameters --> $DIR/lifetime-before-type-params.rs:8:18 | LL | fn fourth<'a, T, 'b, U, 'c, V>() {} - | ^^ ^^ -help: move the lifetime parameter prior to the first type parameter - | -LL | fn fourth<'a, 'b, 'c, T, U, V>() {} - | ^^^ ^^^ -- -- + | --------^^-----^^---- help: reorder the parameters: lifetimes, then types, then consts: `<'a, 'b, 'c, T, U, V>` error[E0601]: `main` function not found in crate `lifetime_before_type_params` | diff --git a/src/test/ui/macros/macro-follow.rs b/src/test/ui/macros/macro-follow.rs index f4a1931da5a..10b44e00175 100644 --- a/src/test/ui/macros/macro-follow.rs +++ b/src/test/ui/macros/macro-follow.rs @@ -12,11 +12,11 @@ macro_rules! follow_pat { ($p:pat >) => {}; //~ERROR `$p:pat` is followed by `>` ($p:pat +) => {}; //~ERROR `$p:pat` is followed by `+` ($p:pat ident) => {}; //~ERROR `$p:pat` is followed by `ident` - ($p:pat $p:pat) => {}; //~ERROR `$p:pat` is followed by `$p:pat` + ($p:pat $q:pat) => {}; //~ERROR `$p:pat` is followed by `$q:pat` ($p:pat $e:expr) => {}; //~ERROR `$p:pat` is followed by `$e:expr` ($p:pat $t:ty) => {}; //~ERROR `$p:pat` is followed by `$t:ty` ($p:pat $s:stmt) => {}; //~ERROR `$p:pat` is followed by `$s:stmt` - ($p:pat $p:path) => {}; //~ERROR `$p:pat` is followed by `$p:path` + ($p:pat $q:path) => {}; //~ERROR `$p:pat` is followed by `$q:path` ($p:pat $b:block) => {}; //~ERROR `$p:pat` is followed by `$b:block` ($p:pat $i:ident) => {}; //~ERROR `$p:pat` is followed by `$i:ident` ($p:pat $t:tt) => {}; //~ERROR `$p:pat` is followed by `$t:tt` @@ -37,7 +37,7 @@ macro_rules! follow_expr { ($e:expr if) => {}; //~ERROR `$e:expr` is followed by `if` ($e:expr in) => {}; //~ERROR `$e:expr` is followed by `in` ($e:expr $p:pat) => {}; //~ERROR `$e:expr` is followed by `$p:pat` - ($e:expr $e:expr) => {}; //~ERROR `$e:expr` is followed by `$e:expr` + ($e:expr $f:expr) => {}; //~ERROR `$e:expr` is followed by `$f:expr` ($e:expr $t:ty) => {}; //~ERROR `$e:expr` is followed by `$t:ty` ($e:expr $s:stmt) => {}; //~ERROR `$e:expr` is followed by `$s:stmt` ($e:expr $p:path) => {}; //~ERROR `$e:expr` is followed by `$p:path` @@ -57,12 +57,12 @@ macro_rules! follow_ty { ($t:ty if) => {}; //~ERROR `$t:ty` is followed by `if` ($t:ty $p:pat) => {}; //~ERROR `$t:ty` is followed by `$p:pat` ($t:ty $e:expr) => {}; //~ERROR `$t:ty` is followed by `$e:expr` - ($t:ty $t:ty) => {}; //~ERROR `$t:ty` is followed by `$t:ty` + ($t:ty $r:ty) => {}; //~ERROR `$t:ty` is followed by `$r:ty` ($t:ty $s:stmt) => {}; //~ERROR `$t:ty` is followed by `$s:stmt` ($t:ty $p:path) => {}; //~ERROR `$t:ty` is followed by `$p:path` ($t:ty $b:block) => {}; // ok (RFC 1494) ($t:ty $i:ident) => {}; //~ERROR `$t:ty` is followed by `$i:ident` - ($t:ty $t:tt) => {}; //~ERROR `$t:ty` is followed by `$t:tt` + ($t:ty $r:tt) => {}; //~ERROR `$t:ty` is followed by `$r:tt` ($t:ty $i:item) => {}; //~ERROR `$t:ty` is followed by `$i:item` ($t:ty $m:meta) => {}; //~ERROR `$t:ty` is followed by `$m:meta` } @@ -82,7 +82,7 @@ macro_rules! follow_stmt { ($s:stmt $p:pat) => {}; //~ERROR `$s:stmt` is followed by `$p:pat` ($s:stmt $e:expr) => {}; //~ERROR `$s:stmt` is followed by `$e:expr` ($s:stmt $t:ty) => {}; //~ERROR `$s:stmt` is followed by `$t:ty` - ($s:stmt $s:stmt) => {}; //~ERROR `$s:stmt` is followed by `$s:stmt` + ($s:stmt $t:stmt) => {}; //~ERROR `$s:stmt` is followed by `$t:stmt` ($s:stmt $p:path) => {}; //~ERROR `$s:stmt` is followed by `$p:path` ($s:stmt $b:block) => {}; //~ERROR `$s:stmt` is followed by `$b:block` ($s:stmt $i:ident) => {}; //~ERROR `$s:stmt` is followed by `$i:ident` @@ -97,11 +97,11 @@ macro_rules! follow_path { ($p:path +) => {}; //~ERROR `$p:path` is followed by `+` ($p:path ident) => {}; //~ERROR `$p:path` is followed by `ident` ($p:path if) => {}; //~ERROR `$p:path` is followed by `if` - ($p:path $p:pat) => {}; //~ERROR `$p:path` is followed by `$p:pat` + ($p:path $q:pat) => {}; //~ERROR `$p:path` is followed by `$q:pat` ($p:path $e:expr) => {}; //~ERROR `$p:path` is followed by `$e:expr` ($p:path $t:ty) => {}; //~ERROR `$p:path` is followed by `$t:ty` ($p:path $s:stmt) => {}; //~ERROR `$p:path` is followed by `$s:stmt` - ($p:path $p:path) => {}; //~ERROR `$p:path` is followed by `$p:path` + ($p:path $q:path) => {}; //~ERROR `$p:path` is followed by `$q:path` ($p:path $b:block) => {}; // ok (RFC 1494) ($p:path $i:ident) => {}; //~ERROR `$p:path` is followed by `$i:ident` ($p:path $t:tt) => {}; //~ERROR `$p:path` is followed by `$t:tt` diff --git a/src/test/ui/macros/macro-follow.stderr b/src/test/ui/macros/macro-follow.stderr index 4aea5cc5de6..e3302eac4ac 100644 --- a/src/test/ui/macros/macro-follow.stderr +++ b/src/test/ui/macros/macro-follow.stderr @@ -54,10 +54,10 @@ LL | ($p:pat ident) => {}; //~ERROR `$p:pat` is followed by `ident` | = note: allowed there are: `=>`, `,`, `=`, `|`, `if` or `in` -error: `$p:pat` is followed by `$p:pat`, which is not allowed for `pat` fragments +error: `$p:pat` is followed by `$q:pat`, which is not allowed for `pat` fragments --> $DIR/macro-follow.rs:15:13 | -LL | ($p:pat $p:pat) => {}; //~ERROR `$p:pat` is followed by `$p:pat` +LL | ($p:pat $q:pat) => {}; //~ERROR `$p:pat` is followed by `$q:pat` | ^^^^^^ not allowed after `pat` fragments | = note: allowed there are: `=>`, `,`, `=`, `|`, `if` or `in` @@ -86,10 +86,10 @@ LL | ($p:pat $s:stmt) => {}; //~ERROR `$p:pat` is followed by `$s:stmt` | = note: allowed there are: `=>`, `,`, `=`, `|`, `if` or `in` -error: `$p:pat` is followed by `$p:path`, which is not allowed for `pat` fragments +error: `$p:pat` is followed by `$q:path`, which is not allowed for `pat` fragments --> $DIR/macro-follow.rs:19:13 | -LL | ($p:pat $p:path) => {}; //~ERROR `$p:pat` is followed by `$p:path` +LL | ($p:pat $q:path) => {}; //~ERROR `$p:pat` is followed by `$q:path` | ^^^^^^^ not allowed after `pat` fragments | = note: allowed there are: `=>`, `,`, `=`, `|`, `if` or `in` @@ -230,10 +230,10 @@ LL | ($e:expr $p:pat) => {}; //~ERROR `$e:expr` is followed by `$p:pat` | = note: allowed there are: `=>`, `,` or `;` -error: `$e:expr` is followed by `$e:expr`, which is not allowed for `expr` fragments +error: `$e:expr` is followed by `$f:expr`, which is not allowed for `expr` fragments --> $DIR/macro-follow.rs:40:14 | -LL | ($e:expr $e:expr) => {}; //~ERROR `$e:expr` is followed by `$e:expr` +LL | ($e:expr $f:expr) => {}; //~ERROR `$e:expr` is followed by `$f:expr` | ^^^^^^^ not allowed after `expr` fragments | = note: allowed there are: `=>`, `,` or `;` @@ -350,10 +350,10 @@ LL | ($t:ty $e:expr) => {}; //~ERROR `$t:ty` is followed by `$e:expr` | = note: allowed there are: `{`, `[`, `=>`, `,`, `>`, `=`, `:`, `;`, `|`, `as` or `where` -error: `$t:ty` is followed by `$t:ty`, which is not allowed for `ty` fragments +error: `$t:ty` is followed by `$r:ty`, which is not allowed for `ty` fragments --> $DIR/macro-follow.rs:60:12 | -LL | ($t:ty $t:ty) => {}; //~ERROR `$t:ty` is followed by `$t:ty` +LL | ($t:ty $r:ty) => {}; //~ERROR `$t:ty` is followed by `$r:ty` | ^^^^^ not allowed after `ty` fragments | = note: allowed there are: `{`, `[`, `=>`, `,`, `>`, `=`, `:`, `;`, `|`, `as` or `where` @@ -382,10 +382,10 @@ LL | ($t:ty $i:ident) => {}; //~ERROR `$t:ty` is followed by `$i:ident` | = note: allowed there are: `{`, `[`, `=>`, `,`, `>`, `=`, `:`, `;`, `|`, `as` or `where` -error: `$t:ty` is followed by `$t:tt`, which is not allowed for `ty` fragments +error: `$t:ty` is followed by `$r:tt`, which is not allowed for `ty` fragments --> $DIR/macro-follow.rs:65:12 | -LL | ($t:ty $t:tt) => {}; //~ERROR `$t:ty` is followed by `$t:tt` +LL | ($t:ty $r:tt) => {}; //~ERROR `$t:ty` is followed by `$r:tt` | ^^^^^ not allowed after `ty` fragments | = note: allowed there are: `{`, `[`, `=>`, `,`, `>`, `=`, `:`, `;`, `|`, `as` or `where` @@ -518,10 +518,10 @@ LL | ($s:stmt $t:ty) => {}; //~ERROR `$s:stmt` is followed by `$t:ty` | = note: allowed there are: `=>`, `,` or `;` -error: `$s:stmt` is followed by `$s:stmt`, which is not allowed for `stmt` fragments +error: `$s:stmt` is followed by `$t:stmt`, which is not allowed for `stmt` fragments --> $DIR/macro-follow.rs:85:14 | -LL | ($s:stmt $s:stmt) => {}; //~ERROR `$s:stmt` is followed by `$s:stmt` +LL | ($s:stmt $t:stmt) => {}; //~ERROR `$s:stmt` is followed by `$t:stmt` | ^^^^^^^ not allowed after `stmt` fragments | = note: allowed there are: `=>`, `,` or `;` @@ -606,10 +606,10 @@ LL | ($p:path if) => {}; //~ERROR `$p:path` is followed by `if` | = note: allowed there are: `{`, `[`, `=>`, `,`, `>`, `=`, `:`, `;`, `|`, `as` or `where` -error: `$p:path` is followed by `$p:pat`, which is not allowed for `path` fragments +error: `$p:path` is followed by `$q:pat`, which is not allowed for `path` fragments --> $DIR/macro-follow.rs:100:14 | -LL | ($p:path $p:pat) => {}; //~ERROR `$p:path` is followed by `$p:pat` +LL | ($p:path $q:pat) => {}; //~ERROR `$p:path` is followed by `$q:pat` | ^^^^^^ not allowed after `path` fragments | = note: allowed there are: `{`, `[`, `=>`, `,`, `>`, `=`, `:`, `;`, `|`, `as` or `where` @@ -638,10 +638,10 @@ LL | ($p:path $s:stmt) => {}; //~ERROR `$p:path` is followed by `$s:stmt` | = note: allowed there are: `{`, `[`, `=>`, `,`, `>`, `=`, `:`, `;`, `|`, `as` or `where` -error: `$p:path` is followed by `$p:path`, which is not allowed for `path` fragments +error: `$p:path` is followed by `$q:path`, which is not allowed for `path` fragments --> $DIR/macro-follow.rs:104:14 | -LL | ($p:path $p:path) => {}; //~ERROR `$p:path` is followed by `$p:path` +LL | ($p:path $q:path) => {}; //~ERROR `$p:path` is followed by `$q:path` | ^^^^^^^ not allowed after `path` fragments | = note: allowed there are: `{`, `[`, `=>`, `,`, `>`, `=`, `:`, `;`, `|`, `as` or `where` diff --git a/src/test/ui/macros/macro-multiple-matcher-bindings.rs b/src/test/ui/macros/macro-multiple-matcher-bindings.rs new file mode 100644 index 00000000000..9e0fa388716 --- /dev/null +++ b/src/test/ui/macros/macro-multiple-matcher-bindings.rs @@ -0,0 +1,25 @@ +// Test that duplicate matcher binding names are caught at declaration time, rather than at macro +// invocation time. +// +// FIXME(mark-i-m): Update this when it becomes a hard error. + +// compile-pass + +#![allow(unused_macros)] + +macro_rules! foo1 { + ($a:ident, $a:ident) => {}; //~WARNING duplicate matcher binding + ($a:ident, $a:path) => {}; //~WARNING duplicate matcher binding +} + +macro_rules! foo2 { + ($a:ident) => {}; // OK + ($a:path) => {}; // OK +} + +macro_rules! foo3 { + ($a:ident, $($a:ident),*) => {}; //~WARNING duplicate matcher binding + ($($a:ident)+ # $($($a:path),+);*) => {}; //~WARNING duplicate matcher binding +} + +fn main() {} diff --git a/src/test/ui/macros/macro-multiple-matcher-bindings.stderr b/src/test/ui/macros/macro-multiple-matcher-bindings.stderr new file mode 100644 index 00000000000..bc78b471a2d --- /dev/null +++ b/src/test/ui/macros/macro-multiple-matcher-bindings.stderr @@ -0,0 +1,37 @@ +warning: duplicate matcher binding + --> $DIR/macro-multiple-matcher-bindings.rs:11:6 + | +LL | ($a:ident, $a:ident) => {}; //~WARNING duplicate matcher binding + | ^^^^^^^^ ^^^^^^^^ + | + = note: #[warn(duplicate_matcher_binding_name)] on by default + = 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 #57593 + +warning: duplicate matcher binding + --> $DIR/macro-multiple-matcher-bindings.rs:12:6 + | +LL | ($a:ident, $a:path) => {}; //~WARNING duplicate matcher binding + | ^^^^^^^^ ^^^^^^^ + | + = 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 #57593 + +warning: duplicate matcher binding + --> $DIR/macro-multiple-matcher-bindings.rs:21:6 + | +LL | ($a:ident, $($a:ident),*) => {}; //~WARNING duplicate matcher binding + | ^^^^^^^^ ^^^^^^^^ + | + = 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 #57593 + +warning: duplicate matcher binding + --> $DIR/macro-multiple-matcher-bindings.rs:22:8 + | +LL | ($($a:ident)+ # $($($a:path),+);*) => {}; //~WARNING duplicate matcher binding + | ^^^^^^^^ ^^^^^^^ + | + = 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 #57593 + diff --git a/src/test/ui/methods/method-deref-to-same-trait-object-with-separate-params.rs b/src/test/ui/methods/method-deref-to-same-trait-object-with-separate-params.rs new file mode 100644 index 00000000000..a5dae1c71cd --- /dev/null +++ b/src/test/ui/methods/method-deref-to-same-trait-object-with-separate-params.rs @@ -0,0 +1,177 @@ +#![feature(arbitrary_self_types, coerce_unsized, dispatch_from_dyn, unsize, unsized_locals)] + +// This tests a few edge-cases around `arbitrary_self_types`. Most specifically, +// it checks that the `ObjectCandidate` you get from method matching can't +// match a trait with the same DefId as a supertrait but a bad type parameter. + +use std::marker::PhantomData; + +mod internal { + use std::ops::{CoerceUnsized, Deref, DispatchFromDyn}; + use std::marker::{PhantomData, Unsize}; + + pub struct Smaht(pub Box, pub PhantomData); + + impl Deref for Smaht { + type Target = T; + + fn deref(&self) -> &Self::Target { + &self.0 + } + } + impl, U: ?Sized, MISC> CoerceUnsized> + for Smaht + {} + impl, U: ?Sized, MISC> DispatchFromDyn> + for Smaht + {} + + pub trait Foo: X {} + pub trait X { + fn foo(self: Smaht) -> T; + } + + impl X for () { + fn foo(self: Smaht) -> u32 { + 0 + } + } + + pub trait Marker {} + impl Marker for dyn Foo {} + impl X for T { + fn foo(self: Smaht) -> u64 { + 1 + } + } + + impl Deref for dyn Foo { + type Target = (); + fn deref(&self) -> &() { &() } + } + + impl Foo for () {} +} + +pub trait FinalFoo { + fn foo(&self) -> u8; +} + +impl FinalFoo for () { + fn foo(&self) -> u8 { 0 } +} + +mod nuisance_foo { + pub trait NuisanceFoo { + fn foo(self); + } + + impl NuisanceFoo for T { + fn foo(self) {} + } +} + + +fn objectcandidate_impl() { + let x: internal::Smaht<(), u32> = internal::Smaht(Box::new(()), PhantomData); + let x: internal::Smaht = x; + + // This picks `>::foo` via `ObjectCandidate`. + // + // The `TraitCandidate` is not relevant because `X` is not in scope. + let z = x.foo(); + + // Observe the type of `z` is `u32` + let _seetype: () = z; //~ ERROR mismatched types + //~| expected (), found u32 +} + +fn traitcandidate_impl() { + use internal::X; + + let x: internal::Smaht<(), u64> = internal::Smaht(Box::new(()), PhantomData); + let x: internal::Smaht = x; + + // This picks `>::foo` via `TraitCandidate`. + // + // The `ObjectCandidate` does not apply, as it only applies to + // `X` (and not `X`). + let z = x.foo(); + + // Observe the type of `z` is `u64` + let _seetype: () = z; //~ ERROR mismatched types + //~| expected (), found u64 +} + +fn traitcandidate_impl_with_nuisance() { + use internal::X; + use nuisance_foo::NuisanceFoo; + + let x: internal::Smaht<(), u64> = internal::Smaht(Box::new(()), PhantomData); + let x: internal::Smaht = x; + + // This picks `>::foo` via `TraitCandidate`. + // + // The `ObjectCandidate` does not apply, as it only applies to + // `X` (and not `X`). + // + // The NuisanceFoo impl has the same priority as the `X` impl, + // so we get a conflict. + let z = x.foo(); //~ ERROR multiple applicable items in scope +} + + +fn neither_impl() { + let x: internal::Smaht<(), u64> = internal::Smaht(Box::new(()), PhantomData); + let x: internal::Smaht = x; + + // This can't pick the `TraitCandidate` impl, because `Foo` is not + // imported. However, this also can't pick the `ObjectCandidate` + // impl, because it only applies to `X` (and not `X`). + // + // Therefore, neither of the candidates is applicable, and we pick + // the `FinalFoo` impl after another deref, which will return `u8`. + let z = x.foo(); + + // Observe the type of `z` is `u8` + let _seetype: () = z; //~ ERROR mismatched types + //~| expected (), found u8 +} + +fn both_impls() { + use internal::X; + + let x: internal::Smaht<(), u32> = internal::Smaht(Box::new(()), PhantomData); + let x: internal::Smaht = x; + + // This can pick both the `TraitCandidate` and the `ObjectCandidate` impl. + // + // However, the `ObjectCandidate` is considered an "inherent candidate", + // and therefore has priority over both the `TraitCandidate` as well as + // any other "nuisance" candidate" (if present). + let z = x.foo(); + + // Observe the type of `z` is `u32` + let _seetype: () = z; //~ ERROR mismatched types + //~| expected (), found u32 +} + + +fn both_impls_with_nuisance() { + // Similar to the `both_impls` example, except with a nuisance impl to + // make sure the `ObjectCandidate` indeed has a higher priority. + + use internal::X; + use nuisance_foo::NuisanceFoo; + + let x: internal::Smaht<(), u32> = internal::Smaht(Box::new(()), PhantomData); + let x: internal::Smaht = x; + let z = x.foo(); + + // Observe the type of `z` is `u32` + let _seetype: () = z; //~ ERROR mismatched types + //~| expected (), found u32 +} + +fn main() { +} diff --git a/src/test/ui/methods/method-deref-to-same-trait-object-with-separate-params.stderr b/src/test/ui/methods/method-deref-to-same-trait-object-with-separate-params.stderr new file mode 100644 index 00000000000..2d8449b96de --- /dev/null +++ b/src/test/ui/methods/method-deref-to-same-trait-object-with-separate-params.stderr @@ -0,0 +1,72 @@ +error[E0308]: mismatched types + --> $DIR/method-deref-to-same-trait-object-with-separate-params.rs:85:24 + | +LL | let _seetype: () = z; //~ ERROR mismatched types + | ^ expected (), found u32 + | + = note: expected type `()` + found type `u32` + +error[E0308]: mismatched types + --> $DIR/method-deref-to-same-trait-object-with-separate-params.rs:102:24 + | +LL | let _seetype: () = z; //~ ERROR mismatched types + | ^ expected (), found u64 + | + = note: expected type `()` + found type `u64` + +error[E0034]: multiple applicable items in scope + --> $DIR/method-deref-to-same-trait-object-with-separate-params.rs:120:15 + | +LL | let z = x.foo(); //~ ERROR multiple applicable items in scope + | ^^^ multiple `foo` found + | +note: candidate #1 is defined in an impl of the trait `internal::X` for the type `_` + --> $DIR/method-deref-to-same-trait-object-with-separate-params.rs:43:9 + | +LL | fn foo(self: Smaht) -> u64 { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: candidate #2 is defined in an impl of the trait `nuisance_foo::NuisanceFoo` for the type `_` + --> $DIR/method-deref-to-same-trait-object-with-separate-params.rs:70:9 + | +LL | fn foo(self) {} + | ^^^^^^^^^^^^ +note: candidate #3 is defined in the trait `FinalFoo` + --> $DIR/method-deref-to-same-trait-object-with-separate-params.rs:57:5 + | +LL | fn foo(&self) -> u8; + | ^^^^^^^^^^^^^^^^^^^^ + = help: to disambiguate the method call, write `FinalFoo::foo(x)` instead + +error[E0308]: mismatched types + --> $DIR/method-deref-to-same-trait-object-with-separate-params.rs:137:24 + | +LL | let _seetype: () = z; //~ ERROR mismatched types + | ^ expected (), found u8 + | + = note: expected type `()` + found type `u8` + +error[E0308]: mismatched types + --> $DIR/method-deref-to-same-trait-object-with-separate-params.rs:155:24 + | +LL | let _seetype: () = z; //~ ERROR mismatched types + | ^ expected (), found u32 + | + = note: expected type `()` + found type `u32` + +error[E0308]: mismatched types + --> $DIR/method-deref-to-same-trait-object-with-separate-params.rs:172:24 + | +LL | let _seetype: () = z; //~ ERROR mismatched types + | ^ expected (), found u32 + | + = note: expected type `()` + found type `u32` + +error: aborting due to 6 previous errors + +Some errors occurred: E0034, E0308. +For more information about an error, try `rustc --explain E0034`. diff --git a/src/test/ui/methods/method-trait-object-with-hrtb.rs b/src/test/ui/methods/method-trait-object-with-hrtb.rs new file mode 100644 index 00000000000..da2f13f5a2f --- /dev/null +++ b/src/test/ui/methods/method-trait-object-with-hrtb.rs @@ -0,0 +1,41 @@ +// compile-pass + +// Check that method probing ObjectCandidate works in the presence of +// auto traits and/or HRTBs. + +mod internal { + pub trait MyObject<'a> { + type Output; + + fn foo(&self) -> Self::Output; + } + + impl<'a> MyObject<'a> for () { + type Output = &'a u32; + + fn foo(&self) -> Self::Output { &4 } + } +} + +fn t1(d: &dyn for<'a> internal::MyObject<'a, Output=&'a u32>) { + d.foo(); +} + +fn t2(d: &dyn internal::MyObject<'static, Output=&'static u32>) { + d.foo(); +} + +fn t3(d: &(dyn for<'a> internal::MyObject<'a, Output=&'a u32> + Sync)) { + d.foo(); +} + +fn t4(d: &(dyn internal::MyObject<'static, Output=&'static u32> + Sync)) { + d.foo(); +} + +fn main() { + t1(&()); + t2(&()); + t3(&()); + t4(&()); +} diff --git a/src/test/ui/nested-ty-params.rs b/src/test/ui/nested-ty-params.rs index 102f8d02ee4..85413acdb14 100644 --- a/src/test/ui/nested-ty-params.rs +++ b/src/test/ui/nested-ty-params.rs @@ -1,4 +1,4 @@ -// error-pattern:can't use type parameters from outer function +// error-pattern:can't use generic parameters from outer function fn hd(v: Vec ) -> U { fn hd1(w: [U]) -> U { return w[0]; } diff --git a/src/test/ui/nested-ty-params.stderr b/src/test/ui/nested-ty-params.stderr index 617eddf6525..37adeffb9b0 100644 --- a/src/test/ui/nested-ty-params.stderr +++ b/src/test/ui/nested-ty-params.stderr @@ -1,22 +1,22 @@ -error[E0401]: can't use type parameters from outer function +error[E0401]: can't use generic parameters from outer function --> $DIR/nested-ty-params.rs:3:16 | LL | fn hd(v: Vec ) -> U { | - type variable from outer function LL | fn hd1(w: [U]) -> U { return w[0]; } - | --- ^ use of type variable from outer function + | --- ^ use of generic parameter from outer function | | - | help: try using a local type parameter instead: `hd1` + | help: try using a local generic parameter instead: `hd1` -error[E0401]: can't use type parameters from outer function +error[E0401]: can't use generic parameters from outer function --> $DIR/nested-ty-params.rs:3:23 | LL | fn hd(v: Vec ) -> U { | - type variable from outer function LL | fn hd1(w: [U]) -> U { return w[0]; } - | --- ^ use of type variable from outer function + | --- ^ use of generic parameter from outer function | | - | help: try using a local type parameter instead: `hd1` + | help: try using a local generic parameter instead: `hd1` error: aborting due to 2 previous errors diff --git a/src/test/ui/nll/issue-57960.rs b/src/test/ui/nll/issue-57960.rs new file mode 100644 index 00000000000..0b52e46c459 --- /dev/null +++ b/src/test/ui/nll/issue-57960.rs @@ -0,0 +1,39 @@ +// run-pass + +#![allow(dead_code)] + +trait Range { + const FIRST: u8; + const LAST: u8; +} + +struct OneDigit; +impl Range for OneDigit { + const FIRST: u8 = 0; + const LAST: u8 = 9; +} + +struct TwoDigits; +impl Range for TwoDigits { + const FIRST: u8 = 10; + const LAST: u8 = 99; +} + +struct ThreeDigits; +impl Range for ThreeDigits { + const FIRST: u8 = 100; + const LAST: u8 = 255; +} + +fn digits(x: u8) -> u32 { + match x { + OneDigit::FIRST...OneDigit::LAST => 1, + TwoDigits::FIRST...TwoDigits::LAST => 2, + ThreeDigits::FIRST...ThreeDigits::LAST => 3, + _ => unreachable!(), + } +} + +fn main() { + assert_eq!(digits(100), 3); +} diff --git a/src/test/ui/parser-recovery-2.stderr b/src/test/ui/parser-recovery-2.stderr index 92d8cbc100a..76f7af38e77 100644 --- a/src/test/ui/parser-recovery-2.stderr +++ b/src/test/ui/parser-recovery-2.stderr @@ -1,3 +1,9 @@ +error: unexpected token: `;` + --> $DIR/parser-recovery-2.rs:12:15 + | +LL | let x = y.; //~ ERROR unexpected token + | ^ + error: incorrect close delimiter: `)` --> $DIR/parser-recovery-2.rs:8:5 | @@ -7,12 +13,6 @@ LL | let x = foo(); //~ ERROR cannot find function `foo` in this scope LL | ) //~ ERROR incorrect close delimiter: `)` | ^ incorrect close delimiter -error: unexpected token: `;` - --> $DIR/parser-recovery-2.rs:12:15 - | -LL | let x = y.; //~ ERROR unexpected token - | ^ - error[E0425]: cannot find function `foo` in this scope --> $DIR/parser-recovery-2.rs:7:17 | diff --git a/src/test/ui/parser/bounds-lifetime.rs b/src/test/ui/parser/bounds-lifetime.rs index 89a969bb2e2..9225cfce94e 100644 --- a/src/test/ui/parser/bounds-lifetime.rs +++ b/src/test/ui/parser/bounds-lifetime.rs @@ -6,6 +6,6 @@ type A = for<'a: 'b,> fn(); // OK(rejected later by ast_validation) type A = for<'a: 'b +> fn(); // OK (rejected later by ast_validation) type A = for<'a, T> fn(); // OK (rejected later by ast_validation) -type A = for<,> fn(); //~ ERROR expected one of `>`, identifier, or lifetime, found `,` +type A = for<,> fn(); //~ ERROR expected one of `>`, `const`, identifier, or lifetime, found `,` fn main() {} diff --git a/src/test/ui/parser/bounds-lifetime.stderr b/src/test/ui/parser/bounds-lifetime.stderr index f39e5beb6ac..191ea3ebd07 100644 --- a/src/test/ui/parser/bounds-lifetime.stderr +++ b/src/test/ui/parser/bounds-lifetime.stderr @@ -1,8 +1,8 @@ -error: expected one of `>`, identifier, or lifetime, found `,` +error: expected one of `>`, `const`, identifier, or lifetime, found `,` --> $DIR/bounds-lifetime.rs:9:14 | -LL | type A = for<,> fn(); //~ ERROR expected one of `>`, identifier, or lifetime, found `,` - | ^ expected one of `>`, identifier, or lifetime here +LL | type A = for<,> fn(); //~ ERROR expected one of `>`, `const`, identifier, or lifetime, found `,` + | ^ expected one of `>`, `const`, identifier, or lifetime here error: aborting due to previous error diff --git a/src/test/ui/parser/issue-10636-2.rs b/src/test/ui/parser/issue-10636-2.rs index a02fd41b349..6fb63639d5f 100644 --- a/src/test/ui/parser/issue-10636-2.rs +++ b/src/test/ui/parser/issue-10636-2.rs @@ -5,7 +5,7 @@ pub fn trace_option(option: Option) { option.map(|some| 42; //~^ ERROR: expected one of -} //~ ERROR: incorrect close delimiter +} //~^ ERROR: expected expression, found `)` fn main() {} diff --git a/src/test/ui/parser/issue-10636-2.stderr b/src/test/ui/parser/issue-10636-2.stderr index 9b3115cb3f4..38d57ce5723 100644 --- a/src/test/ui/parser/issue-10636-2.stderr +++ b/src/test/ui/parser/issue-10636-2.stderr @@ -1,25 +1,17 @@ -error: incorrect close delimiter: `}` - --> $DIR/issue-10636-2.rs:8:1 - | -LL | pub fn trace_option(option: Option) { - | - close delimiter possibly meant for this -LL | option.map(|some| 42; - | - un-closed delimiter -... -LL | } //~ ERROR: incorrect close delimiter - | ^ incorrect close delimiter - error: expected one of `)`, `,`, `.`, `?`, or an operator, found `;` --> $DIR/issue-10636-2.rs:5:25 | LL | option.map(|some| 42; - | ^ expected one of `)`, `,`, `.`, `?`, or an operator here + | - ^ + | | | + | | help: `)` may belong here + | unclosed delimiter error: expected expression, found `)` --> $DIR/issue-10636-2.rs:8:1 | -LL | } //~ ERROR: incorrect close delimiter +LL | } | ^ expected expression -error: aborting due to 3 previous errors +error: aborting due to 2 previous errors diff --git a/src/test/ui/parser/issue-14303-enum.stderr b/src/test/ui/parser/issue-14303-enum.stderr index a31429e7228..bcecd75b1ab 100644 --- a/src/test/ui/parser/issue-14303-enum.stderr +++ b/src/test/ui/parser/issue-14303-enum.stderr @@ -2,11 +2,7 @@ error: lifetime parameters must be declared prior to type parameters --> $DIR/issue-14303-enum.rs:1:15 | LL | enum X<'a, T, 'b> { - | ^^ -help: move the lifetime parameter prior to the first type parameter - | -LL | enum X<'a, 'b, T> { - | ^^^ -- + | --------^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, 'b, T>` error: aborting due to previous error diff --git a/src/test/ui/parser/issue-14303-fn-def.stderr b/src/test/ui/parser/issue-14303-fn-def.stderr index 4582aeef428..082c37e0be7 100644 --- a/src/test/ui/parser/issue-14303-fn-def.stderr +++ b/src/test/ui/parser/issue-14303-fn-def.stderr @@ -2,11 +2,7 @@ error: lifetime parameters must be declared prior to type parameters --> $DIR/issue-14303-fn-def.rs:1:15 | LL | fn foo<'a, T, 'b>(x: &'a T) {} - | ^^ -help: move the lifetime parameter prior to the first type parameter - | -LL | fn foo<'a, 'b, T>(x: &'a T) {} - | ^^^ -- + | --------^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, 'b, T>` error: aborting due to previous error diff --git a/src/test/ui/parser/issue-14303-fncall.rs b/src/test/ui/parser/issue-14303-fncall.rs index 17b9b766b21..39694198cdb 100644 --- a/src/test/ui/parser/issue-14303-fncall.rs +++ b/src/test/ui/parser/issue-14303-fncall.rs @@ -11,7 +11,7 @@ fn foo<'a, 'b>(start: &'a usize, end: &'a usize) { let _x = (*start..*end) .map(|x| S { a: start, b: end }) .collect::>>(); - //~^ ERROR lifetime parameters must be declared prior to type parameters + //~^ ERROR lifetime arguments must be declared prior to type arguments } fn main() {} diff --git a/src/test/ui/parser/issue-14303-fncall.stderr b/src/test/ui/parser/issue-14303-fncall.stderr index 2a736491594..8ef9f1a1a6c 100644 --- a/src/test/ui/parser/issue-14303-fncall.stderr +++ b/src/test/ui/parser/issue-14303-fncall.stderr @@ -1,12 +1,8 @@ -error: lifetime parameters must be declared prior to type parameters +error: lifetime arguments must be declared prior to type arguments --> $DIR/issue-14303-fncall.rs:13:29 | LL | .collect::>>(); - | ^^ must be declared prior to type parameters -help: move the lifetime parameter prior to the first type parameter - | -LL | .collect::>>(); - | ^^^ -- + | ^^ error: aborting due to previous error diff --git a/src/test/ui/parser/issue-14303-impl.stderr b/src/test/ui/parser/issue-14303-impl.stderr index a1953396153..3b5615d2a9e 100644 --- a/src/test/ui/parser/issue-14303-impl.stderr +++ b/src/test/ui/parser/issue-14303-impl.stderr @@ -2,11 +2,7 @@ error: lifetime parameters must be declared prior to type parameters --> $DIR/issue-14303-impl.rs:3:13 | LL | impl<'a, T, 'b> X {} - | ^^ -help: move the lifetime parameter prior to the first type parameter - | -LL | impl<'a, 'b, T> X {} - | ^^^ -- + | --------^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, 'b, T>` error: aborting due to previous error diff --git a/src/test/ui/parser/issue-14303-path.rs b/src/test/ui/parser/issue-14303-path.rs index a08c89f3437..386d19859e4 100644 --- a/src/test/ui/parser/issue-14303-path.rs +++ b/src/test/ui/parser/issue-14303-path.rs @@ -8,6 +8,6 @@ pub struct X<'a, 'b, 'c, T> { } fn bar<'a, 'b, 'c, T>(x: foo::X<'a, T, 'b, 'c>) {} -//~^ ERROR lifetime parameters must be declared prior to type parameters +//~^ ERROR lifetime arguments must be declared prior to type arguments fn main() {} diff --git a/src/test/ui/parser/issue-14303-path.stderr b/src/test/ui/parser/issue-14303-path.stderr index fb4fb32e11e..19f2995ebee 100644 --- a/src/test/ui/parser/issue-14303-path.stderr +++ b/src/test/ui/parser/issue-14303-path.stderr @@ -1,14 +1,8 @@ -error: lifetime parameters must be declared prior to type parameters +error: lifetime arguments must be declared prior to type arguments --> $DIR/issue-14303-path.rs:10:40 | LL | fn bar<'a, 'b, 'c, T>(x: foo::X<'a, T, 'b, 'c>) {} - | ^^ ^^ must be declared prior to type parameters - | | - | must be declared prior to type parameters -help: move the lifetime parameters prior to the first type parameter - | -LL | fn bar<'a, 'b, 'c, T>(x: foo::X<'a, 'b, 'c, T>) {} - | ^^^ ^^^ -- + | ^^ ^^ error: aborting due to previous error diff --git a/src/test/ui/parser/issue-14303-struct.stderr b/src/test/ui/parser/issue-14303-struct.stderr index 668b8d1de68..dbd0b987dd1 100644 --- a/src/test/ui/parser/issue-14303-struct.stderr +++ b/src/test/ui/parser/issue-14303-struct.stderr @@ -2,11 +2,7 @@ error: lifetime parameters must be declared prior to type parameters --> $DIR/issue-14303-struct.rs:1:17 | LL | struct X<'a, T, 'b> { - | ^^ -help: move the lifetime parameter prior to the first type parameter - | -LL | struct X<'a, 'b, T> { - | ^^^ -- + | --------^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, 'b, T>` error: aborting due to previous error diff --git a/src/test/ui/parser/issue-14303-trait.stderr b/src/test/ui/parser/issue-14303-trait.stderr index 11ce0c44351..7dfa62d823f 100644 --- a/src/test/ui/parser/issue-14303-trait.stderr +++ b/src/test/ui/parser/issue-14303-trait.stderr @@ -2,11 +2,7 @@ error: lifetime parameters must be declared prior to type parameters --> $DIR/issue-14303-trait.rs:1:18 | LL | trait Foo<'a, T, 'b> {} - | ^^ -help: move the lifetime parameter prior to the first type parameter - | -LL | trait Foo<'a, 'b, T> {} - | ^^^ -- + | --------^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, 'b, T>` error: aborting due to previous error diff --git a/src/test/ui/parser/issue-32214.rs b/src/test/ui/parser/issue-32214.rs index 7e55bc038e7..7191a3234c0 100644 --- a/src/test/ui/parser/issue-32214.rs +++ b/src/test/ui/parser/issue-32214.rs @@ -3,6 +3,6 @@ trait Trait { type Item; } pub fn test >() {} -//~^ ERROR type parameters must be declared prior to associated type bindings +//~^ ERROR associated type bindings must be declared after generic parameters fn main() { } diff --git a/src/test/ui/parser/issue-32214.stderr b/src/test/ui/parser/issue-32214.stderr index 660e517c85a..7022019a22f 100644 --- a/src/test/ui/parser/issue-32214.stderr +++ b/src/test/ui/parser/issue-32214.stderr @@ -1,12 +1,10 @@ -error: type parameters must be declared prior to associated type bindings - --> $DIR/issue-32214.rs:5:34 +error: associated type bindings must be declared after generic parameters + --> $DIR/issue-32214.rs:5:25 | LL | pub fn test >() {} - | ^ must be declared prior to associated type bindings -help: move the type parameter prior to the first associated type binding - | -LL | pub fn test >() {} - | ^^ -- + | -------^^^ + | | + | this associated type binding should be moved after the generic parameters error: aborting due to previous error diff --git a/src/test/ui/parser/macro-mismatched-delim-paren-brace.stderr b/src/test/ui/parser/macro-mismatched-delim-paren-brace.stderr index 805ba8b6baa..abb08209795 100644 --- a/src/test/ui/parser/macro-mismatched-delim-paren-brace.stderr +++ b/src/test/ui/parser/macro-mismatched-delim-paren-brace.stderr @@ -1,3 +1,9 @@ +error: unexpected close delimiter: `}` + --> $DIR/macro-mismatched-delim-paren-brace.rs:5:1 + | +LL | } //~ ERROR unexpected close delimiter: `}` + | ^ unexpected close delimiter + error: incorrect close delimiter: `}` --> $DIR/macro-mismatched-delim-paren-brace.rs:4:5 | @@ -7,11 +13,5 @@ LL | bar, "baz", 1, 2.0 LL | } //~ ERROR incorrect close delimiter | ^ incorrect close delimiter -error: unexpected close delimiter: `}` - --> $DIR/macro-mismatched-delim-paren-brace.rs:5:1 - | -LL | } //~ ERROR unexpected close delimiter: `}` - | ^ unexpected close delimiter - error: aborting due to 2 previous errors diff --git a/src/test/ui/parser/removed-syntax-uniq-mut-ty.rs b/src/test/ui/parser/removed-syntax-uniq-mut-ty.rs index 12de76d9d6d..79d51f5595d 100644 --- a/src/test/ui/parser/removed-syntax-uniq-mut-ty.rs +++ b/src/test/ui/parser/removed-syntax-uniq-mut-ty.rs @@ -1 +1 @@ -type mut_box = Box; //~ ERROR expected one of `>`, lifetime, or type, found `mut` +type mut_box = Box; //~ ERROR expected one of `>`, const, lifetime, or type, found `mut` diff --git a/src/test/ui/parser/removed-syntax-uniq-mut-ty.stderr b/src/test/ui/parser/removed-syntax-uniq-mut-ty.stderr index 0177b19d74e..b2759778d03 100644 --- a/src/test/ui/parser/removed-syntax-uniq-mut-ty.stderr +++ b/src/test/ui/parser/removed-syntax-uniq-mut-ty.stderr @@ -1,8 +1,8 @@ -error: expected one of `>`, lifetime, or type, found `mut` +error: expected one of `>`, const, lifetime, or type, found `mut` --> $DIR/removed-syntax-uniq-mut-ty.rs:1:20 | -LL | type mut_box = Box; //~ ERROR expected one of `>`, lifetime, or type, found `mut` - | ^^^ expected one of `>`, lifetime, or type here +LL | type mut_box = Box; //~ ERROR expected one of `>`, const, lifetime, or type, found `mut` + | ^^^ expected one of `>`, const, lifetime, or type here error: aborting due to previous error diff --git a/src/test/ui/resolve/resolve-type-param-in-item-in-trait.rs b/src/test/ui/resolve/resolve-type-param-in-item-in-trait.rs index 112427a3fce..c77a66524f7 100644 --- a/src/test/ui/resolve/resolve-type-param-in-item-in-trait.rs +++ b/src/test/ui/resolve/resolve-type-param-in-item-in-trait.rs @@ -6,7 +6,7 @@ trait TraitA { fn outer(&self) { enum Foo { Variance(A) - //~^ ERROR can't use type parameters from outer function + //~^ ERROR can't use generic parameters from outer function } } } @@ -14,21 +14,21 @@ enum Foo { trait TraitB { fn outer(&self) { struct Foo(A); - //~^ ERROR can't use type parameters from outer function + //~^ ERROR can't use generic parameters from outer function } } trait TraitC { fn outer(&self) { struct Foo { a: A } - //~^ ERROR can't use type parameters from outer function + //~^ ERROR can't use generic parameters from outer function } } trait TraitD { fn outer(&self) { fn foo(a: A) { } - //~^ ERROR can't use type parameters from outer function + //~^ ERROR can't use generic parameters from outer function } } diff --git a/src/test/ui/resolve/resolve-type-param-in-item-in-trait.stderr b/src/test/ui/resolve/resolve-type-param-in-item-in-trait.stderr index 8eca720d88e..f6b8abf4057 100644 --- a/src/test/ui/resolve/resolve-type-param-in-item-in-trait.stderr +++ b/src/test/ui/resolve/resolve-type-param-in-item-in-trait.stderr @@ -1,44 +1,44 @@ -error[E0401]: can't use type parameters from outer function +error[E0401]: can't use generic parameters from outer function --> $DIR/resolve-type-param-in-item-in-trait.rs:8:22 | LL | trait TraitA { | - type variable from outer function LL | fn outer(&self) { - | ----- try adding a local type parameter in this method instead + | ----- try adding a local generic parameter in this method instead LL | enum Foo { LL | Variance(A) - | ^ use of type variable from outer function + | ^ use of generic parameter from outer function -error[E0401]: can't use type parameters from outer function +error[E0401]: can't use generic parameters from outer function --> $DIR/resolve-type-param-in-item-in-trait.rs:16:23 | LL | trait TraitB { | - type variable from outer function LL | fn outer(&self) { - | ----- try adding a local type parameter in this method instead + | ----- try adding a local generic parameter in this method instead LL | struct Foo(A); - | ^ use of type variable from outer function + | ^ use of generic parameter from outer function -error[E0401]: can't use type parameters from outer function +error[E0401]: can't use generic parameters from outer function --> $DIR/resolve-type-param-in-item-in-trait.rs:23:28 | LL | trait TraitC { | - type variable from outer function LL | fn outer(&self) { - | ----- try adding a local type parameter in this method instead + | ----- try adding a local generic parameter in this method instead LL | struct Foo { a: A } - | ^ use of type variable from outer function + | ^ use of generic parameter from outer function -error[E0401]: can't use type parameters from outer function +error[E0401]: can't use generic parameters from outer function --> $DIR/resolve-type-param-in-item-in-trait.rs:30:22 | LL | trait TraitD { | - type variable from outer function LL | fn outer(&self) { LL | fn foo(a: A) { } - | ------ ^ use of type variable from outer function + | ------ ^ use of generic parameter from outer function | | - | help: try using a local type parameter instead: `foo` + | help: try using a local generic parameter instead: `foo` error: aborting due to 4 previous errors diff --git a/src/test/ui/resolve/token-error-correct-3.rs b/src/test/ui/resolve/token-error-correct-3.rs index 86cf71117a6..b1ca0bbfc57 100644 --- a/src/test/ui/resolve/token-error-correct-3.rs +++ b/src/test/ui/resolve/token-error-correct-3.rs @@ -17,7 +17,7 @@ pub fn ensure_dir_exists, F: FnOnce(&Path)>(path: P, //~| expected type `()` //~| found type `std::result::Result` //~| expected one of - } else { //~ ERROR: incorrect close delimiter: `}` + } else { //~^ ERROR: expected one of //~| unexpected token Ok(false); diff --git a/src/test/ui/resolve/token-error-correct-3.stderr b/src/test/ui/resolve/token-error-correct-3.stderr index 2164d27a051..a6bb83c71f3 100644 --- a/src/test/ui/resolve/token-error-correct-3.stderr +++ b/src/test/ui/resolve/token-error-correct-3.stderr @@ -1,19 +1,11 @@ -error: incorrect close delimiter: `}` - --> $DIR/token-error-correct-3.rs:20:9 - | -LL | if !is_directory(path.as_ref()) { //~ ERROR: cannot find function `is_directory` - | - close delimiter possibly meant for this -LL | callback(path.as_ref(); //~ ERROR expected one of - | - un-closed delimiter -... -LL | } else { //~ ERROR: incorrect close delimiter: `}` - | ^ incorrect close delimiter - error: expected one of `)`, `,`, `.`, `?`, or an operator, found `;` --> $DIR/token-error-correct-3.rs:14:35 | LL | callback(path.as_ref(); //~ ERROR expected one of - | ^ expected one of `)`, `,`, `.`, `?`, or an operator here + | - ^ + | | | + | | help: `)` may belong here + | unclosed delimiter error: expected one of `.`, `;`, `?`, `}`, or an operator, found `)` --> $DIR/token-error-correct-3.rs:20:9 @@ -21,7 +13,7 @@ error: expected one of `.`, `;`, `?`, `}`, or an operator, found `)` LL | fs::create_dir_all(path.as_ref()).map(|()| true) //~ ERROR: mismatched types | - expected one of `.`, `;`, `?`, `}`, or an operator here ... -LL | } else { //~ ERROR: incorrect close delimiter: `}` +LL | } else { | ^ unexpected token error[E0425]: cannot find function `is_directory` in this scope @@ -41,7 +33,7 @@ LL | fs::create_dir_all(path.as_ref()).map(|()| true) //~ ERROR: mis = note: expected type `()` found type `std::result::Result` -error: aborting due to 5 previous errors +error: aborting due to 4 previous errors Some errors occurred: E0308, E0425. For more information about an error, try `rustc --explain E0308`. diff --git a/src/test/ui/resolve/token-error-correct.rs b/src/test/ui/resolve/token-error-correct.rs index b97e22f7d91..d64907780ef 100644 --- a/src/test/ui/resolve/token-error-correct.rs +++ b/src/test/ui/resolve/token-error-correct.rs @@ -2,6 +2,8 @@ fn main() { foo(bar(; - //~^ ERROR: expected expression, found `;` + //~^ ERROR cannot find function `bar` in this scope } //~^ ERROR: incorrect close delimiter: `}` + +fn foo(_: usize) {} diff --git a/src/test/ui/resolve/token-error-correct.stderr b/src/test/ui/resolve/token-error-correct.stderr index 0a4590461b5..b0827ea7367 100644 --- a/src/test/ui/resolve/token-error-correct.stderr +++ b/src/test/ui/resolve/token-error-correct.stderr @@ -5,15 +5,16 @@ LL | fn main() { | - close delimiter possibly meant for this LL | foo(bar(; | - un-closed delimiter -LL | //~^ ERROR: expected expression, found `;` +LL | //~^ ERROR cannot find function `bar` in this scope LL | } | ^ incorrect close delimiter -error: expected expression, found `;` - --> $DIR/token-error-correct.rs:4:13 +error[E0425]: cannot find function `bar` in this scope + --> $DIR/token-error-correct.rs:4:9 | LL | foo(bar(; - | ^ expected expression + | ^^^ not found in this scope error: aborting due to 2 previous errors +For more information about this error, try `rustc --explain E0425`. diff --git a/src/test/ui/rfc1598-generic-associated-types/empty_generics.rs b/src/test/ui/rfc1598-generic-associated-types/empty_generics.rs index 158ebc7d388..afc27701920 100644 --- a/src/test/ui/rfc1598-generic-associated-types/empty_generics.rs +++ b/src/test/ui/rfc1598-generic-associated-types/empty_generics.rs @@ -3,7 +3,7 @@ trait Foo { type Bar<,>; - //~^ ERROR expected one of `>`, identifier, or lifetime, found `,` + //~^ ERROR expected one of `>`, `const`, identifier, or lifetime, found `,` } fn main() {} diff --git a/src/test/ui/rfc1598-generic-associated-types/empty_generics.stderr b/src/test/ui/rfc1598-generic-associated-types/empty_generics.stderr index 2a01b2a3f0f..5b98302924e 100644 --- a/src/test/ui/rfc1598-generic-associated-types/empty_generics.stderr +++ b/src/test/ui/rfc1598-generic-associated-types/empty_generics.stderr @@ -1,8 +1,8 @@ -error: expected one of `>`, identifier, or lifetime, found `,` +error: expected one of `>`, `const`, identifier, or lifetime, found `,` --> $DIR/empty_generics.rs:5:14 | LL | type Bar<,>; - | ^ expected one of `>`, identifier, or lifetime here + | ^ expected one of `>`, `const`, identifier, or lifetime here warning: the feature `generic_associated_types` is incomplete and may cause the compiler to crash --> $DIR/empty_generics.rs:1:12 diff --git a/src/test/ui/suggestions/suggest-move-lifetimes.stderr b/src/test/ui/suggestions/suggest-move-lifetimes.stderr index b36e927b5c0..2d6dee06216 100644 --- a/src/test/ui/suggestions/suggest-move-lifetimes.stderr +++ b/src/test/ui/suggestions/suggest-move-lifetimes.stderr @@ -2,41 +2,25 @@ error: lifetime parameters must be declared prior to type parameters --> $DIR/suggest-move-lifetimes.rs:1:13 | LL | struct A { //~ ERROR lifetime parameters must be declared - | ^^ -help: move the lifetime parameter prior to the first type parameter - | -LL | struct A<'a, T> { //~ ERROR lifetime parameters must be declared - | ^^^ -- + | ----^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, T>` error: lifetime parameters must be declared prior to type parameters --> $DIR/suggest-move-lifetimes.rs:5:13 | LL | struct B { //~ ERROR lifetime parameters must be declared - | ^^ -help: move the lifetime parameter prior to the first type parameter - | -LL | struct B<'a, T, U> { //~ ERROR lifetime parameters must be declared - | ^^^ -- + | ----^^---- help: reorder the parameters: lifetimes, then types, then consts: `<'a, T, U>` error: lifetime parameters must be declared prior to type parameters --> $DIR/suggest-move-lifetimes.rs:10:16 | LL | struct C { //~ ERROR lifetime parameters must be declared - | ^^ -help: move the lifetime parameter prior to the first type parameter - | -LL | struct C<'a, T, U> { //~ ERROR lifetime parameters must be declared - | ^^^ -- + | -------^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, T, U>` error: lifetime parameters must be declared prior to type parameters --> $DIR/suggest-move-lifetimes.rs:15:16 | LL | struct D { //~ ERROR lifetime parameters must be declared - | ^^ ^^ ^^ -help: move the lifetime parameter prior to the first type parameter - | -LL | struct D<'a, 'b, 'c, T, U, V> { //~ ERROR lifetime parameters must be declared - | ^^^ ^^^ ^^^ -- -- + | -------^^--^^-----^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, 'b, 'c, T, U, V>` error: aborting due to 4 previous errors diff --git a/src/test/ui/suggestions/suggest-move-types.rs b/src/test/ui/suggestions/suggest-move-types.rs index fd10ba4350c..890950ea08c 100644 --- a/src/test/ui/suggestions/suggest-move-types.rs +++ b/src/test/ui/suggestions/suggest-move-types.rs @@ -25,19 +25,20 @@ trait ThreeWithLifetime<'a, 'b, 'c, T, U, V> { type C; } -struct A> { //~ ERROR type parameters must be declared +struct A> { //~ ERROR associated type bindings must be declared after generic parameters m: M, t: T, } struct Al<'a, T, M: OneWithLifetime> { -//~^ ERROR generic arguments must declare lifetimes, types and associated type bindings in that order +//~^ ERROR associated type bindings must be declared after generic parameters +//~^^ ERROR lifetime arguments must be declared prior to type arguments m: M, t: &'a T, } -struct B> { //~ ERROR type parameters must be declared +struct B> { //~ ERROR associated type bindings must be declared after generic parameters m: M, t: T, u: U, @@ -45,14 +46,15 @@ struct B> { //~ ERROR type paramete } struct Bl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime> { -//~^ ERROR generic arguments must declare lifetimes, types and associated type bindings in that order +//~^ ERROR associated type bindings must be declared after generic parameters +//~^^ ERROR lifetime arguments must be declared prior to type arguments m: M, t: &'a T, u: &'b U, v: &'c V, } -struct C> { //~ ERROR type parameters must be declared +struct C> { //~ ERROR associated type bindings must be declared after generic parameters m: M, t: T, u: U, @@ -60,14 +62,15 @@ struct C> { //~ ERROR type paramete } struct Cl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime> { -//~^ ERROR generic arguments must declare lifetimes, types and associated type bindings in that order +//~^ ERROR associated type bindings must be declared after generic parameters +//~^^ ERROR lifetime arguments must be declared prior to type arguments m: M, t: &'a T, u: &'b U, v: &'c V, } -struct D> { //~ ERROR type parameters must be declared +struct D> { //~ ERROR associated type bindings must be declared after generic parameters m: M, t: T, u: U, @@ -75,7 +78,8 @@ struct D> { //~ ERROR type paramete } struct Dl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime> { -//~^ ERROR generic arguments must declare lifetimes, types and associated type bindings in that order +//~^ ERROR associated type bindings must be declared after generic parameters +//~^^ ERROR lifetime arguments must be declared prior to type arguments m: M, t: &'a T, u: &'b U, diff --git a/src/test/ui/suggestions/suggest-move-types.stderr b/src/test/ui/suggestions/suggest-move-types.stderr index 3643d9a9124..0901b71911d 100644 --- a/src/test/ui/suggestions/suggest-move-types.stderr +++ b/src/test/ui/suggestions/suggest-move-types.stderr @@ -1,107 +1,102 @@ -error: type parameters must be declared prior to associated type bindings - --> $DIR/suggest-move-types.rs:28:26 +error: associated type bindings must be declared after generic parameters + --> $DIR/suggest-move-types.rs:28:20 | -LL | struct A> { //~ ERROR type parameters must be declared - | ^ must be declared prior to associated type bindings -help: move the type parameter prior to the first associated type binding - | -LL | struct A> { //~ ERROR type parameters must be declared - | ^^ -- +LL | struct A> { //~ ERROR associated type bindings must be declared after generic parameters + | ----^^^ + | | + | this associated type binding should be moved after the generic parameters -error: generic arguments must declare lifetimes, types and associated type bindings in that order - --> $DIR/suggest-move-types.rs:34:46 +error: associated type bindings must be declared after generic parameters + --> $DIR/suggest-move-types.rs:34:37 | LL | struct Al<'a, T, M: OneWithLifetime> { - | ^ ^^ must be declared prior to type parameters - | | - | must be declared prior to associated type bindings -help: move the parameters - | -LL | struct Al<'a, T, M: OneWithLifetime<'a, T, A=()>> { - | ^^^ ^^ -- + | ----^^^^^^^ + | | + | this associated type binding should be moved after the generic parameters -error: type parameters must be declared prior to associated type bindings - --> $DIR/suggest-move-types.rs:40:46 - | -LL | struct B> { //~ ERROR type parameters must be declared - | ^ ^ ^ must be declared prior to associated type bindings - | | | - | | must be declared prior to associated type bindings - | must be declared prior to associated type bindings -help: move the type parameters prior to the first associated type binding - | -LL | struct B> { //~ ERROR type parameters must be declared - | ^^ ^^ ^^ -- +error: associated type bindings must be declared after generic parameters + --> $DIR/suggest-move-types.rs:41:28 + | +LL | struct B> { //~ ERROR associated type bindings must be declared after generic parameters + | ----^^----^^----^^^^^^^^^ + | | | | + | | | this associated type binding should be moved after the generic parameters + | | this associated type binding should be moved after the generic parameters + | this associated type binding should be moved after the generic parameters -error: generic arguments must declare lifetimes, types and associated type bindings in that order - --> $DIR/suggest-move-types.rs:47:80 +error: associated type bindings must be declared after generic parameters + --> $DIR/suggest-move-types.rs:48:53 | LL | struct Bl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime> { - | ^ ^ ^ ^^ ^^ ^^ must be declared prior to type parameters - | | | | | | - | | | | | must be declared prior to type parameters - | | | | must be declared prior to type parameters - | | | must be declared prior to associated type bindings - | | must be declared prior to associated type bindings - | must be declared prior to associated type bindings -help: move the parameters - | -LL | struct Bl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime<'a, 'b, 'c, T, U, V, A=(), B=(), C=()>> { - | ^^^ ^^^ ^^^ ^^ ^^ ^^ -- + | ----^^----^^----^^^^^^^^^^^^^^^^^^^^^ + | | | | + | | | this associated type binding should be moved after the generic parameters + | | this associated type binding should be moved after the generic parameters + | this associated type binding should be moved after the generic parameters -error: type parameters must be declared prior to associated type bindings - --> $DIR/suggest-move-types.rs:55:49 - | -LL | struct C> { //~ ERROR type parameters must be declared - | ^ ^ must be declared prior to associated type bindings - | | - | must be declared prior to associated type bindings -help: move the type parameters prior to the first associated type binding - | -LL | struct C> { //~ ERROR type parameters must be declared - | ^^ ^^ -- +error: associated type bindings must be declared after generic parameters + --> $DIR/suggest-move-types.rs:57:28 + | +LL | struct C> { //~ ERROR associated type bindings must be declared after generic parameters + | ^^^----^^----^^----^^^^^^ + | | | | + | | | this associated type binding should be moved after the generic parameters + | | this associated type binding should be moved after the generic parameters + | this associated type binding should be moved after the generic parameters -error: generic arguments must declare lifetimes, types and associated type bindings in that order - --> $DIR/suggest-move-types.rs:62:56 +error: associated type bindings must be declared after generic parameters + --> $DIR/suggest-move-types.rs:64:53 | LL | struct Cl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime> { - | ^^ ^ ^^ ^ ^^ must be declared prior to type parameters - | | | | | - | | | | must be declared prior to associated type bindings - | | | must be declared prior to type parameters - | | must be declared prior to associated type bindings - | must be declared prior to type parameters -help: move the parameters + | ^^^^^^^----^^----^^----^^^^^^^^^^^^^^ + | | | | + | | | this associated type binding should be moved after the generic parameters + | | this associated type binding should be moved after the generic parameters + | this associated type binding should be moved after the generic parameters + +error: associated type bindings must be declared after generic parameters + --> $DIR/suggest-move-types.rs:73:28 + | +LL | struct D> { //~ ERROR associated type bindings must be declared after generic parameters + | ^^^----^^----^^^^^----^^^ + | | | | + | | | this associated type binding should be moved after the generic parameters + | | this associated type binding should be moved after the generic parameters + | this associated type binding should be moved after the generic parameters + +error: associated type bindings must be declared after generic parameters + --> $DIR/suggest-move-types.rs:80:53 | -LL | struct Cl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime<'a, 'b, 'c, T, U, V, A=(), B=(), C=()>> { - | ^^^ ^^^ ^^^ -- ^^ ^^ -- +LL | struct Dl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime> { + | ^^^^^^^----^^----^^^^^^^^^----^^^^^^^ + | | | | + | | | this associated type binding should be moved after the generic parameters + | | this associated type binding should be moved after the generic parameters + | this associated type binding should be moved after the generic parameters -error: type parameters must be declared prior to associated type bindings - --> $DIR/suggest-move-types.rs:70:43 +error: lifetime arguments must be declared prior to type arguments + --> $DIR/suggest-move-types.rs:34:46 | -LL | struct D> { //~ ERROR type parameters must be declared - | ^ ^ must be declared prior to associated type bindings - | | - | must be declared prior to associated type bindings -help: move the type parameters prior to the first associated type binding +LL | struct Al<'a, T, M: OneWithLifetime> { + | ^^ + +error: lifetime arguments must be declared prior to type arguments + --> $DIR/suggest-move-types.rs:48:80 | -LL | struct D> { //~ ERROR type parameters must be declared - | ^^ ^^ -- -- +LL | struct Bl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime> { + | ^^ ^^ ^^ -error: generic arguments must declare lifetimes, types and associated type bindings in that order - --> $DIR/suggest-move-types.rs:77:56 +error: lifetime arguments must be declared prior to type arguments + --> $DIR/suggest-move-types.rs:64:56 | -LL | struct Dl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime> { - | ^^ ^ ^^ ^ ^^ must be declared prior to type parameters - | | | | | - | | | | must be declared prior to associated type bindings - | | | must be declared prior to type parameters - | | must be declared prior to associated type bindings - | must be declared prior to type parameters -help: move the parameters +LL | struct Cl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime> { + | ^^ ^^ ^^ + +error: lifetime arguments must be declared prior to type arguments + --> $DIR/suggest-move-types.rs:80:56 | -LL | struct Dl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime<'a, 'b, 'c, T, U, V, A=(), B=(), C=()>> { - | ^^^ ^^^ ^^^ -- ^^ ^^ -- -- +LL | struct Dl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime> { + | ^^ ^^ ^^ -error: aborting due to 8 previous errors +error: aborting due to 12 previous errors diff --git a/src/test/ui/traits/trait-object-vs-lifetime.rs b/src/test/ui/traits/trait-object-vs-lifetime.rs index a12429c868e..36dec21be05 100644 --- a/src/test/ui/traits/trait-object-vs-lifetime.rs +++ b/src/test/ui/traits/trait-object-vs-lifetime.rs @@ -12,6 +12,6 @@ fn main() { //~^ ERROR wrong number of lifetime arguments: expected 1, found 2 //~| ERROR wrong number of type arguments: expected 1, found 0 let _: S<'static +, 'static>; - //~^ ERROR lifetime parameters must be declared prior to type parameters + //~^ ERROR lifetime arguments must be declared prior to type arguments //~| ERROR at least one non-builtin 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 4cc96bae5cd..e0c52a72a09 100644 --- a/src/test/ui/traits/trait-object-vs-lifetime.stderr +++ b/src/test/ui/traits/trait-object-vs-lifetime.stderr @@ -1,12 +1,8 @@ -error: lifetime parameters must be declared prior to type parameters +error: lifetime arguments must be declared prior to type arguments --> $DIR/trait-object-vs-lifetime.rs:14:25 | LL | let _: S<'static +, 'static>; - | ^^^^^^^ must be declared prior to type parameters -help: move the lifetime parameter prior to the first type parameter - | -LL | let _: S<'static, 'static +>; - | ^^^^^^^^ -- + | ^^^^^^^ error[E0224]: at least one non-builtin trait is required for an object type --> $DIR/trait-object-vs-lifetime.rs:9:23 diff --git a/src/test/ui/type/type-arg-out-of-scope.rs b/src/test/ui/type/type-arg-out-of-scope.rs index b96c9bf6a0e..d5b815f6a95 100644 --- a/src/test/ui/type/type-arg-out-of-scope.rs +++ b/src/test/ui/type/type-arg-out-of-scope.rs @@ -1,4 +1,4 @@ -// error-pattern:can't use type parameters from outer function +// error-pattern:can't use generic parameters from outer function fn foo(x: T) { fn bar(f: Box T>) { } } diff --git a/src/test/ui/type/type-arg-out-of-scope.stderr b/src/test/ui/type/type-arg-out-of-scope.stderr index 62b6a86662d..645cbb33abe 100644 --- a/src/test/ui/type/type-arg-out-of-scope.stderr +++ b/src/test/ui/type/type-arg-out-of-scope.stderr @@ -1,22 +1,22 @@ -error[E0401]: can't use type parameters from outer function +error[E0401]: can't use generic parameters from outer function --> $DIR/type-arg-out-of-scope.rs:3:25 | LL | fn foo(x: T) { | - type variable from outer function LL | fn bar(f: Box T>) { } - | --- ^ use of type variable from outer function + | --- ^ use of generic parameter from outer function | | - | help: try using a local type parameter instead: `bar` + | help: try using a local generic parameter instead: `bar` -error[E0401]: can't use type parameters from outer function +error[E0401]: can't use generic parameters from outer function --> $DIR/type-arg-out-of-scope.rs:3:31 | LL | fn foo(x: T) { | - type variable from outer function LL | fn bar(f: Box T>) { } - | --- ^ use of type variable from outer function + | --- ^ use of generic parameter from outer function | | - | help: try using a local type parameter instead: `bar` + | help: try using a local generic parameter instead: `bar` error: aborting due to 2 previous errors diff --git a/src/test/ui/type/type-dependent-def-issue-49241.rs b/src/test/ui/type/type-dependent-def-issue-49241.rs index 4c366a86363..51bd116fbd6 100644 --- a/src/test/ui/type/type-dependent-def-issue-49241.rs +++ b/src/test/ui/type/type-dependent-def-issue-49241.rs @@ -1,6 +1,6 @@ fn main() { let v = vec![0]; - const l: usize = v.count(); //~ ERROR can't capture dynamic environment in a fn item + const l: usize = v.count(); //~ ERROR attempt to use a non-constant value in a constant let s: [u32; l] = v.into_iter().collect(); //~^ ERROR evaluation of constant value failed } diff --git a/src/test/ui/type/type-dependent-def-issue-49241.stderr b/src/test/ui/type/type-dependent-def-issue-49241.stderr index 8783959f45f..0af777fdcf9 100644 --- a/src/test/ui/type/type-dependent-def-issue-49241.stderr +++ b/src/test/ui/type/type-dependent-def-issue-49241.stderr @@ -1,10 +1,8 @@ -error[E0434]: can't capture dynamic environment in a fn item +error[E0435]: attempt to use a non-constant value in a constant --> $DIR/type-dependent-def-issue-49241.rs:3:22 | -LL | const l: usize = v.count(); //~ ERROR can't capture dynamic environment in a fn item - | ^ - | - = help: use the `|| { ... }` closure form instead +LL | const l: usize = v.count(); //~ ERROR attempt to use a non-constant value in a constant + | ^ non-constant value error[E0080]: evaluation of constant value failed --> $DIR/type-dependent-def-issue-49241.rs:4:18 @@ -14,5 +12,5 @@ LL | let s: [u32; l] = v.into_iter().collect(); error: aborting due to 2 previous errors -Some errors occurred: E0080, E0434. +Some errors occurred: E0080, E0435. For more information about an error, try `rustc --explain E0080`. diff --git a/src/test/ui/use-self-in-inner-fn.rs b/src/test/ui/use-self-in-inner-fn.rs index cde96dc778b..eccb315feb1 100644 --- a/src/test/ui/use-self-in-inner-fn.rs +++ b/src/test/ui/use-self-in-inner-fn.rs @@ -4,8 +4,8 @@ impl A { //~^ NOTE `Self` type implicitly declared here, by this `impl` fn banana(&mut self) { fn peach(this: &Self) { - //~^ ERROR can't use type parameters from outer function - //~| NOTE use of type variable from outer function + //~^ ERROR can't use generic parameters from outer function + //~| NOTE use of generic parameter from outer function //~| NOTE use a type here instead } } diff --git a/src/test/ui/use-self-in-inner-fn.stderr b/src/test/ui/use-self-in-inner-fn.stderr index a613804b803..96609349924 100644 --- a/src/test/ui/use-self-in-inner-fn.stderr +++ b/src/test/ui/use-self-in-inner-fn.stderr @@ -1,4 +1,4 @@ -error[E0401]: can't use type parameters from outer function +error[E0401]: can't use generic parameters from outer function --> $DIR/use-self-in-inner-fn.rs:6:25 | LL | impl A { @@ -7,7 +7,7 @@ LL | impl A { LL | fn peach(this: &Self) { | ^^^^ | | - | use of type variable from outer function + | use of generic parameter from outer function | use a type here instead error: aborting due to previous error diff --git a/src/tools/compiletest/Cargo.toml b/src/tools/compiletest/Cargo.toml index edf4aeab1c7..00e1a53473c 100644 --- a/src/tools/compiletest/Cargo.toml +++ b/src/tools/compiletest/Cargo.toml @@ -2,6 +2,7 @@ authors = ["The Rust Project Developers"] name = "compiletest" version = "0.0.0" +edition = "2018" [dependencies] diff = "0.1.10" diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs index f6f8ef1dff4..42afb72c91f 100644 --- a/src/tools/compiletest/src/common.rs +++ b/src/tools/compiletest/src/common.rs @@ -5,7 +5,7 @@ use std::str::FromStr; use test::ColorConfig; -use util::PathBufExt; +use crate::util::PathBufExt; #[derive(Clone, Copy, PartialEq, Debug)] pub enum Mode { @@ -66,7 +66,7 @@ fn from_str(s: &str) -> Result { } impl fmt::Display for Mode { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let s = match *self { CompileFail => "compile-fail", RunFail => "run-fail", diff --git a/src/tools/compiletest/src/errors.rs b/src/tools/compiletest/src/errors.rs index fd3f002fb66..0329fb0db14 100644 --- a/src/tools/compiletest/src/errors.rs +++ b/src/tools/compiletest/src/errors.rs @@ -33,7 +33,7 @@ fn from_str(s: &str) -> Result { } impl fmt::Display for ErrorKind { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { ErrorKind::Help => write!(f, "help message"), ErrorKind::Error => write!(f, "error"), diff --git a/src/tools/compiletest/src/header.rs b/src/tools/compiletest/src/header.rs index 591d92f0cfa..80a015d7aea 100644 --- a/src/tools/compiletest/src/header.rs +++ b/src/tools/compiletest/src/header.rs @@ -4,10 +4,10 @@ use std::io::BufReader; use std::path::{Path, PathBuf}; -use common::{self, CompareMode, Config, Mode}; -use util; +use crate::common::{self, CompareMode, Config, Mode}; +use crate::util; -use extract_gdb_version; +use crate::extract_gdb_version; /// Whether to ignore the test. #[derive(Clone, Copy, PartialEq, Debug)] diff --git a/src/tools/compiletest/src/json.rs b/src/tools/compiletest/src/json.rs index 106aa67157a..12aae303f29 100644 --- a/src/tools/compiletest/src/json.rs +++ b/src/tools/compiletest/src/json.rs @@ -1,5 +1,5 @@ -use errors::{Error, ErrorKind}; -use runtest::ProcRes; +use crate::errors::{Error, ErrorKind}; +use crate::runtest::ProcRes; use serde_json; use std::path::Path; use std::str::FromStr; diff --git a/src/tools/compiletest/src/main.rs b/src/tools/compiletest/src/main.rs index 15d53f1e375..1f9b4b2ad43 100644 --- a/src/tools/compiletest/src/main.rs +++ b/src/tools/compiletest/src/main.rs @@ -1,29 +1,21 @@ #![crate_name = "compiletest"] #![feature(test)] -#![deny(warnings)] +#![deny(warnings, rust_2018_idioms)] -extern crate diff; -extern crate env_logger; -extern crate filetime; -extern crate getopts; #[cfg(unix)] extern crate libc; #[macro_use] extern crate log; -extern crate regex; #[macro_use] extern crate lazy_static; #[macro_use] extern crate serde_derive; -extern crate serde_json; extern crate test; -extern crate rustfix; -extern crate walkdir; -use common::CompareMode; -use common::{expected_output_path, output_base_dir, output_relative_path, UI_EXTENSIONS}; -use common::{Config, TestPaths}; -use common::{DebugInfoBoth, DebugInfoGdb, DebugInfoLldb, Mode, Pretty}; +use crate::common::CompareMode; +use crate::common::{expected_output_path, output_base_dir, output_relative_path, UI_EXTENSIONS}; +use crate::common::{Config, TestPaths}; +use crate::common::{DebugInfoBoth, DebugInfoGdb, DebugInfoLldb, Mode, Pretty}; use filetime::FileTime; use getopts::Options; use std::env; @@ -33,8 +25,10 @@ use std::path::{Path, PathBuf}; use std::process::Command; use test::ColorConfig; -use util::logv; +use crate::util::logv; use walkdir::WalkDir; +use env_logger; +use getopts; use self::header::{EarlyProps, Ignore}; diff --git a/src/tools/compiletest/src/read2.rs b/src/tools/compiletest/src/read2.rs index 5a4caddcdd3..6dfd8e97c63 100644 --- a/src/tools/compiletest/src/read2.rs +++ b/src/tools/compiletest/src/read2.rs @@ -100,18 +100,15 @@ pub fn read2( #[cfg(windows)] mod imp { - extern crate miow; - extern crate winapi; - use std::io; use std::os::windows::prelude::*; use std::process::{ChildStderr, ChildStdout}; use std::slice; - use self::miow::iocp::{CompletionPort, CompletionStatus}; - use self::miow::pipe::NamedPipe; - use self::miow::Overlapped; - use self::winapi::shared::winerror::ERROR_BROKEN_PIPE; + use miow::iocp::{CompletionPort, CompletionStatus}; + use miow::pipe::NamedPipe; + use miow::Overlapped; + use winapi::shared::winerror::ERROR_BROKEN_PIPE; struct Pipe<'a> { dst: &'a mut Vec, diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index ff201b03a0b..31529810a04 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -1,18 +1,18 @@ -use common::CompareMode; -use common::{expected_output_path, UI_EXTENSIONS, UI_FIXED, UI_STDERR, UI_STDOUT}; -use common::{output_base_dir, output_base_name, output_testname_unique}; -use common::{Codegen, CodegenUnits, DebugInfoBoth, DebugInfoGdb, DebugInfoLldb, Rustdoc}; -use common::{CompileFail, Pretty, RunFail, RunPass, RunPassValgrind}; -use common::{Config, TestPaths}; -use common::{Incremental, MirOpt, RunMake, Ui}; +use crate::common::CompareMode; +use crate::common::{expected_output_path, UI_EXTENSIONS, UI_FIXED, UI_STDERR, UI_STDOUT}; +use crate::common::{output_base_dir, output_base_name, output_testname_unique}; +use crate::common::{Codegen, CodegenUnits, DebugInfoBoth, DebugInfoGdb, DebugInfoLldb, Rustdoc}; +use crate::common::{CompileFail, Pretty, RunFail, RunPass, RunPassValgrind}; +use crate::common::{Config, TestPaths}; +use crate::common::{Incremental, MirOpt, RunMake, Ui}; use diff; -use errors::{self, Error, ErrorKind}; +use crate::errors::{self, Error, ErrorKind}; use filetime::FileTime; -use header::TestProps; -use json; +use crate::header::TestProps; +use crate::json; use regex::Regex; use rustfix::{apply_suggestions, get_suggestions_from_json, Filter}; -use util::{logv, PathBufExt}; +use crate::util::{logv, PathBufExt}; use std::collections::hash_map::DefaultHasher; use std::collections::{HashMap, HashSet, VecDeque}; @@ -27,8 +27,8 @@ use std::process::{Child, Command, ExitStatus, Output, Stdio}; use std::str; -use extract_gdb_version; -use is_android_gdb_target; +use crate::extract_gdb_version; +use crate::is_android_gdb_target; #[cfg(windows)] fn disable_error_reporting R, R>(f: F) -> R { @@ -1937,7 +1937,7 @@ fn split_maybe_args(&self, argstr: &Option) -> Vec { } fn make_cmdline(&self, command: &Command, libpath: &str) -> String { - use util; + use crate::util; // Linux and mac don't require adjusting the library search path if cfg!(unix) { @@ -3255,7 +3255,7 @@ fn prune_duplicate_outputs(&self, modes: &[CompareMode]) { } fn create_stamp(&self) { - let stamp = ::stamp(&self.config, self.testpaths, self.revision); + let stamp = crate::stamp(&self.config, self.testpaths, self.revision); fs::write(&stamp, compute_stamp_hash(&self.config)).unwrap(); } } @@ -3311,7 +3311,7 @@ impl fmt::Debug for ExpectedLine where T: AsRef + fmt::Debug, { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { if let &ExpectedLine::Text(ref t) = self { write!(formatter, "{:?}", t) } else { @@ -3334,7 +3334,7 @@ fn nocomment_mir_line(line: &str) -> &str { } fn read2_abbreviated(mut child: Child) -> io::Result { - use read2::read2; + use crate::read2::read2; use std::mem::replace; const HEAD_LEN: usize = 160 * 1024; diff --git a/src/tools/compiletest/src/util.rs b/src/tools/compiletest/src/util.rs index 90dfadeee46..85be2fed075 100644 --- a/src/tools/compiletest/src/util.rs +++ b/src/tools/compiletest/src/util.rs @@ -1,7 +1,7 @@ use std::ffi::OsStr; use std::env; use std::path::PathBuf; -use common::Config; +use crate::common::Config; /// Conversion table from triple OS name to Rust SYSNAME const OS_TABLE: &'static [(&'static str, &'static str)] = &[ diff --git a/src/tools/error_index_generator/Cargo.toml b/src/tools/error_index_generator/Cargo.toml index 7f8783c9d89..116be234f3c 100644 --- a/src/tools/error_index_generator/Cargo.toml +++ b/src/tools/error_index_generator/Cargo.toml @@ -2,6 +2,7 @@ authors = ["The Rust Project Developers"] name = "error_index_generator" version = "0.0.0" +edition = "2018" [dependencies] rustdoc = { path = "../../librustdoc" } diff --git a/src/tools/error_index_generator/main.rs b/src/tools/error_index_generator/main.rs index 72cfd7d5e58..ef045495a08 100644 --- a/src/tools/error_index_generator/main.rs +++ b/src/tools/error_index_generator/main.rs @@ -1,8 +1,9 @@ #![feature(rustc_private)] +#![deny(rust_2018_idioms)] + extern crate env_logger; extern crate syntax; -extern crate rustdoc; extern crate serialize as rustc_serialize; use std::collections::BTreeMap; diff --git a/src/tools/rustdoc/Cargo.toml b/src/tools/rustdoc/Cargo.toml index d3881500441..36aa5916da7 100644 --- a/src/tools/rustdoc/Cargo.toml +++ b/src/tools/rustdoc/Cargo.toml @@ -2,6 +2,7 @@ name = "rustdoc-tool" version = "0.0.0" authors = ["The Rust Project Developers"] +edition = "2018" # Cargo adds a number of paths to the dylib search path on windows, which results in # the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool" diff --git a/src/tools/rustdoc/main.rs b/src/tools/rustdoc/main.rs index df9d2c6ba96..8bdc365c4ca 100644 --- a/src/tools/rustdoc/main.rs +++ b/src/tools/rustdoc/main.rs @@ -1,3 +1,5 @@ +#![deny(rust_2018_idioms)] + #![feature(link_args)] #[allow(unused_attributes)] @@ -10,6 +12,4 @@ // See src/rustc/rustc.rs for the corresponding rustc settings. extern {} -extern crate rustdoc; - fn main() { rustdoc::main() }