From c6b0fccac822abe319a1f10d67c1271702098475 Mon Sep 17 00:00:00 2001 From: Alisdair Owens Date: Wed, 2 Sep 2015 15:35:56 +0100 Subject: [PATCH 01/14] Add long diagnostics for E0329 --- src/librustc_typeck/diagnostics.rs | 32 +++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/src/librustc_typeck/diagnostics.rs b/src/librustc_typeck/diagnostics.rs index e356f612cdef2..826524a415f75 100644 --- a/src/librustc_typeck/diagnostics.rs +++ b/src/librustc_typeck/diagnostics.rs @@ -2705,6 +2705,37 @@ fn main() { ``` "##, +E0329: r##" +An attempt was made to access an associated constant through either a generic +type parameter or `Self`. This is not supported yet. An example causing this +error is shown below: + +``` +trait Foo { + const BAR: f64; +} + +struct MyStruct; + +impl Foo for MyStruct { + const BAR: f64 = 0f64; +} + +fn get_bar_bad(t: F) -> f64 { + F::BAR +} +``` + +Currently, the value of `BAR` for a particular type can only be accessed through +a concrete type, as shown below: + +``` +fn get_bar_good() -> f64 { + ::BAR +} +``` +"##, + E0366: r##" An attempt was made to implement `Drop` on a concrete specialization of a generic type. An example is shown below: @@ -3251,7 +3282,6 @@ register_diagnostics! { E0320, // recursive overflow during dropck E0321, // extended coherence rules for defaulted traits violated E0328, // cannot implement Unsize explicitly - E0329, // associated const depends on type parameter or Self. E0374, // the trait `CoerceUnsized` may only be implemented for a coercion // between structures with one field being coerced, none found E0375, // the trait `CoerceUnsized` may only be implemented for a coercion From 865d6c3b5b8aa66109b08e1f73721e06116cc727 Mon Sep 17 00:00:00 2001 From: Xiao Chuan Yu Date: Thu, 3 Sep 2015 01:23:00 -0400 Subject: [PATCH 02/14] Fix mistake in trait.md --- src/doc/trpl/traits.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/doc/trpl/traits.md b/src/doc/trpl/traits.md index 80c45ac4f0ade..0870a6ef34147 100644 --- a/src/doc/trpl/traits.md +++ b/src/doc/trpl/traits.md @@ -390,7 +390,7 @@ fn normal>(x: &T) -> i64 { // can be called with T == i64 fn inverse() -> T - // this is using ConvertTo as if it were "ConvertFrom" + // this is using ConvertTo as if it were "ConvertTo" where i32: ConvertTo { 42.convert() } From 3903ea96f557dc923cf73d3905554083cd921a01 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Wed, 2 Sep 2015 22:06:04 +0300 Subject: [PATCH 03/14] Make `null()` and `null_mut()` const functions --- src/libcore/ptr.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index b7479b0c604f3..09dbffe6156e7 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -51,7 +51,7 @@ pub use intrinsics::write_bytes; /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] -pub fn null() -> *const T { 0 as *const T } +pub const fn null() -> *const T { 0 as *const T } /// Creates a null mutable raw pointer. /// @@ -65,7 +65,7 @@ pub fn null() -> *const T { 0 as *const T } /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] -pub fn null_mut() -> *mut T { 0 as *mut T } +pub const fn null_mut() -> *mut T { 0 as *mut T } /// Swaps the values at two mutable locations of the same type, without /// deinitialising either. They may overlap, unlike `mem::swap` which is @@ -163,7 +163,7 @@ impl *const T { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_null(self) -> bool where T: Sized { - self == 0 as *const T + self == null() } /// Returns `None` if the pointer is null, or else returns a reference to @@ -212,7 +212,7 @@ impl *mut T { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_null(self) -> bool where T: Sized { - self == 0 as *mut T + self == null_mut() } /// Returns `None` if the pointer is null, or else returns a reference to From 6fcdead4ee18f9b2288013ac296cfac7412c62bf Mon Sep 17 00:00:00 2001 From: John Thomas Date: Wed, 2 Sep 2015 23:13:56 -0700 Subject: [PATCH 04/14] Bash output fix to match real 'ruby embed.rb' call The embed rust file that we compile prints out 'Thread finished..' messages along with a 'done!' --- src/doc/trpl/rust-inside-other-languages.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/doc/trpl/rust-inside-other-languages.md b/src/doc/trpl/rust-inside-other-languages.md index 0270a92b8c9c2..8dd2e365aa82c 100644 --- a/src/doc/trpl/rust-inside-other-languages.md +++ b/src/doc/trpl/rust-inside-other-languages.md @@ -217,6 +217,17 @@ And finally, we can try running it: ```bash $ ruby embed.rb +Thread finished with count=5000000 +Thread finished with count=5000000 +Thread finished with count=5000000 +Thread finished with count=5000000 +Thread finished with count=5000000 +Thread finished with count=5000000 +Thread finished with count=5000000 +Thread finished with count=5000000 +Thread finished with count=5000000 +Thread finished with count=5000000 +done! done! $ ``` From 06fb196256bbab1e7aa4f43daf45321efaa6e0eb Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Thu, 3 Sep 2015 09:49:50 +0300 Subject: [PATCH 05/14] Use `null()`/`null_mut()` instead of `0 as *const T`/`0 as *mut T` --- src/libcollections/btree/node.rs | 2 +- src/libcollections/vec.rs | 2 +- src/liblog/lib.rs | 6 +++--- src/librustc_trans/back/archive.rs | 7 ++++--- src/librustc_trans/back/msvc/registry.rs | 15 ++++++++------- src/libstd/io/lazy.rs | 3 ++- src/libstd/rand/os.rs | 3 ++- src/libstd/rt/at_exit_imp.rs | 3 ++- src/libstd/rt/unwind/seh.rs | 5 +++-- src/libstd/sys/common/net.rs | 7 ++++--- .../unix/backtrace/printing/libbacktrace.rs | 2 +- src/libstd/sys/unix/os.rs | 10 +++++----- src/libstd/sys/unix/process.rs | 2 +- src/libstd/sys/unix/stack_overflow.rs | 4 ++-- src/libstd/sys/unix/sync.rs | 10 ++++++---- src/libstd/sys/unix/thread.rs | 2 +- src/libstd/sys/windows/c.rs | 5 +++-- src/libstd/sys/windows/fs.rs | 18 +++++++++--------- src/libstd/sys/windows/net.rs | 3 ++- src/libstd/sys/windows/pipe.rs | 3 ++- src/libstd/sys/windows/thread_local.rs | 2 +- src/libstd/thread/scoped_tls.rs | 3 ++- 22 files changed, 65 insertions(+), 52 deletions(-) diff --git a/src/libcollections/btree/node.rs b/src/libcollections/btree/node.rs index ab343430296e8..d8f8ca6eae59c 100644 --- a/src/libcollections/btree/node.rs +++ b/src/libcollections/btree/node.rs @@ -296,7 +296,7 @@ impl Drop for Node { self.destroy(); } - self.keys = unsafe { Unique::new(0 as *mut K) }; + self.keys = unsafe { Unique::new(ptr::null_mut()) }; } } diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index ec3c36d0c8137..bb752b07abeb8 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -1135,7 +1135,7 @@ impl ops::Deref for Vec { fn deref(&self) -> &[T] { unsafe { let p = self.buf.ptr(); - assume(p != 0 as *mut T); + assume(!p.is_null()); slice::from_raw_parts(p, self.len) } } diff --git a/src/liblog/lib.rs b/src/liblog/lib.rs index 2187c1fb7dfa4..4517c2f915773 100644 --- a/src/liblog/lib.rs +++ b/src/liblog/lib.rs @@ -184,6 +184,7 @@ use std::io::{self, Stderr}; use std::io::prelude::*; use std::mem; use std::env; +use std::ptr; use std::rt; use std::slice; use std::sync::{Once, StaticMutex}; @@ -209,11 +210,10 @@ static LOCK: StaticMutex = StaticMutex::new(); /// logging statement should be run. static mut LOG_LEVEL: u32 = MAX_LOG_LEVEL; -static mut DIRECTIVES: *mut Vec = - 0 as *mut Vec; +static mut DIRECTIVES: *mut Vec = ptr::null_mut(); /// Optional filter. -static mut FILTER: *mut String = 0 as *mut _; +static mut FILTER: *mut String = ptr::null_mut(); /// Debug log level pub const DEBUG: u32 = 4; diff --git a/src/librustc_trans/back/archive.rs b/src/librustc_trans/back/archive.rs index 02f4bc83b7524..76bbce00f19dc 100644 --- a/src/librustc_trans/back/archive.rs +++ b/src/librustc_trans/back/archive.rs @@ -18,6 +18,7 @@ use std::io; use std::mem; use std::path::{Path, PathBuf}; use std::process::{Command, Output, Stdio}; +use std::ptr; use std::str; use libc; @@ -449,7 +450,7 @@ impl<'a> ArchiveBuilder<'a> { } let name = try!(CString::new(child_name)); - members.push(llvm::LLVMRustArchiveMemberNew(0 as *const _, + members.push(llvm::LLVMRustArchiveMemberNew(ptr::null(), name.as_ptr(), child.raw())); strings.push(name); @@ -462,7 +463,7 @@ impl<'a> ArchiveBuilder<'a> { let name = try!(CString::new(name_in_archive)); members.push(llvm::LLVMRustArchiveMemberNew(path.as_ptr(), name.as_ptr(), - 0 as *mut _)); + ptr::null_mut())); strings.push(path); strings.push(name); } @@ -472,7 +473,7 @@ impl<'a> ArchiveBuilder<'a> { if skip(child_name) { continue } let name = try!(CString::new(child_name)); - let m = llvm::LLVMRustArchiveMemberNew(0 as *const _, + let m = llvm::LLVMRustArchiveMemberNew(ptr::null(), name.as_ptr(), child.raw()); members.push(m); diff --git a/src/librustc_trans/back/msvc/registry.rs b/src/librustc_trans/back/msvc/registry.rs index 21078641c1f53..d178565e18f59 100644 --- a/src/librustc_trans/back/msvc/registry.rs +++ b/src/librustc_trans/back/msvc/registry.rs @@ -12,6 +12,7 @@ use std::io; use std::ffi::{OsString, OsStr}; use std::os::windows::prelude::*; use std::ops::RangeFrom; +use std::ptr; use libc::{DWORD, LPCWSTR, LONG, LPDWORD, LPBYTE, ERROR_SUCCESS}; use libc::c_void; @@ -88,7 +89,7 @@ impl RegistryKey { pub fn open(&self, key: &OsStr) -> io::Result { let key = key.encode_wide().chain(Some(0)).collect::>(); - let mut ret = 0 as *mut _; + let mut ret = ptr::null_mut(); let err = unsafe { RegOpenKeyExW(self.raw(), key.as_ptr(), 0, KEY_READ | KEY_WOW64_32KEY, &mut ret) @@ -110,8 +111,8 @@ impl RegistryKey { let mut len = 0; let mut kind = 0; unsafe { - let err = RegQueryValueExW(self.raw(), name.as_ptr(), 0 as *mut _, - &mut kind, 0 as *mut _, &mut len); + let err = RegQueryValueExW(self.raw(), name.as_ptr(), ptr::null_mut(), + &mut kind, ptr::null_mut(), &mut len); if err != ERROR_SUCCESS { return Err(io::Error::from_raw_os_error(err as i32)) } @@ -124,8 +125,8 @@ impl RegistryKey { // characters so we need to be sure to halve it for the capacity // passed in. let mut v = Vec::with_capacity(len as usize / 2); - let err = RegQueryValueExW(self.raw(), name.as_ptr(), 0 as *mut _, - 0 as *mut _, v.as_mut_ptr() as *mut _, + let err = RegQueryValueExW(self.raw(), name.as_ptr(), ptr::null_mut(), + ptr::null_mut(), v.as_mut_ptr() as *mut _, &mut len); if err != ERROR_SUCCESS { return Err(io::Error::from_raw_os_error(err as i32)) @@ -156,8 +157,8 @@ impl<'a> Iterator for Iter<'a> { let mut v = Vec::with_capacity(256); let mut len = v.capacity() as DWORD; let ret = RegEnumKeyExW(self.key.raw(), i, v.as_mut_ptr(), &mut len, - 0 as *mut _, 0 as *mut _, 0 as *mut _, - 0 as *mut _); + ptr::null_mut(), ptr::null_mut(), ptr::null_mut(), + ptr::null_mut()); if ret == ERROR_NO_MORE_ITEMS as LONG { None } else if ret != ERROR_SUCCESS { diff --git a/src/libstd/io/lazy.rs b/src/libstd/io/lazy.rs index c3e309d182b95..ad17a650336c5 100644 --- a/src/libstd/io/lazy.rs +++ b/src/libstd/io/lazy.rs @@ -11,6 +11,7 @@ use prelude::v1::*; use cell::Cell; +use ptr; use rt; use sync::{StaticMutex, Arc}; @@ -26,7 +27,7 @@ impl Lazy { pub const fn new(init: fn() -> Arc) -> Lazy { Lazy { lock: StaticMutex::new(), - ptr: Cell::new(0 as *mut _), + ptr: Cell::new(ptr::null_mut()), init: init } } diff --git a/src/libstd/rand/os.rs b/src/libstd/rand/os.rs index 51d5af056cb7f..1df9642d3bb74 100644 --- a/src/libstd/rand/os.rs +++ b/src/libstd/rand/os.rs @@ -185,6 +185,7 @@ mod imp { use io; use mem; + use ptr; use rand::Rng; use libc::{c_int, size_t}; @@ -207,7 +208,7 @@ mod imp { enum SecRandom {} #[allow(non_upper_case_globals)] - const kSecRandomDefault: *const SecRandom = 0 as *const SecRandom; + const kSecRandomDefault: *const SecRandom = ptr::null(); #[link(name = "Security", kind = "framework")] extern "C" { diff --git a/src/libstd/rt/at_exit_imp.rs b/src/libstd/rt/at_exit_imp.rs index 17d2940a6f10c..54e5b499e537a 100644 --- a/src/libstd/rt/at_exit_imp.rs +++ b/src/libstd/rt/at_exit_imp.rs @@ -18,6 +18,7 @@ use alloc::boxed::FnBox; use boxed::Box; +use ptr; use sys_common::mutex::Mutex; use vec::Vec; @@ -28,7 +29,7 @@ type Queue = Vec>; // the thread infrastructure to be in place (useful on the borders of // initialization/destruction). static LOCK: Mutex = Mutex::new(); -static mut QUEUE: *mut Queue = 0 as *mut Queue; +static mut QUEUE: *mut Queue = ptr::null_mut(); // The maximum number of times the cleanup routines will be run. While running // the at_exit closures new ones may be registered, and this count is the number diff --git a/src/libstd/rt/unwind/seh.rs b/src/libstd/rt/unwind/seh.rs index ed44f9a8bda94..8c7937581665b 100644 --- a/src/libstd/rt/unwind/seh.rs +++ b/src/libstd/rt/unwind/seh.rs @@ -53,6 +53,7 @@ use prelude::v1::*; use any::Any; use libc::{c_ulong, DWORD, c_void}; +use ptr; use sys_common::thread_local::StaticKey; // 0x R U S T @@ -98,7 +99,7 @@ pub unsafe fn panic(data: Box) -> ! { rtassert!(PANIC_DATA.get().is_null()); PANIC_DATA.set(Box::into_raw(exception) as *mut u8); - RaiseException(RUST_PANIC, 0, 0, 0 as *const _); + RaiseException(RUST_PANIC, 0, 0, ptr::null()); rtabort!("could not unwind stack"); } @@ -108,7 +109,7 @@ pub unsafe fn cleanup(ptr: *mut u8) -> Box { rtassert!(ptr as DWORD == RUST_PANIC); let data = PANIC_DATA.get() as *mut Box; - PANIC_DATA.set(0 as *mut u8); + PANIC_DATA.set(ptr::null_mut()); rtassert!(!data.is_null()); *Box::from_raw(data) diff --git a/src/libstd/sys/common/net.rs b/src/libstd/sys/common/net.rs index 67e1099c29540..4fb3134eac99c 100644 --- a/src/libstd/sys/common/net.rs +++ b/src/libstd/sys/common/net.rs @@ -16,6 +16,7 @@ use io::{self, Error, ErrorKind}; use libc::{self, c_int, c_char, c_void, socklen_t}; use mem; use net::{SocketAddr, Shutdown, IpAddr}; +use ptr; use str::from_utf8; use sys::c; use sys::net::{cvt, cvt_r, cvt_gai, Socket, init, wrlen_t}; @@ -123,9 +124,9 @@ pub fn lookup_host(host: &str) -> io::Result { init(); let c_host = try!(CString::new(host)); - let mut res = 0 as *mut _; + let mut res = ptr::null_mut(); unsafe { - try!(cvt_gai(getaddrinfo(c_host.as_ptr(), 0 as *const _, 0 as *const _, + try!(cvt_gai(getaddrinfo(c_host.as_ptr(), ptr::null(), ptr::null(), &mut res))); Ok(LookupHost { original: res, cur: res }) } @@ -154,7 +155,7 @@ pub fn lookup_addr(addr: &IpAddr) -> io::Result { let data = unsafe { try!(cvt_gai(getnameinfo(inner, len, hostbuf.as_mut_ptr(), NI_MAXHOST as libc::size_t, - 0 as *mut _, 0, 0))); + ptr::null_mut(), 0, 0))); CStr::from_ptr(hostbuf.as_ptr()) }; diff --git a/src/libstd/sys/unix/backtrace/printing/libbacktrace.rs b/src/libstd/sys/unix/backtrace/printing/libbacktrace.rs index 711e241161dd7..5640eb81f2ae3 100644 --- a/src/libstd/sys/unix/backtrace/printing/libbacktrace.rs +++ b/src/libstd/sys/unix/backtrace/printing/libbacktrace.rs @@ -123,7 +123,7 @@ pub fn print(w: &mut Write, idx: isize, addr: *mut libc::c_void, // FIXME: We also call self_exe_name() on DragonFly BSD. I haven't // tested if this is required or not. unsafe fn init_state() -> *mut backtrace_state { - static mut STATE: *mut backtrace_state = 0 as *mut backtrace_state; + static mut STATE: *mut backtrace_state = ptr::null_mut(); static mut LAST_FILENAME: [libc::c_char; 256] = [0; 256]; if !STATE.is_null() { return STATE } let selfname = if cfg!(target_os = "freebsd") || diff --git a/src/libstd/sys/unix/os.rs b/src/libstd/sys/unix/os.rs index fa31ac682d40b..70be04b631ad5 100644 --- a/src/libstd/sys/unix/os.rs +++ b/src/libstd/sys/unix/os.rs @@ -291,7 +291,7 @@ pub fn args() -> Args { }; Args { iter: vec.into_iter(), - _dont_send_or_sync_me: 0 as *mut (), + _dont_send_or_sync_me: ptr::null_mut(), } } @@ -347,7 +347,7 @@ pub fn args() -> Args { } } - Args { iter: res.into_iter(), _dont_send_or_sync_me: 0 as *mut _ } + Args { iter: res.into_iter(), _dont_send_or_sync_me: ptr::null_mut() } } #[cfg(any(target_os = "linux", @@ -363,7 +363,7 @@ pub fn args() -> Args { let v: Vec = bytes.into_iter().map(|v| { OsStringExt::from_vec(v) }).collect(); - Args { iter: v.into_iter(), _dont_send_or_sync_me: 0 as *mut _ } + Args { iter: v.into_iter(), _dont_send_or_sync_me: ptr::null_mut() } } pub struct Env { @@ -403,7 +403,7 @@ pub fn env() -> Env { result.push(parse(CStr::from_ptr(*environ).to_bytes())); environ = environ.offset(1); } - Env { iter: result.into_iter(), _dont_send_or_sync_me: 0 as *mut _ } + Env { iter: result.into_iter(), _dont_send_or_sync_me: ptr::null_mut() } }; fn parse(input: &[u8]) -> (OsString, OsString) { @@ -481,7 +481,7 @@ pub fn home_dir() -> Option { loop { let mut buf = Vec::with_capacity(amt); let mut passwd: c::passwd = mem::zeroed(); - let mut result = 0 as *mut _; + let mut result = ptr::null_mut(); match c::getpwuid_r(me, &mut passwd, buf.as_mut_ptr(), buf.capacity() as libc::size_t, &mut result) { diff --git a/src/libstd/sys/unix/process.rs b/src/libstd/sys/unix/process.rs index 59798e938a69b..12ca31ce5e1e4 100644 --- a/src/libstd/sys/unix/process.rs +++ b/src/libstd/sys/unix/process.rs @@ -405,7 +405,7 @@ fn make_envp(env: Option<&HashMap>) (ptrs.as_ptr() as *const _, tmps, ptrs) } else { - (0 as *const _, Vec::new(), Vec::new()) + (ptr::null(), Vec::new(), Vec::new()) } } diff --git a/src/libstd/sys/unix/stack_overflow.rs b/src/libstd/sys/unix/stack_overflow.rs index 1aa75fa18b737..baff3c6bcbb83 100644 --- a/src/libstd/sys/unix/stack_overflow.rs +++ b/src/libstd/sys/unix/stack_overflow.rs @@ -93,7 +93,7 @@ mod imp { // See comment above for why this function returns. } - static mut MAIN_ALTSTACK: *mut libc::c_void = 0 as *mut libc::c_void; + static mut MAIN_ALTSTACK: *mut libc::c_void = ptr::null_mut(); pub unsafe fn init() { PAGE_SIZE = ::sys::os::page_size(); @@ -155,7 +155,7 @@ mod imp { } pub unsafe fn make_handler() -> super::Handler { - super::Handler { _data: 0 as *mut libc::c_void } + super::Handler { _data: ptr::null_mut() } } pub unsafe fn drop_handler(_handler: &mut super::Handler) { diff --git a/src/libstd/sys/unix/sync.rs b/src/libstd/sys/unix/sync.rs index 9c8a1f4ca40ec..4e49b6473c94b 100644 --- a/src/libstd/sys/unix/sync.rs +++ b/src/libstd/sys/unix/sync.rs @@ -59,15 +59,16 @@ extern { target_os = "openbsd"))] mod os { use libc; + use ptr; pub type pthread_mutex_t = *mut libc::c_void; pub type pthread_mutexattr_t = *mut libc::c_void; pub type pthread_cond_t = *mut libc::c_void; pub type pthread_rwlock_t = *mut libc::c_void; - pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = 0 as *mut _; - pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = 0 as *mut _; - pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = 0 as *mut _; + pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = ptr::null_mut(); + pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = ptr::null_mut(); + pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = ptr::null_mut(); pub const PTHREAD_MUTEX_RECURSIVE: libc::c_int = 2; } @@ -213,6 +214,7 @@ mod os { #[cfg(target_os = "android")] mod os { use libc; + use ptr; #[repr(C)] pub struct pthread_mutex_t { value: libc::c_int } @@ -243,7 +245,7 @@ mod os { writerThreadId: 0, pendingReaders: 0, pendingWriters: 0, - reserved: [0 as *mut _; 4], + reserved: [ptr::null_mut(); 4], }; pub const PTHREAD_MUTEX_RECURSIVE: libc::c_int = 1; } diff --git a/src/libstd/sys/unix/thread.rs b/src/libstd/sys/unix/thread.rs index 8d59461f1e4e7..5a551e2b3f33f 100644 --- a/src/libstd/sys/unix/thread.rs +++ b/src/libstd/sys/unix/thread.rs @@ -72,7 +72,7 @@ impl Thread { extern fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void { unsafe { start_thread(main); } - 0 as *mut _ + ptr::null_mut() } } diff --git a/src/libstd/sys/windows/c.rs b/src/libstd/sys/windows/c.rs index 8fb03ae79022d..30c7e5a52b7c7 100644 --- a/src/libstd/sys/windows/c.rs +++ b/src/libstd/sys/windows/c.rs @@ -16,6 +16,7 @@ use libc; use libc::{c_uint, c_ulong}; use libc::{DWORD, BOOL, BOOLEAN, ERROR_CALL_NOT_IMPLEMENTED, LPVOID, HANDLE}; use libc::{LPCWSTR, LONG}; +use ptr; pub use self::GET_FILEEX_INFO_LEVELS::*; pub use self::FILE_INFO_BY_HANDLE_CLASS::*; @@ -294,9 +295,9 @@ pub struct CRITICAL_SECTION { } pub const CONDITION_VARIABLE_INIT: CONDITION_VARIABLE = CONDITION_VARIABLE { - ptr: 0 as *mut _, + ptr: ptr::null_mut(), }; -pub const SRWLOCK_INIT: SRWLOCK = SRWLOCK { ptr: 0 as *mut _ }; +pub const SRWLOCK_INIT: SRWLOCK = SRWLOCK { ptr: ptr::null_mut() }; #[repr(C)] pub struct LUID { diff --git a/src/libstd/sys/windows/fs.rs b/src/libstd/sys/windows/fs.rs index d413d536cc85b..e9d98b36a43f8 100644 --- a/src/libstd/sys/windows/fs.rs +++ b/src/libstd/sys/windows/fs.rs @@ -328,12 +328,12 @@ impl File { try!(cvt({ c::DeviceIoControl(self.handle.raw(), c::FSCTL_GET_REPARSE_POINT, - 0 as *mut _, + ptr::null_mut(), 0, space.as_mut_ptr() as *mut _, space.len() as libc::DWORD, &mut bytes, - 0 as *mut _) + ptr::null_mut()) })); Ok((bytes, &*(space.as_ptr() as *const c::REPARSE_DATA_BUFFER))) } @@ -680,15 +680,15 @@ fn directory_junctions_are_directories() { c::FSCTL_SET_REPARSE_POINT, data.as_ptr() as *mut _, (*db).ReparseDataLength + 8, - 0 as *mut _, 0, + ptr::null_mut(), 0, &mut ret, - 0 as *mut _)).map(|_| ()) + ptr::null_mut())).map(|_| ()) } } fn opendir(p: &Path, write: bool) -> io::Result { unsafe { - let mut token = 0 as *mut _; + let mut token = ptr::null_mut(); let mut tp: c::TOKEN_PRIVILEGES = mem::zeroed(); try!(cvt(c::OpenProcessToken(c::GetCurrentProcess(), c::TOKEN_ADJUST_PRIVILEGES, @@ -699,14 +699,14 @@ fn directory_junctions_are_directories() { "SeBackupPrivilege".as_ref() }; let name = name.encode_wide().chain(Some(0)).collect::>(); - try!(cvt(c::LookupPrivilegeValueW(0 as *const _, + try!(cvt(c::LookupPrivilegeValueW(ptr::null(), name.as_ptr(), &mut tp.Privileges[0].Luid))); tp.PrivilegeCount = 1; tp.Privileges[0].Attributes = c::SE_PRIVILEGE_ENABLED; let size = mem::size_of::() as libc::DWORD; try!(cvt(c::AdjustTokenPrivileges(token, libc::FALSE, &mut tp, size, - 0 as *mut _, 0 as *mut _))); + ptr::null_mut(), ptr::null_mut()))); try!(cvt(libc::CloseHandle(token))); File::open_reparse_point(p, write) @@ -726,9 +726,9 @@ fn directory_junctions_are_directories() { c::FSCTL_DELETE_REPARSE_POINT, data.as_ptr() as *mut _, (*db).ReparseDataLength + 8, - 0 as *mut _, 0, + ptr::null_mut(), 0, &mut bytes, - 0 as *mut _)).map(|_| ()) + ptr::null_mut())).map(|_| ()) } } } diff --git a/src/libstd/sys/windows/net.rs b/src/libstd/sys/windows/net.rs index 57e84b0c46c58..e62b2d8cb18ff 100644 --- a/src/libstd/sys/windows/net.rs +++ b/src/libstd/sys/windows/net.rs @@ -15,6 +15,7 @@ use mem; use net::SocketAddr; use num::One; use ops::Neg; +use ptr; use rt; use sync::Once; use sys; @@ -80,7 +81,7 @@ impl Socket { SocketAddr::V6(..) => libc::AF_INET6, }; let socket = try!(unsafe { - match c::WSASocketW(fam, ty, 0, 0 as *mut _, 0, + match c::WSASocketW(fam, ty, 0, ptr::null_mut(), 0, c::WSA_FLAG_OVERLAPPED) { INVALID_SOCKET => Err(last_error()), n => Ok(Socket(n)), diff --git a/src/libstd/sys/windows/pipe.rs b/src/libstd/sys/windows/pipe.rs index 7e286b91f4a7f..3e2f442f073f6 100644 --- a/src/libstd/sys/windows/pipe.rs +++ b/src/libstd/sys/windows/pipe.rs @@ -10,6 +10,7 @@ use io; use libc; +use ptr; use sys::cvt; use sys::c; use sys::handle::Handle; @@ -26,7 +27,7 @@ pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> { let mut reader = libc::INVALID_HANDLE_VALUE; let mut writer = libc::INVALID_HANDLE_VALUE; try!(cvt(unsafe { - c::CreatePipe(&mut reader, &mut writer, 0 as *mut _, 0) + c::CreatePipe(&mut reader, &mut writer, ptr::null_mut(), 0) })); let reader = Handle::new(reader); let writer = Handle::new(writer); diff --git a/src/libstd/sys/windows/thread_local.rs b/src/libstd/sys/windows/thread_local.rs index d9b7a59712b0c..17bc7ee887693 100644 --- a/src/libstd/sys/windows/thread_local.rs +++ b/src/libstd/sys/windows/thread_local.rs @@ -58,7 +58,7 @@ pub type Dtor = unsafe extern fn(*mut u8); // the thread infrastructure to be in place (useful on the borders of // initialization/destruction). static DTOR_LOCK: Mutex = Mutex::new(); -static mut DTORS: *mut Vec<(Key, Dtor)> = 0 as *mut _; +static mut DTORS: *mut Vec<(Key, Dtor)> = ptr::null_mut(); // ------------------------------------------------------------------------- // Native bindings diff --git a/src/libstd/thread/scoped_tls.rs b/src/libstd/thread/scoped_tls.rs index bfcaabdbc17b8..87f58b4c84910 100644 --- a/src/libstd/thread/scoped_tls.rs +++ b/src/libstd/thread/scoped_tls.rs @@ -226,6 +226,7 @@ impl ScopedKey { #[doc(hidden)] mod imp { use cell::Cell; + use ptr; pub struct KeyInner { inner: Cell<*mut T> } @@ -233,7 +234,7 @@ mod imp { impl KeyInner { pub const fn new() -> KeyInner { - KeyInner { inner: Cell::new(0 as *mut _) } + KeyInner { inner: Cell::new(ptr::null_mut()) } } pub unsafe fn set(&self, ptr: *mut T) { self.inner.set(ptr); } pub unsafe fn get(&self) -> *mut T { self.inner.get() } From fcad49e4161f2083db3ea3c3534d13d10bd130eb Mon Sep 17 00:00:00 2001 From: Ariel Ben-Yehuda Date: Tue, 1 Sep 2015 20:37:05 +0300 Subject: [PATCH 06/14] remove totally useless struct-field index --- src/librustc/metadata/encoder.rs | 80 ++++++++++++++------------------ 1 file changed, 34 insertions(+), 46 deletions(-) diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index 8085c643f1935..563cb1cbe736b 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -287,6 +287,15 @@ fn encode_enum_variant_info(ecx: &EncodeContext, for variant in &def.variants { let vid = variant.did; assert!(vid.is_local()); + + if let ty::VariantKind::Dict = variant.kind() { + // tuple-like enum variant fields aren't really items so + // don't try to encode them. + for field in &variant.fields { + encode_field(ecx, rbml_w, field, index); + } + } + index.push(entry { val: vid.node as i64, pos: rbml_w.mark_stable_position(), @@ -308,11 +317,6 @@ fn encode_enum_variant_info(ecx: &EncodeContext, let stab = stability::lookup(ecx.tcx, vid); encode_stability(rbml_w, stab); - if let ty::VariantKind::Dict = variant.kind() { - let idx = encode_info_for_struct(ecx, rbml_w, variant, index); - encode_index(rbml_w, idx, write_i64); - } - encode_struct_fields(rbml_w, variant, vid); let specified_disr_val = variant.disr_val; @@ -618,41 +622,29 @@ fn encode_provided_source(rbml_w: &mut Encoder, } } -/* Returns an index of items in this class */ -fn encode_info_for_struct<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>, - rbml_w: &mut Encoder, - variant: ty::VariantDef<'tcx>, - global_index: &mut Vec>) - -> Vec> { - /* Each class has its own index, since different classes - may have fields with the same name */ - let mut index = Vec::new(); - /* We encode both private and public fields -- need to include - private fields to get the offsets right */ - for field in &variant.fields { - let nm = field.name; - let id = field.did.node; - - let pos = rbml_w.mark_stable_position(); - index.push(entry {val: id as i64, pos: pos}); - global_index.push(entry { - val: id as i64, - pos: pos, - }); - rbml_w.start_tag(tag_items_data_item); - debug!("encode_info_for_struct: doing {} {}", - nm, id); - encode_struct_field_family(rbml_w, field.vis); - encode_name(rbml_w, nm); - encode_bounds_and_type_for_item(rbml_w, ecx, id); - encode_def_id(rbml_w, DefId::local(id)); - - let stab = stability::lookup(ecx.tcx, field.did); - encode_stability(rbml_w, stab); +fn encode_field<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>, + rbml_w: &mut Encoder, + field: ty::FieldDef<'tcx>, + global_index: &mut Vec>) { + let nm = field.name; + let id = field.did.node; - rbml_w.end_tag(); - } - index + let pos = rbml_w.mark_stable_position(); + global_index.push(entry { + val: id as i64, + pos: pos, + }); + rbml_w.start_tag(tag_items_data_item); + debug!("encode_field: encoding {} {}", nm, id); + encode_struct_field_family(rbml_w, field.vis); + encode_name(rbml_w, nm); + encode_bounds_and_type_for_item(rbml_w, ecx, id); + encode_def_id(rbml_w, DefId::local(id)); + + let stab = stability::lookup(ecx.tcx, field.did); + encode_stability(rbml_w, stab); + + rbml_w.end_tag(); } fn encode_info_for_struct_ctor(ecx: &EncodeContext, @@ -1146,11 +1138,9 @@ fn encode_info_for_item(ecx: &EncodeContext, let def = ecx.tcx.lookup_adt_def(def_id); let variant = def.struct_variant(); - /* First, encode the fields - These come first because we need to write them to make - the index, and the index needs to be in the item for the - class itself */ - let idx = encode_info_for_struct(ecx, rbml_w, variant, index); + for field in &variant.fields { + encode_field(ecx, rbml_w, field, index); + } /* Index the class*/ add_to_index(item, rbml_w, index); @@ -1179,8 +1169,6 @@ fn encode_info_for_item(ecx: &EncodeContext, // Encode inherent implementations for this structure. encode_inherent_implementations(ecx, rbml_w, def_id); - /* Each class has its own index -- encode it */ - encode_index(rbml_w, idx, write_i64); rbml_w.end_tag(); // If this is a tuple-like struct, encode the type of the constructor. From cde09e7ca36aa2ee7d7677d038944cadbd65f40b Mon Sep 17 00:00:00 2001 From: Ariel Ben-Yehuda Date: Thu, 3 Sep 2015 01:22:31 +0300 Subject: [PATCH 07/14] rewrite metadata indexing this improves the compilation time for small crates by ~20% --- src/librustc/lib.rs | 1 - src/librustc/metadata/common.rs | 8 +- src/librustc/metadata/creader.rs | 3 +- src/librustc/metadata/csearch.rs | 36 +----- src/librustc/metadata/cstore.rs | 3 +- src/librustc/metadata/decoder.rs | 187 +++++++++++---------------- src/librustc/metadata/encoder.rs | 119 +++++------------- src/librustc/metadata/index.rs | 208 +++++++++++++++++++++++++++++++ src/librustc/metadata/mod.rs | 1 + 9 files changed, 322 insertions(+), 244 deletions(-) create mode 100644 src/librustc/metadata/index.rs diff --git a/src/librustc/lib.rs b/src/librustc/lib.rs index f6a877bafce72..755d83bf8ec9d 100644 --- a/src/librustc/lib.rs +++ b/src/librustc/lib.rs @@ -51,7 +51,6 @@ #![feature(rustc_diagnostic_macros)] #![feature(rustc_private)] #![feature(scoped_tls)] -#![feature(slice_bytes)] #![feature(slice_splits)] #![feature(slice_patterns)] #![feature(staged_api)] diff --git a/src/librustc/metadata/common.rs b/src/librustc/metadata/common.rs index 3e0cf30fe942f..0fb55bd790766 100644 --- a/src/librustc/metadata/common.rs +++ b/src/librustc/metadata/common.rs @@ -45,13 +45,7 @@ pub const tag_items_data_item_is_tuple_struct_ctor: usize = 0x29; pub const tag_index: usize = 0x2a; -pub const tag_index_buckets: usize = 0x2b; - -pub const tag_index_buckets_bucket: usize = 0x2c; - -pub const tag_index_buckets_bucket_elt: usize = 0x2d; - -pub const tag_index_table: usize = 0x2e; +// GAP 0x2b, 0x2c, 0x2d, 0x2e pub const tag_meta_item_name_value: usize = 0x2f; diff --git a/src/librustc/metadata/creader.rs b/src/librustc/metadata/creader.rs index d758b2534411f..5ac84578369d2 100644 --- a/src/librustc/metadata/creader.rs +++ b/src/librustc/metadata/creader.rs @@ -304,6 +304,7 @@ impl<'a> CrateReader<'a> { let cmeta = Rc::new(cstore::crate_metadata { name: name.to_string(), local_path: RefCell::new(SmallVector::zero()), + index: decoder::load_index(metadata.as_slice()), data: metadata, cnum_map: RefCell::new(cnum_map), cnum: cnum, @@ -521,7 +522,7 @@ impl<'a> CrateReader<'a> { } let registrar = decoder::get_plugin_registrar_fn(ekrate.metadata.as_slice()) - .map(|id| decoder::get_symbol(ekrate.metadata.as_slice(), id)); + .map(|id| decoder::get_symbol_from_buf(ekrate.metadata.as_slice(), id)); match (ekrate.dylib.as_ref(), registrar) { (Some(dylib), Some(reg)) => Some((dylib.to_path_buf(), reg)), diff --git a/src/librustc/metadata/csearch.rs b/src/librustc/metadata/csearch.rs index 91c7ac4891857..c539bfc596413 100644 --- a/src/librustc/metadata/csearch.rs +++ b/src/librustc/metadata/csearch.rs @@ -11,23 +11,18 @@ // Searching for information from the cstore use front::map as ast_map; -use metadata::common::*; use metadata::cstore; use metadata::decoder; use metadata::inline::InlinedItem; use middle::def_id::DefId; use middle::lang_items; use middle::ty; +use util::nodemap::FnvHashMap; -use rbml; -use rbml::reader; use std::rc::Rc; use syntax::ast; use rustc_front::attr; use rustc_front::hir; -use syntax::diagnostic::expect; - -use std::collections::hash_map::HashMap; #[derive(Copy, Clone)] pub struct MethodInfo { @@ -38,7 +33,7 @@ pub struct MethodInfo { pub fn get_symbol(cstore: &cstore::CStore, def: DefId) -> String { let cdata = cstore.get_crate_data(def.krate); - decoder::get_symbol(cdata.data(), def.node) + decoder::get_symbol(&cdata, def.node) } /// Iterates over all the language items in the given crate. @@ -201,7 +196,7 @@ pub fn get_struct_field_names(cstore: &cstore::CStore, def: DefId) -> Vec HashMap FnvHashMap> { let cdata = cstore.get_crate_data(def.krate); decoder::get_struct_field_attrs(&*cdata) @@ -243,31 +238,6 @@ pub fn get_super_predicates<'tcx>(tcx: &ty::ctxt<'tcx>, def: DefId) decoder::get_super_predicates(&*cdata, def.node, tcx) } -pub fn get_field_type<'tcx>(tcx: &ty::ctxt<'tcx>, class_id: DefId, - def: DefId) -> ty::TypeScheme<'tcx> { - let cstore = &tcx.sess.cstore; - let cdata = cstore.get_crate_data(class_id.krate); - let all_items = reader::get_doc(rbml::Doc::new(cdata.data()), tag_items); - let class_doc = expect(tcx.sess.diagnostic(), - decoder::maybe_find_item(class_id.node, all_items), - || { - (format!("get_field_type: class ID {:?} not found", - class_id)).to_string() - }); - let the_field = expect(tcx.sess.diagnostic(), - decoder::maybe_find_item(def.node, class_doc), - || { - (format!("get_field_type: in class {:?}, field ID {:?} not found", - class_id, - def)).to_string() - }); - let ty = decoder::item_type(def, the_field, tcx, &*cdata); - ty::TypeScheme { - generics: ty::Generics::empty(), - ty: ty, - } -} - pub fn get_impl_polarity<'tcx>(tcx: &ty::ctxt<'tcx>, def: DefId) -> Option diff --git a/src/librustc/metadata/cstore.rs b/src/librustc/metadata/cstore.rs index 838f78163f018..42f52b2d20b1b 100644 --- a/src/librustc/metadata/cstore.rs +++ b/src/librustc/metadata/cstore.rs @@ -18,7 +18,7 @@ pub use self::LinkagePreference::*; pub use self::NativeLibraryKind::*; use back::svh::Svh; -use metadata::{creader, decoder, loader}; +use metadata::{creader, decoder, index, loader}; use session::search_paths::PathKind; use util::nodemap::{FnvHashMap, NodeMap, NodeSet}; @@ -65,6 +65,7 @@ pub struct crate_metadata { pub codemap_import_info: RefCell>, pub span: codemap::Span, pub staged_api: bool, + pub index: index::Index, /// Flag if this crate is required by an rlib version of this crate, or in /// other words whether it was explicitly linked to. An example of a crate diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index 5991b79896b74..309a18feb9aad 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -26,6 +26,7 @@ use metadata::csearch::MethodInfo; use metadata::csearch; use metadata::cstore; use metadata::encoder::def_to_u64; +use metadata::index; use metadata::inline::InlinedItem; use metadata::tydecode::TyDecoder; use middle::def; @@ -37,12 +38,9 @@ use middle::ty::{self, RegionEscape, Ty}; use util::nodemap::FnvHashMap; use std::cell::{Cell, RefCell}; -use std::collections::HashMap; -use std::hash::{Hash, SipHasher, Hasher}; use std::io::prelude::*; use std::io; use std::rc::Rc; -use std::slice::bytes; use std::str; use rbml::reader; @@ -59,57 +57,24 @@ use syntax::ptr::P; pub type Cmd<'a> = &'a crate_metadata; -// A function that takes a def_id relative to the crate being searched and -// returns a def_id relative to the compilation environment, i.e. if we hit a -// def_id for an item defined in another crate, somebody needs to figure out -// what crate that's in and give us a def_id that makes sense for the current -// build. - -fn u32_from_be_bytes(bytes: &[u8]) -> u32 { - let mut b = [0; 4]; - bytes::copy_memory(&bytes[..4], &mut b); - unsafe { (*(b.as_ptr() as *const u32)).to_be() } -} - -fn lookup_hash<'a, F>(d: rbml::Doc<'a>, mut eq_fn: F, hash: u64) -> Option> where - F: FnMut(&[u8]) -> bool, -{ - let index = reader::get_doc(d, tag_index); - let table = reader::get_doc(index, tag_index_table); - let hash_pos = table.start + (hash % 256 * 4) as usize; - let pos = u32_from_be_bytes(&d.data[hash_pos..]) as usize; - let tagged_doc = reader::doc_at(d.data, pos).unwrap(); - - reader::tagged_docs(tagged_doc.doc, tag_index_buckets_bucket_elt).find(|elt| { - eq_fn(&elt.data[elt.start + 4 .. elt.end]) - }).map(|elt| { - let pos = u32_from_be_bytes(&elt.data[elt.start..]) as usize; - reader::doc_at(d.data, pos).unwrap().doc - }) -} - -pub fn maybe_find_item<'a>(item_id: ast::NodeId, - items: rbml::Doc<'a>) -> Option> { - fn eq_item(bytes: &[u8], item_id: ast::NodeId) -> bool { - u32_from_be_bytes(bytes) == item_id +impl crate_metadata { + fn get_item(&self, item_id: ast::NodeId) -> Option { + self.index.lookup_item(self.data(), item_id).map(|pos| { + reader::doc_at(self.data(), pos as usize).unwrap().doc + }) } - let mut s = SipHasher::new_with_keys(0, 0); - (item_id as i64).hash(&mut s); - lookup_hash(items, |a| eq_item(a, item_id), s.finish()) -} -fn find_item<'a>(item_id: ast::NodeId, items: rbml::Doc<'a>) -> rbml::Doc<'a> { - match maybe_find_item(item_id, items) { - None => panic!("lookup_item: id not found: {}", item_id), - Some(d) => d + fn lookup_item(&self, item_id: ast::NodeId) -> rbml::Doc { + match self.get_item(item_id) { + None => panic!("lookup_item: id not found: {}", item_id), + Some(d) => d + } } } -// Looks up an item in the given metadata and returns an rbml doc pointing -// to the item data. -fn lookup_item<'a>(item_id: ast::NodeId, data: &'a [u8]) -> rbml::Doc<'a> { - let items = reader::get_doc(rbml::Doc::new(data), tag_items); - find_item(item_id, items) +pub fn load_index(data: &[u8]) -> index::Index { + let index = reader::get_doc(rbml::Doc::new(data), tag_index); + index::Index::from_buf(index.data, index.start, index.end) } #[derive(Debug, PartialEq)] @@ -380,7 +345,7 @@ pub fn get_trait_def<'tcx>(cdata: Cmd, item_id: ast::NodeId, tcx: &ty::ctxt<'tcx>) -> ty::TraitDef<'tcx> { - let item_doc = lookup_item(item_id, cdata.data()); + let item_doc = cdata.lookup_item(item_id); let generics = doc_generics(item_doc, tcx, cdata, tag_item_generics); let unsafety = parse_unsafety(item_doc); let associated_type_names = parse_associated_type_names(item_doc); @@ -410,7 +375,7 @@ pub fn get_adt_def<'tcx>(intr: &IdentInterner, let mut disr_val = 0; reader::tagged_docs(doc, tag_items_data_item_variant).map(|p| { let did = translated_def_id(cdata, p); - let item = lookup_item(did.node, cdata.data()); + let item = cdata.lookup_item(did.node); if let Some(disr) = variant_disr_val(item) { disr_val = disr; @@ -459,7 +424,7 @@ pub fn get_adt_def<'tcx>(intr: &IdentInterner, } } - let doc = lookup_item(item_id, cdata.data()); + let doc = cdata.lookup_item(item_id); let did = DefId { krate: cdata.cnum, node: item_id }; let (kind, variants) = match item_family(doc) { Enum => (ty::AdtKind::Enum, @@ -516,7 +481,7 @@ pub fn get_predicates<'tcx>(cdata: Cmd, tcx: &ty::ctxt<'tcx>) -> ty::GenericPredicates<'tcx> { - let item_doc = lookup_item(item_id, cdata.data()); + let item_doc = cdata.lookup_item(item_id); doc_predicates(item_doc, tcx, cdata, tag_item_generics) } @@ -525,14 +490,14 @@ pub fn get_super_predicates<'tcx>(cdata: Cmd, tcx: &ty::ctxt<'tcx>) -> ty::GenericPredicates<'tcx> { - let item_doc = lookup_item(item_id, cdata.data()); + let item_doc = cdata.lookup_item(item_id); doc_predicates(item_doc, tcx, cdata, tag_item_super_predicates) } pub fn get_type<'tcx>(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt<'tcx>) -> ty::TypeScheme<'tcx> { - let item_doc = lookup_item(id, cdata.data()); + let item_doc = cdata.lookup_item(id); let t = item_type(DefId { krate: cdata.cnum, node: id }, item_doc, tcx, cdata); let generics = doc_generics(item_doc, tcx, cdata, tag_item_generics); @@ -543,7 +508,7 @@ pub fn get_type<'tcx>(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt<'tcx>) } pub fn get_stability(cdata: Cmd, id: ast::NodeId) -> Option { - let item = lookup_item(id, cdata.data()); + let item = cdata.lookup_item(id); reader::maybe_get_doc(item, tag_items_data_item_stability).map(|doc| { let mut decoder = reader::Decoder::new(doc); Decodable::decode(&mut decoder).unwrap() @@ -551,7 +516,7 @@ pub fn get_stability(cdata: Cmd, id: ast::NodeId) -> Option { } pub fn get_repr_attrs(cdata: Cmd, id: ast::NodeId) -> Vec { - let item = lookup_item(id, cdata.data()); + let item = cdata.lookup_item(id); match reader::maybe_get_doc(item, tag_items_data_item_repr).map(|doc| { let mut decoder = reader::Decoder::new(doc); Decodable::decode(&mut decoder).unwrap() @@ -565,7 +530,7 @@ pub fn get_impl_polarity<'tcx>(cdata: Cmd, id: ast::NodeId) -> Option { - let item_doc = lookup_item(id, cdata.data()); + let item_doc = cdata.lookup_item(id); let fam = item_family(item_doc); match fam { Family::Impl => { @@ -578,7 +543,7 @@ pub fn get_impl_polarity<'tcx>(cdata: Cmd, pub fn get_custom_coerce_unsized_kind<'tcx>(cdata: Cmd, id: ast::NodeId) -> Option { - let item_doc = lookup_item(id, cdata.data()); + let item_doc = cdata.lookup_item(id); reader::maybe_get_doc(item_doc, tag_impl_coerce_unsized_kind).map(|kind_doc| { let mut decoder = reader::Decoder::new(kind_doc); Decodable::decode(&mut decoder).unwrap() @@ -590,7 +555,7 @@ pub fn get_impl_trait<'tcx>(cdata: Cmd, tcx: &ty::ctxt<'tcx>) -> Option> { - let item_doc = lookup_item(id, cdata.data()); + let item_doc = cdata.lookup_item(id); let fam = item_family(item_doc); match fam { Family::Impl | Family::DefaultImpl => { @@ -602,8 +567,16 @@ pub fn get_impl_trait<'tcx>(cdata: Cmd, } } -pub fn get_symbol(data: &[u8], id: ast::NodeId) -> String { - return item_symbol(lookup_item(id, data)); +pub fn get_symbol(cdata: Cmd, id: ast::NodeId) -> String { + return item_symbol(cdata.lookup_item(id)); +} + +/// If you have a crate_metadata, call get_symbol instead +pub fn get_symbol_from_buf(data: &[u8], id: ast::NodeId) -> String { + let index = load_index(data); + let pos = index.lookup_item(data, id).unwrap(); + let doc = reader::doc_at(data, pos as usize).unwrap().doc; + item_symbol(doc) } // Something that a name can resolve to. @@ -655,10 +628,8 @@ fn each_child_of_item_or_crate(intr: Rc, None => cdata }; - let other_crates_items = reader::get_doc(rbml::Doc::new(crate_data.data()), tag_items); - // Get the item. - match maybe_find_item(child_def_id.node, other_crates_items) { + match crate_data.get_item(child_def_id.node) { None => {} Some(child_item_doc) => { // Hand off the item to the callback. @@ -676,13 +647,12 @@ fn each_child_of_item_or_crate(intr: Rc, for inherent_impl_def_id_doc in reader::tagged_docs(item_doc, tag_items_data_item_inherent_impl) { let inherent_impl_def_id = item_def_id(inherent_impl_def_id_doc, cdata); - let items = reader::get_doc(rbml::Doc::new(cdata.data()), tag_items); - if let Some(inherent_impl_doc) = maybe_find_item(inherent_impl_def_id.node, items) { + if let Some(inherent_impl_doc) = cdata.get_item(inherent_impl_def_id.node) { for impl_item_def_id_doc in reader::tagged_docs(inherent_impl_doc, tag_item_impl_item) { let impl_item_def_id = item_def_id(impl_item_def_id_doc, cdata); - if let Some(impl_method_doc) = maybe_find_item(impl_item_def_id.node, items) { + if let Some(impl_method_doc) = cdata.get_item(impl_item_def_id.node) { if let StaticMethod = item_family(impl_method_doc) { // Hand off the static method to the callback. let static_method_name = item_name(&*intr, impl_method_doc); @@ -717,10 +687,8 @@ fn each_child_of_item_or_crate(intr: Rc, None => cdata }; - let other_crates_items = reader::get_doc(rbml::Doc::new(crate_data.data()), tag_items); - // Get the item. - if let Some(child_item_doc) = maybe_find_item(child_def_id.node, other_crates_items) { + if let Some(child_item_doc) = crate_data.get_item(child_def_id.node) { // Hand off the item to the callback. let def_like = item_to_def_like(crate_data, child_item_doc, child_def_id); // These items have a public visibility because they're part of @@ -740,9 +708,7 @@ pub fn each_child_of_item(intr: Rc, G: FnMut(ast::CrateNum) -> Rc, { // Find the item. - let root_doc = rbml::Doc::new(cdata.data()); - let items = reader::get_doc(root_doc, tag_items); - let item_doc = match maybe_find_item(id, items) { + let item_doc = match cdata.get_item(id) { None => return, Some(item_doc) => item_doc, }; @@ -775,11 +741,11 @@ pub fn each_top_level_item_of_crate(intr: Rc, } pub fn get_item_path(cdata: Cmd, id: ast::NodeId) -> Vec { - item_path(lookup_item(id, cdata.data())) + item_path(cdata.lookup_item(id)) } pub fn get_item_name(intr: &IdentInterner, cdata: Cmd, id: ast::NodeId) -> ast::Name { - item_name(intr, lookup_item(id, cdata.data())) + item_name(intr, cdata.lookup_item(id)) } pub type DecodeInlinedItem<'a> = @@ -793,14 +759,14 @@ pub fn maybe_get_item_ast<'tcx>(cdata: Cmd, tcx: &ty::ctxt<'tcx>, id: ast::NodeI mut decode_inlined_item: DecodeInlinedItem) -> csearch::FoundAst<'tcx> { debug!("Looking up item: {}", id); - let item_doc = lookup_item(id, cdata.data()); + let item_doc = cdata.lookup_item(id); let path = item_path(item_doc).split_last().unwrap().1.to_vec(); match decode_inlined_item(cdata, tcx, path, item_doc) { Ok(ii) => csearch::FoundAst::Found(ii), Err(path) => { match item_parent_item(cdata, item_doc) { Some(did) => { - let parent_item = lookup_item(did.node, cdata.data()); + let parent_item = cdata.lookup_item(did.node); match decode_inlined_item(cdata, tcx, path, parent_item) { Ok(ii) => csearch::FoundAst::FoundParent(did, ii), Err(_) => csearch::FoundAst::NotFound @@ -842,7 +808,7 @@ fn get_explicit_self(item: rbml::Doc) -> ty::ExplicitSelfCategory { /// Returns the def IDs of all the items in the given implementation. pub fn get_impl_items(cdata: Cmd, impl_id: ast::NodeId) -> Vec { - reader::tagged_docs(lookup_item(impl_id, cdata.data()), tag_item_impl_item).map(|doc| { + reader::tagged_docs(cdata.lookup_item(impl_id), tag_item_impl_item).map(|doc| { let def_id = item_def_id(doc, cdata); match item_sort(doc) { Some('C') => ty::ConstTraitItemId(def_id), @@ -857,12 +823,12 @@ pub fn get_trait_name(intr: Rc, cdata: Cmd, id: ast::NodeId) -> ast::Name { - let doc = lookup_item(id, cdata.data()); + let doc = cdata.lookup_item(id); item_name(&*intr, doc) } pub fn is_static_method(cdata: Cmd, id: ast::NodeId) -> bool { - let doc = lookup_item(id, cdata.data()); + let doc = cdata.lookup_item(id); match item_sort(doc) { Some('r') | Some('p') => { get_explicit_self(doc) == ty::StaticExplicitSelfCategory @@ -876,12 +842,12 @@ pub fn get_impl_or_trait_item<'tcx>(intr: Rc, id: ast::NodeId, tcx: &ty::ctxt<'tcx>) -> ty::ImplOrTraitItem<'tcx> { - let item_doc = lookup_item(id, cdata.data()); + let item_doc = cdata.lookup_item(id); let def_id = item_def_id(item_doc, cdata); let container_id = item_require_parent_item(cdata, item_doc); - let container_doc = lookup_item(container_id.node, cdata.data()); + let container_doc = cdata.lookup_item(container_id.node); let container = match item_family(container_doc) { Trait => TraitContainer(container_id), _ => ImplContainer(container_id), @@ -936,8 +902,7 @@ pub fn get_impl_or_trait_item<'tcx>(intr: Rc, pub fn get_trait_item_def_ids(cdata: Cmd, id: ast::NodeId) -> Vec { - let data = cdata.data(); - let item = lookup_item(id, data); + let item = cdata.lookup_item(id); reader::tagged_docs(item, tag_item_trait_item).map(|mth| { let def_id = item_def_id(mth, cdata); match item_sort(mth) { @@ -950,8 +915,7 @@ pub fn get_trait_item_def_ids(cdata: Cmd, id: ast::NodeId) } pub fn get_item_variances(cdata: Cmd, id: ast::NodeId) -> ty::ItemVariances { - let data = cdata.data(); - let item_doc = lookup_item(id, data); + let item_doc = cdata.lookup_item(id); let variance_doc = reader::get_doc(item_doc, tag_item_variances); let mut decoder = reader::Decoder::new(variance_doc); Decodable::decode(&mut decoder).unwrap() @@ -962,12 +926,11 @@ pub fn get_provided_trait_methods<'tcx>(intr: Rc, id: ast::NodeId, tcx: &ty::ctxt<'tcx>) -> Vec>> { - let data = cdata.data(); - let item = lookup_item(id, data); + let item = cdata.lookup_item(id); reader::tagged_docs(item, tag_item_trait_item).filter_map(|mth_id| { let did = item_def_id(mth_id, cdata); - let mth = lookup_item(did.node, data); + let mth = cdata.lookup_item(did.node); if item_sort(mth) == Some('p') { let trait_item = get_impl_or_trait_item(intr.clone(), @@ -990,13 +953,12 @@ pub fn get_associated_consts<'tcx>(intr: Rc, id: ast::NodeId, tcx: &ty::ctxt<'tcx>) -> Vec>> { - let data = cdata.data(); - let item = lookup_item(id, data); + let item = cdata.lookup_item(id); [tag_item_trait_item, tag_item_impl_item].iter().flat_map(|&tag| { reader::tagged_docs(item, tag).filter_map(|ac_id| { let did = item_def_id(ac_id, cdata); - let ac_doc = lookup_item(did.node, data); + let ac_doc = cdata.lookup_item(did.node); if item_sort(ac_doc) == Some('C') { let trait_item = get_impl_or_trait_item(intr.clone(), @@ -1017,7 +979,7 @@ pub fn get_associated_consts<'tcx>(intr: Rc, pub fn get_type_name_if_impl(cdata: Cmd, node_id: ast::NodeId) -> Option { - let item = lookup_item(node_id, cdata.data()); + let item = cdata.lookup_item(node_id); if item_family(item) != Impl { return None; } @@ -1031,7 +993,7 @@ pub fn get_methods_if_impl(intr: Rc, cdata: Cmd, node_id: ast::NodeId) -> Option > { - let item = lookup_item(node_id, cdata.data()); + let item = cdata.lookup_item(node_id); if item_family(item) != Impl { return None; } @@ -1046,7 +1008,7 @@ pub fn get_methods_if_impl(intr: Rc, let mut impl_methods = Vec::new(); for impl_method_id in impl_method_ids { - let impl_method_doc = lookup_item(impl_method_id.node, cdata.data()); + let impl_method_doc = cdata.lookup_item(impl_method_id.node); let family = item_family(impl_method_doc); match family { StaticMethod | Method => { @@ -1069,7 +1031,7 @@ pub fn get_tuple_struct_definition_if_ctor(cdata: Cmd, node_id: ast::NodeId) -> Option { - let item = lookup_item(node_id, cdata.data()); + let item = cdata.lookup_item(node_id); reader::tagged_docs(item, tag_items_data_item_is_tuple_struct_ctor).next().map(|_| { item_require_parent_item(cdata, item) }) @@ -1083,11 +1045,11 @@ pub fn get_item_attrs(cdata: Cmd, // look at the definition let node_id = get_tuple_struct_definition_if_ctor(cdata, orig_node_id); let node_id = node_id.map(|x| x.node).unwrap_or(orig_node_id); - let item = lookup_item(node_id, cdata.data()); + let item = cdata.lookup_item(node_id); get_attributes(item) } -pub fn get_struct_field_attrs(cdata: Cmd) -> HashMap> { +pub fn get_struct_field_attrs(cdata: Cmd) -> FnvHashMap> { let data = rbml::Doc::new(cdata.data()); let fields = reader::get_doc(data, tag_struct_fields); reader::tagged_docs(fields, tag_struct_field).map(|field| { @@ -1107,8 +1069,7 @@ fn struct_field_family_to_visibility(family: Family) -> hir::Visibility { pub fn get_struct_field_names(intr: &IdentInterner, cdata: Cmd, id: ast::NodeId) -> Vec { - let data = cdata.data(); - let item = lookup_item(id, data); + let item = cdata.lookup_item(id); reader::tagged_docs(item, tag_item_field).map(|an_item| { item_name(intr, an_item) }).chain(reader::tagged_docs(item, tag_item_unnamed_field).map(|_| { @@ -1299,7 +1260,7 @@ pub fn each_inherent_implementation_for_type(cdata: Cmd, mut callback: F) where F: FnMut(DefId), { - let item_doc = lookup_item(id, cdata.data()); + let item_doc = cdata.lookup_item(id); for impl_doc in reader::tagged_docs(item_doc, tag_items_data_item_inherent_impl) { if reader::maybe_get_doc(impl_doc, tag_item_trait_ref).is_none() { callback(item_def_id(impl_doc, cdata)); @@ -1313,7 +1274,7 @@ pub fn each_implementation_for_trait(cdata: Cmd, F: FnMut(DefId), { if cdata.cnum == def_id.krate { - let item_doc = lookup_item(def_id.node, cdata.data()); + let item_doc = cdata.lookup_item(def_id.node); for impl_doc in reader::tagged_docs(item_doc, tag_items_data_item_extension_impl) { callback(item_def_id(impl_doc, cdata)); } @@ -1337,12 +1298,12 @@ pub fn each_implementation_for_trait(cdata: Cmd, pub fn get_trait_of_item(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt) -> Option { - let item_doc = lookup_item(id, cdata.data()); + let item_doc = cdata.lookup_item(id); let parent_item_id = match item_parent_item(cdata, item_doc) { None => return None, Some(item_id) => item_id, }; - let parent_item_doc = lookup_item(parent_item_id.node, cdata.data()); + let parent_item_doc = cdata.lookup_item(parent_item_id.node); match item_family(parent_item_doc) { Trait => Some(item_def_id(parent_item_doc, cdata)), Impl | DefaultImpl => { @@ -1423,7 +1384,7 @@ pub fn get_missing_lang_items(cdata: Cmd) } pub fn get_method_arg_names(cdata: Cmd, id: ast::NodeId) -> Vec { - let method_doc = lookup_item(id, cdata.data()); + let method_doc = cdata.lookup_item(id); match reader::maybe_get_doc(method_doc, tag_method_argument_names) { Some(args_doc) => { reader::tagged_docs(args_doc, tag_method_argument_name).map(|name_doc| { @@ -1446,7 +1407,7 @@ pub fn get_reachable_ids(cdata: Cmd) -> Vec { } pub fn is_typedef(cdata: Cmd, id: ast::NodeId) -> bool { - let item_doc = lookup_item(id, cdata.data()); + let item_doc = cdata.lookup_item(id); match item_family(item_doc) { Type => true, _ => false, @@ -1454,7 +1415,7 @@ pub fn is_typedef(cdata: Cmd, id: ast::NodeId) -> bool { } pub fn is_const_fn(cdata: Cmd, id: ast::NodeId) -> bool { - let item_doc = lookup_item(id, cdata.data()); + let item_doc = cdata.lookup_item(id); match fn_constness(item_doc) { hir::Constness::Const => true, hir::Constness::NotConst => false, @@ -1462,7 +1423,7 @@ pub fn is_const_fn(cdata: Cmd, id: ast::NodeId) -> bool { } pub fn is_impl(cdata: Cmd, id: ast::NodeId) -> bool { - let item_doc = lookup_item(id, cdata.data()); + let item_doc = cdata.lookup_item(id); match item_family(item_doc) { Impl => true, _ => false, @@ -1543,14 +1504,14 @@ fn doc_predicates<'tcx>(base_doc: rbml::Doc, } pub fn is_defaulted_trait(cdata: Cmd, trait_id: ast::NodeId) -> bool { - let trait_doc = lookup_item(trait_id, cdata.data()); + let trait_doc = cdata.lookup_item(trait_id); assert!(item_family(trait_doc) == Family::Trait); let defaulted_doc = reader::get_doc(trait_doc, tag_defaulted_trait); reader::doc_as_u8(defaulted_doc) != 0 } pub fn is_default_impl(cdata: Cmd, impl_id: ast::NodeId) -> bool { - let impl_doc = lookup_item(impl_id, cdata.data()); + let impl_doc = cdata.lookup_item(impl_id); item_family(impl_doc) == Family::DefaultImpl } @@ -1565,9 +1526,7 @@ pub fn get_imported_filemaps(metadata: &[u8]) -> Vec { } pub fn is_extern_fn(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt) -> bool { - let root_doc = rbml::Doc::new(cdata.data()); - let items = reader::get_doc(root_doc, tag_items); - let item_doc = match maybe_find_item(id, items) { + let item_doc = match cdata.get_item(id) { Some(doc) => doc, None => return false, }; diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index 563cb1cbe736b..ff24541692ecc 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -19,6 +19,7 @@ use metadata::common::*; use metadata::cstore; use metadata::decoder; use metadata::tyencode; +use metadata::index::{self, IndexEntry}; use metadata::inline::InlinedItemRef; use middle::def; use middle::def_id::{DefId, LOCAL_CRATE}; @@ -29,7 +30,6 @@ use util::nodemap::{FnvHashMap, NodeMap, NodeSet}; use serialize::Encodable; use std::cell::RefCell; -use std::hash::{Hash, Hasher, SipHasher}; use std::io::prelude::*; use std::io::{Cursor, SeekFrom}; use std::rc::Rc; @@ -86,12 +86,6 @@ fn encode_def_id(rbml_w: &mut Encoder, id: DefId) { rbml_w.wr_tagged_u64(tag_def_id, def_to_u64(id)); } -#[derive(Clone)] -struct entry { - val: T, - pos: u64 -} - fn encode_trait_ref<'a, 'tcx>(rbml_w: &mut Encoder, ecx: &EncodeContext<'a, 'tcx>, trait_ref: ty::TraitRef<'tcx>, @@ -279,7 +273,7 @@ fn encode_enum_variant_info(ecx: &EncodeContext, rbml_w: &mut Encoder, id: NodeId, vis: ast::Visibility, - index: &mut Vec>) { + index: &mut Vec) { debug!("encode_enum_variant_info(id={})", id); let mut disr_val = 0; @@ -296,8 +290,8 @@ fn encode_enum_variant_info(ecx: &EncodeContext, } } - index.push(entry { - val: vid.node as i64, + index.push(IndexEntry { + node: vid.node, pos: rbml_w.mark_stable_position(), }); rbml_w.start_tag(tag_items_data_item); @@ -625,13 +619,13 @@ fn encode_provided_source(rbml_w: &mut Encoder, fn encode_field<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>, rbml_w: &mut Encoder, field: ty::FieldDef<'tcx>, - global_index: &mut Vec>) { + global_index: &mut Vec) { let nm = field.name; let id = field.did.node; let pos = rbml_w.mark_stable_position(); - global_index.push(entry { - val: id as i64, + global_index.push(IndexEntry { + node: id, pos: pos, }); rbml_w.start_tag(tag_items_data_item); @@ -651,10 +645,10 @@ fn encode_info_for_struct_ctor(ecx: &EncodeContext, rbml_w: &mut Encoder, name: Name, ctor_id: NodeId, - index: &mut Vec>, + index: &mut Vec, struct_id: NodeId) { - index.push(entry { - val: ctor_id as i64, + index.push(IndexEntry { + node: ctor_id, pos: rbml_w.mark_stable_position(), }); @@ -989,15 +983,15 @@ fn encode_stability(rbml_w: &mut Encoder, stab_opt: Option<&attr::Stability>) { fn encode_info_for_item(ecx: &EncodeContext, rbml_w: &mut Encoder, item: &ast::Item, - index: &mut Vec>, + index: &mut Vec, path: PathElems, vis: ast::Visibility) { let tcx = ecx.tcx; fn add_to_index(item: &ast::Item, rbml_w: &mut Encoder, - index: &mut Vec>) { - index.push(entry { - val: item.id as i64, + index: &mut Vec) { + index.push(IndexEntry { + node: item.id, pos: rbml_w.mark_stable_position(), }); } @@ -1261,8 +1255,8 @@ fn encode_info_for_item(ecx: &EncodeContext, None }; - index.push(entry { - val: trait_item_def_id.def_id().node as i64, + index.push(IndexEntry { + node: trait_item_def_id.def_id().node, pos: rbml_w.mark_stable_position(), }); @@ -1352,8 +1346,8 @@ fn encode_info_for_item(ecx: &EncodeContext, for (i, &item_def_id) in r.iter().enumerate() { assert_eq!(item_def_id.def_id().krate, LOCAL_CRATE); - index.push(entry { - val: item_def_id.def_id().node as i64, + index.push(IndexEntry { + node: item_def_id.def_id().node, pos: rbml_w.mark_stable_position(), }); @@ -1474,11 +1468,11 @@ fn encode_info_for_item(ecx: &EncodeContext, fn encode_info_for_foreign_item(ecx: &EncodeContext, rbml_w: &mut Encoder, nitem: &ast::ForeignItem, - index: &mut Vec>, + index: &mut Vec, path: PathElems, abi: abi::Abi) { - index.push(entry { - val: nitem.id as i64, + index.push(IndexEntry { + node: nitem.id, pos: rbml_w.mark_stable_position(), }); @@ -1522,7 +1516,7 @@ fn my_visit_expr(_e: &ast::Expr) { } fn my_visit_item(i: &ast::Item, rbml_w: &mut Encoder, ecx: &EncodeContext, - index: &mut Vec>) { + index: &mut Vec) { ecx.tcx.map.with_path(i.id, |path| { encode_info_for_item(ecx, rbml_w, i, index, path, i.vis); }); @@ -1531,7 +1525,7 @@ fn my_visit_item(i: &ast::Item, fn my_visit_foreign_item(ni: &ast::ForeignItem, rbml_w: &mut Encoder, ecx: &EncodeContext, - index: &mut Vec>) { + index: &mut Vec) { debug!("writing foreign item {}::{}", ecx.tcx.map.path_to_string(ni.id), ni.ident); @@ -1547,7 +1541,7 @@ fn my_visit_foreign_item(ni: &ast::ForeignItem, struct EncodeVisitor<'a, 'b:'a, 'c:'a, 'tcx:'c> { rbml_w_for_visit_item: &'a mut Encoder<'b>, ecx: &'a EncodeContext<'c,'tcx>, - index: &'a mut Vec>, + index: &'a mut Vec, } impl<'a, 'b, 'c, 'tcx, 'v> Visitor<'v> for EncodeVisitor<'a, 'b, 'c, 'tcx> { @@ -1574,11 +1568,11 @@ impl<'a, 'b, 'c, 'tcx, 'v> Visitor<'v> for EncodeVisitor<'a, 'b, 'c, 'tcx> { fn encode_info_for_items(ecx: &EncodeContext, rbml_w: &mut Encoder, krate: &ast::Crate) - -> Vec> { + -> Vec { let mut index = Vec::new(); rbml_w.start_tag(tag_items_data); - index.push(entry { - val: CRATE_NODE_ID as i64, + index.push(IndexEntry { + node: CRATE_NODE_ID, pos: rbml_w.mark_stable_position(), }); encode_info_for_mod(ecx, @@ -1601,62 +1595,13 @@ fn encode_info_for_items(ecx: &EncodeContext, } -// Path and definition ID indexing -fn encode_index(rbml_w: &mut Encoder, index: Vec>, mut write_fn: F) where - F: FnMut(&mut Cursor>, &T), - T: Hash, -{ - let mut buckets: Vec>> = (0..256u16).map(|_| Vec::new()).collect(); - for elt in index { - let mut s = SipHasher::new(); - elt.val.hash(&mut s); - let h = s.finish() as usize; - (&mut buckets[h % 256]).push(elt); - } +fn encode_index(rbml_w: &mut Encoder, index: Vec) +{ rbml_w.start_tag(tag_index); - let mut bucket_locs = Vec::new(); - rbml_w.start_tag(tag_index_buckets); - for bucket in &buckets { - bucket_locs.push(rbml_w.mark_stable_position()); - rbml_w.start_tag(tag_index_buckets_bucket); - for elt in bucket { - rbml_w.start_tag(tag_index_buckets_bucket_elt); - assert!(elt.pos < 0xffff_ffff); - { - let wr: &mut Cursor> = rbml_w.writer; - write_be_u32(wr, elt.pos as u32); - } - write_fn(rbml_w.writer, &elt.val); - rbml_w.end_tag(); - } - rbml_w.end_tag(); - } + index::write_index(index, rbml_w.writer); rbml_w.end_tag(); - rbml_w.start_tag(tag_index_table); - for pos in &bucket_locs { - assert!(*pos < 0xffff_ffff); - let wr: &mut Cursor> = rbml_w.writer; - write_be_u32(wr, *pos as u32); - } - rbml_w.end_tag(); - rbml_w.end_tag(); -} - -fn write_i64(writer: &mut Cursor>, &n: &i64) { - let wr: &mut Cursor> = writer; - assert!(n < 0x7fff_ffff); - write_be_u32(wr, n as u32); -} - -fn write_be_u32(w: &mut Write, u: u32) { - w.write_all(&[ - (u >> 24) as u8, - (u >> 16) as u8, - (u >> 8) as u8, - (u >> 0) as u8, - ]); } fn encode_meta_item(rbml_w: &mut Encoder, mi: &ast::MetaItem) { @@ -2160,11 +2105,11 @@ fn encode_metadata_inner(wr: &mut Cursor>, i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap(); let items_index = encode_info_for_items(&ecx, &mut rbml_w, krate); stats.item_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i; + rbml_w.end_tag(); i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap(); - encode_index(&mut rbml_w, items_index, write_i64); + encode_index(&mut rbml_w, items_index); stats.index_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i; - rbml_w.end_tag(); encode_struct_field_attrs(&mut rbml_w, krate); diff --git a/src/librustc/metadata/index.rs b/src/librustc/metadata/index.rs new file mode 100644 index 0000000000000..b02a9022a7a6e --- /dev/null +++ b/src/librustc/metadata/index.rs @@ -0,0 +1,208 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::io::{Cursor, Write}; +use std::slice; +use std::u32; +use syntax::ast::NodeId; + +#[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord)] +pub struct IndexEntry { + pub node: NodeId, + pub pos: u64 +} + +#[derive(Debug)] +pub struct IndexArrayEntry { + bits: u32, + first_pos: u32 +} + +impl IndexArrayEntry { + fn encode_to(&self, b: &mut W) { + write_be_u32(b, self.bits); + write_be_u32(b, self.first_pos); + } + + fn decode_from(b: &[u32]) -> Self { + IndexArrayEntry { + bits: b[0].to_be(), + first_pos: b[1].to_be() + } + } +} + +/// The Item Index +/// +/// This index maps the NodeId of each item to its location in the +/// metadata. +/// +/// The index is a sparse bit-vector consisting of a index-array +/// and a position-array. Each entry in the index-array handles 32 nodes. +/// The first word is a bit-array consisting of the nodes that hold items, +/// the second is the index of the first of the items in the position-array. +/// If there is a large set of non-item trailing nodes, they can be omitted +/// from the index-array. +/// +/// The index is serialized as an array of big-endian 32-bit words. +/// The first word is the number of items in the position-array. +/// Then, for each item, its position in the metadata follows. +/// After that the index-array is stored. +/// +/// struct index { +/// u32 item_count; +/// u32 items[self.item_count]; +/// struct { u32 bits; u32 offset; } positions[..]; +/// } +pub struct Index { + position_start: usize, + index_start: usize, + index_end: usize, +} + +pub fn write_index(mut entries: Vec, buf: &mut Cursor>) { + assert!(entries.len() < u32::MAX as usize); + entries.sort(); + + let mut last_entry = IndexArrayEntry { bits: 0, first_pos: 0 }; + + write_be_u32(buf, entries.len() as u32); + for &IndexEntry { pos, .. } in &entries { + assert!(pos < u32::MAX as u64); + write_be_u32(buf, pos as u32); + } + + let mut pos_in_index_array = 0; + for (i, &IndexEntry { node, .. }) in entries.iter().enumerate() { + let (x, s) = (node / 32 as u32, node % 32 as u32); + while x > pos_in_index_array { + pos_in_index_array += 1; + last_entry.encode_to(buf); + last_entry = IndexArrayEntry { bits: 0, first_pos: i as u32 }; + } + last_entry.bits |= 1< Option { + let ix = (i as usize)*2; + if ix >= index.len() { + None + } else { + Some(IndexArrayEntry::decode_from(&index[ix..ix+2])) + } + } + + fn item_from_pos(&self, positions: &[u32], pos: u32) -> u32 { + positions[pos as usize].to_be() + } + + #[inline(never)] + pub fn lookup_item(&self, buf: &[u8], node: NodeId) -> Option { + let index = bytes_to_words(&buf[self.index_start..self.index_end]); + let positions = bytes_to_words(&buf[self.position_start..self.index_start]); + let (x, s) = (node / 32 as u32, node % 32 as u32); + let result = match self.lookup_index(index, x) { + Some(IndexArrayEntry { bits, first_pos }) => { + let bit = 1< None // trailing zero + }; + debug!("lookup_item({:?}) = {:?}", node, result); + result + } + + pub fn from_buf(buf: &[u8], start: usize, end: usize) -> Self { + let buf = bytes_to_words(&buf[start..end]); + let position_count = buf[0].to_be() as usize; + let position_len = position_count*4; + info!("loaded index - position: {}-{}-{}", start, start+position_len, end); + debug!("index contents are {:?}", + buf.iter().map(|b| format!("{:08x}", b)).collect::>().concat()); + assert!(end-4-start >= position_len); + assert_eq!((end-4-start-position_len)%8, 0); + Index { + position_start: start+4, + index_start: start+position_len+4, + index_end: end + } + } +} + +fn write_be_u32(w: &mut W, u: u32) { + let _ = w.write_all(&[ + (u >> 24) as u8, + (u >> 16) as u8, + (u >> 8) as u8, + (u >> 0) as u8, + ]); +} + +fn bytes_to_words(b: &[u8]) -> &[u32] { + assert!(b.len() % 4 == 0); + unsafe { slice::from_raw_parts(b.as_ptr() as *const u32, b.len()/4) } +} + +#[test] +fn test_index() { + let entries = vec![ + IndexEntry { node: 0, pos: 17 }, + IndexEntry { node: 31, pos: 29 }, + IndexEntry { node: 32, pos: 1175 }, + IndexEntry { node: 191, pos: 21 }, + IndexEntry { node: 128, pos: 34 }, + IndexEntry { node: 145, pos: 70 }, + IndexEntry { node: 305, pos: 93214 }, + IndexEntry { node: 138, pos: 64 }, + IndexEntry { node: 129, pos: 53 }, + IndexEntry { node: 192, pos: 33334 }, + IndexEntry { node: 200, pos: 80123 }, + ]; + let mut c = Cursor::new(vec![]); + write_index(entries.clone(), &mut c); + let mut buf = c.into_inner(); + let expected: &[u8] = &[ + 0, 0, 0, 11, // # entries + // values: + 0,0,0,17, 0,0,0,29, 0,0,4,151, 0,0,0,34, + 0,0,0,53, 0,0,0,64, 0,0,0,70, 0,0,0,21, + 0,0,130,54, 0,1,56,251, 0,1,108,30, + // index: + 128,0,0,1,0,0,0,0, 0,0,0,1,0,0,0,2, + 0,0,0,0,0,0,0,3, 0,0,0,0,0,0,0,3, + 0,2,4,3,0,0,0,3, 128,0,0,0,0,0,0,7, + 0,0,1,1,0,0,0,8, 0,0,0,0,0,0,0,10, + 0,0,0,0,0,0,0,10, 0,2,0,0,0,0,0,10 + ]; + assert_eq!(buf, expected); + + // insert some junk padding + for i in 0..17 { buf.insert(0, i); buf.push(i) } + let index = Index::from_buf(&buf, 17, buf.len()-17); + + // test round-trip + for i in 0..4096 { + assert_eq!(index.lookup_item(&buf, i), + entries.iter().find(|e| e.node == i).map(|n| n.pos as u32)); + } +} diff --git a/src/librustc/metadata/mod.rs b/src/librustc/metadata/mod.rs index 44901eb054791..e532388d52ed8 100644 --- a/src/librustc/metadata/mod.rs +++ b/src/librustc/metadata/mod.rs @@ -16,6 +16,7 @@ pub mod decoder; pub mod creader; pub mod cstore; pub mod csearch; +pub mod index; pub mod loader; pub mod filesearch; pub mod macro_import; From b6a397888689a22803bb364f74177e855b64c680 Mon Sep 17 00:00:00 2001 From: llogiq Date: Thu, 3 Sep 2015 12:35:34 +0200 Subject: [PATCH 08/14] clippy improvements to iterators --- src/libcore/iter.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index 3d17b10ba3a85..53b72fe2ba795 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -1513,7 +1513,7 @@ impl Iterator for Chain where fn next(&mut self) -> Option { match self.state { ChainState::Both => match self.a.next() { - elt @ Some(..) => return elt, + elt @ Some(..) => elt, None => { self.state = ChainState::Back; self.b.next() @@ -1590,7 +1590,7 @@ impl DoubleEndedIterator for Chain where fn next_back(&mut self) -> Option { match self.state { ChainState::Both => match self.b.next_back() { - elt @ Some(..) => return elt, + elt @ Some(..) => elt, None => { self.state = ChainState::Front; self.a.next_back() @@ -1683,7 +1683,7 @@ impl Iterator for Map where F: FnMut(I::Item) -> B { #[inline] fn next(&mut self) -> Option { - self.iter.next().map(|a| (self.f)(a)) + self.iter.next().map(self.f) } #[inline] @@ -1698,7 +1698,7 @@ impl DoubleEndedIterator for Map where { #[inline] fn next_back(&mut self) -> Option { - self.iter.next_back().map(|a| (self.f)(a)) + self.iter.next_back().map(self.f) } } @@ -2210,7 +2210,7 @@ impl Iterator for FlatMap return Some(x) } } - match self.iter.next().map(|x| (self.f)(x)) { + match self.iter.next().map(self.f) { None => return self.backiter.as_mut().and_then(|it| it.next()), next => self.frontiter = next.map(IntoIterator::into_iter), } @@ -2243,7 +2243,7 @@ impl DoubleEndedIterator for FlatMap wher return Some(y) } } - match self.iter.next_back().map(|x| (self.f)(x)) { + match self.iter.next_back().map(self.f) { None => return self.frontiter.as_mut().and_then(|it| it.next_back()), next => self.backiter = next.map(IntoIterator::into_iter), } From a520568ae7dea13430c3d9ba5b3fb9596d863791 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Thu, 3 Sep 2015 15:19:08 +0530 Subject: [PATCH 09/14] Elide lifetimes in libcore --- src/libcore/cell.rs | 14 ++-- src/libcore/nonzero.rs | 2 +- src/libcore/num/flt2dec/bignum.rs | 10 +-- src/libcore/num/flt2dec/strategy/dragon.rs | 4 +- src/libcore/ops.rs | 8 +-- src/libcore/option.rs | 8 +-- src/libcore/ptr.rs | 2 +- src/libcore/slice.rs | 74 +++++++++++----------- src/libcore/str/mod.rs | 22 +++---- 9 files changed, 72 insertions(+), 72 deletions(-) diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs index 06eb22278080a..d37f5169af1df 100644 --- a/src/libcore/cell.rs +++ b/src/libcore/cell.rs @@ -231,7 +231,7 @@ impl Cell { /// ``` #[inline] #[unstable(feature = "as_unsafe_cell", issue = "27708")] - pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell { + pub unsafe fn as_unsafe_cell(&self) -> &UnsafeCell { &self.value } } @@ -387,7 +387,7 @@ impl RefCell { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn borrow<'a>(&'a self) -> Ref<'a, T> { + pub fn borrow(&self) -> Ref { match BorrowRef::new(&self.borrow) { Some(b) => Ref { _value: unsafe { &*self.value.get() }, @@ -433,7 +433,7 @@ impl RefCell { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn borrow_mut<'a>(&'a self) -> RefMut<'a, T> { + pub fn borrow_mut(&self) -> RefMut { match BorrowRefMut::new(&self.borrow) { Some(b) => RefMut { _value: unsafe { &mut *self.value.get() }, @@ -450,7 +450,7 @@ impl RefCell { /// This function is `unsafe` because `UnsafeCell`'s field is public. #[inline] #[unstable(feature = "as_unsafe_cell", issue = "27708")] - pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell { + pub unsafe fn as_unsafe_cell(&self) -> &UnsafeCell { &self.value } } @@ -541,7 +541,7 @@ impl<'b, T: ?Sized> Deref for Ref<'b, T> { type Target = T; #[inline] - fn deref<'a>(&'a self) -> &'a T { + fn deref(&self) -> &T { self._value } } @@ -750,7 +750,7 @@ impl<'b, T: ?Sized> Deref for RefMut<'b, T> { type Target = T; #[inline] - fn deref<'a>(&'a self) -> &'a T { + fn deref(&self) -> &T { self._value } } @@ -758,7 +758,7 @@ impl<'b, T: ?Sized> Deref for RefMut<'b, T> { #[stable(feature = "rust1", since = "1.0.0")] impl<'b, T: ?Sized> DerefMut for RefMut<'b, T> { #[inline] - fn deref_mut<'a>(&'a mut self) -> &'a mut T { + fn deref_mut(&mut self) -> &mut T { self._value } } diff --git a/src/libcore/nonzero.rs b/src/libcore/nonzero.rs index 2524e5662aa84..c945e4e066159 100644 --- a/src/libcore/nonzero.rs +++ b/src/libcore/nonzero.rs @@ -51,7 +51,7 @@ impl Deref for NonZero { type Target = T; #[inline] - fn deref<'a>(&'a self) -> &'a T { + fn deref(&self) -> &T { let NonZero(ref inner) = *self; inner } diff --git a/src/libcore/num/flt2dec/bignum.rs b/src/libcore/num/flt2dec/bignum.rs index ee2ffbffab654..091e9c889da47 100644 --- a/src/libcore/num/flt2dec/bignum.rs +++ b/src/libcore/num/flt2dec/bignum.rs @@ -211,7 +211,7 @@ macro_rules! define_bignum { self } - pub fn add_small<'a>(&'a mut self, other: $ty) -> &'a mut $name { + pub fn add_small(&mut self, other: $ty) -> &mut $name { use num::flt2dec::bignum::FullOps; let (mut carry, v) = self.base[0].full_add(other, false); @@ -248,7 +248,7 @@ macro_rules! define_bignum { /// Multiplies itself by a digit-sized `other` and returns its own /// mutable reference. - pub fn mul_small<'a>(&'a mut self, other: $ty) -> &'a mut $name { + pub fn mul_small(&mut self, other: $ty) -> &mut $name { use num::flt2dec::bignum::FullOps; let mut sz = self.size; @@ -267,7 +267,7 @@ macro_rules! define_bignum { } /// Multiplies itself by `2^bits` and returns its own mutable reference. - pub fn mul_pow2<'a>(&'a mut self, bits: usize) -> &'a mut $name { + pub fn mul_pow2(&mut self, bits: usize) -> &mut $name { use mem; let digitbits = mem::size_of::<$ty>() * 8; @@ -308,7 +308,7 @@ macro_rules! define_bignum { } /// Multiplies itself by `5^e` and returns its own mutable reference. - pub fn mul_pow5<'a>(&'a mut self, mut e: usize) -> &'a mut $name { + pub fn mul_pow5(&mut self, mut e: usize) -> &mut $name { use mem; use num::flt2dec::bignum::SMALL_POW5; @@ -377,7 +377,7 @@ macro_rules! define_bignum { /// Divides itself by a digit-sized `other` and returns its own /// mutable reference *and* the remainder. - pub fn div_rem_small<'a>(&'a mut self, other: $ty) -> (&'a mut $name, $ty) { + pub fn div_rem_small(&mut self, other: $ty) -> (&mut $name, $ty) { use num::flt2dec::bignum::FullOps; assert!(other > 0); diff --git a/src/libcore/num/flt2dec/strategy/dragon.rs b/src/libcore/num/flt2dec/strategy/dragon.rs index ab610f28e9eca..40aa2a527dbc5 100644 --- a/src/libcore/num/flt2dec/strategy/dragon.rs +++ b/src/libcore/num/flt2dec/strategy/dragon.rs @@ -42,7 +42,7 @@ static POW10TO256: [Digit; 27] = 0xcc5573c0, 0x65f9ef17, 0x55bc28f2, 0x80dcc7f7, 0xf46eeddc, 0x5fdcefce, 0x553f7]; #[doc(hidden)] -pub fn mul_pow10<'a>(x: &'a mut Big, n: usize) -> &'a mut Big { +pub fn mul_pow10(x: &mut Big, n: usize) -> &mut Big { debug_assert!(n < 512); if n & 7 != 0 { x.mul_small(POW10[n & 7]); } if n & 8 != 0 { x.mul_small(POW10[8]); } @@ -54,7 +54,7 @@ pub fn mul_pow10<'a>(x: &'a mut Big, n: usize) -> &'a mut Big { x } -fn div_2pow10<'a>(x: &'a mut Big, mut n: usize) -> &'a mut Big { +fn div_2pow10(x: &mut Big, mut n: usize) -> &mut Big { let largest = POW10.len() - 1; while n > largest { x.div_rem_small(POW10[largest]); diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs index 3fb720ab6c83c..07de4d0761baa 100644 --- a/src/libcore/ops.rs +++ b/src/libcore/ops.rs @@ -965,7 +965,7 @@ pub trait Index { /// The method for the indexing (`Foo[Bar]`) operation #[stable(feature = "rust1", since = "1.0.0")] - fn index<'a>(&'a self, index: Idx) -> &'a Self::Output; + fn index(&self, index: Idx) -> &Self::Output; } /// The `IndexMut` trait is used to specify the functionality of indexing @@ -1008,7 +1008,7 @@ pub trait Index { pub trait IndexMut: Index { /// The method for the indexing (`Foo[Bar]`) operation #[stable(feature = "rust1", since = "1.0.0")] - fn index_mut<'a>(&'a mut self, index: Idx) -> &'a mut Self::Output; + fn index_mut(&mut self, index: Idx) -> &mut Self::Output; } /// An unbounded range. @@ -1119,7 +1119,7 @@ pub trait Deref { /// The method called to dereference a value #[stable(feature = "rust1", since = "1.0.0")] - fn deref<'a>(&'a self) -> &'a Self::Target; + fn deref(&self) -> &Self::Target; } #[stable(feature = "rust1", since = "1.0.0")] @@ -1180,7 +1180,7 @@ impl<'a, T: ?Sized> Deref for &'a mut T { pub trait DerefMut: Deref { /// The method called to mutably dereference a value #[stable(feature = "rust1", since = "1.0.0")] - fn deref_mut<'a>(&'a mut self) -> &'a mut Self::Target; + fn deref_mut(&mut self) -> &mut Self::Target; } #[stable(feature = "rust1", since = "1.0.0")] diff --git a/src/libcore/option.rs b/src/libcore/option.rs index a36a120689cc6..1434617baddce 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -241,7 +241,7 @@ impl Option { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - pub fn as_ref<'r>(&'r self) -> Option<&'r T> { + pub fn as_ref(&self) -> Option<&T> { match *self { Some(ref x) => Some(x), None => None, @@ -262,7 +262,7 @@ impl Option { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - pub fn as_mut<'r>(&'r mut self) -> Option<&'r mut T> { + pub fn as_mut(&mut self) -> Option<&mut T> { match *self { Some(ref mut x) => Some(x), None => None, @@ -289,7 +289,7 @@ impl Option { #[unstable(feature = "as_slice", reason = "waiting for mut conventions", issue = "27776")] - pub fn as_mut_slice<'r>(&'r mut self) -> &'r mut [T] { + pub fn as_mut_slice(&mut self) -> &mut [T] { match *self { Some(ref mut x) => { let result: &mut [T] = slice::mut_ref_slice(x); @@ -692,7 +692,7 @@ impl Option { #[inline] #[unstable(feature = "as_slice", since = "unsure of the utility here", issue = "27776")] - pub fn as_slice<'a>(&'a self) -> &'a [T] { + pub fn as_slice(&self) -> &[T] { match *self { Some(ref x) => slice::ref_slice(x), None => { diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index b7479b0c604f3..142130aad9f2b 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -468,7 +468,7 @@ impl Deref for Unique { type Target = *mut T; #[inline] - fn deref<'a>(&'a self) -> &'a *mut T { + fn deref(&self) -> &*mut T { unsafe { mem::transmute(&*self.pointer) } } } diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index fdd5e61c8f27b..cf605f507bca6 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -69,48 +69,48 @@ use raw::Slice as RawSlice; pub trait SliceExt { type Item; - fn split_at<'a>(&'a self, mid: usize) -> (&'a [Self::Item], &'a [Self::Item]); - fn iter<'a>(&'a self) -> Iter<'a, Self::Item>; - fn split<'a, P>(&'a self, pred: P) -> Split<'a, Self::Item, P> + fn split_at(&self, mid: usize) -> (&[Self::Item], &[Self::Item]); + fn iter(&self) -> Iter; + fn split

(&self, pred: P) -> Split where P: FnMut(&Self::Item) -> bool; - fn splitn<'a, P>(&'a self, n: usize, pred: P) -> SplitN<'a, Self::Item, P> + fn splitn

(&self, n: usize, pred: P) -> SplitN where P: FnMut(&Self::Item) -> bool; - fn rsplitn<'a, P>(&'a self, n: usize, pred: P) -> RSplitN<'a, Self::Item, P> + fn rsplitn

(&self, n: usize, pred: P) -> RSplitN where P: FnMut(&Self::Item) -> bool; - fn windows<'a>(&'a self, size: usize) -> Windows<'a, Self::Item>; - fn chunks<'a>(&'a self, size: usize) -> Chunks<'a, Self::Item>; - fn get<'a>(&'a self, index: usize) -> Option<&'a Self::Item>; - fn first<'a>(&'a self) -> Option<&'a Self::Item>; - fn tail<'a>(&'a self) -> &'a [Self::Item]; - fn init<'a>(&'a self) -> &'a [Self::Item]; - fn split_first<'a>(&'a self) -> Option<(&'a Self::Item, &'a [Self::Item])>; - fn split_last<'a>(&'a self) -> Option<(&'a Self::Item, &'a [Self::Item])>; - fn last<'a>(&'a self) -> Option<&'a Self::Item>; - unsafe fn get_unchecked<'a>(&'a self, index: usize) -> &'a Self::Item; + fn windows(&self, size: usize) -> Windows; + fn chunks(&self, size: usize) -> Chunks; + fn get(&self, index: usize) -> Option<&Self::Item>; + fn first(&self) -> Option<&Self::Item>; + fn tail(&self) -> &[Self::Item]; + fn init(&self) -> &[Self::Item]; + fn split_first(&self) -> Option<(&Self::Item, &[Self::Item])>; + fn split_last(&self) -> Option<(&Self::Item, &[Self::Item])>; + fn last(&self) -> Option<&Self::Item>; + unsafe fn get_unchecked(&self, index: usize) -> &Self::Item; fn as_ptr(&self) -> *const Self::Item; fn binary_search_by(&self, f: F) -> Result where F: FnMut(&Self::Item) -> Ordering; fn len(&self) -> usize; fn is_empty(&self) -> bool { self.len() == 0 } - fn get_mut<'a>(&'a mut self, index: usize) -> Option<&'a mut Self::Item>; - fn iter_mut<'a>(&'a mut self) -> IterMut<'a, Self::Item>; - fn first_mut<'a>(&'a mut self) -> Option<&'a mut Self::Item>; - fn tail_mut<'a>(&'a mut self) -> &'a mut [Self::Item]; - fn init_mut<'a>(&'a mut self) -> &'a mut [Self::Item]; - fn split_first_mut<'a>(&'a mut self) -> Option<(&'a mut Self::Item, &'a mut [Self::Item])>; - fn split_last_mut<'a>(&'a mut self) -> Option<(&'a mut Self::Item, &'a mut [Self::Item])>; - fn last_mut<'a>(&'a mut self) -> Option<&'a mut Self::Item>; - fn split_mut<'a, P>(&'a mut self, pred: P) -> SplitMut<'a, Self::Item, P> + fn get_mut(&mut self, index: usize) -> Option<&mut Self::Item>; + fn iter_mut(&mut self) -> IterMut; + fn first_mut(&mut self) -> Option<&mut Self::Item>; + fn tail_mut(&mut self) -> &mut [Self::Item]; + fn init_mut(&mut self) -> &mut [Self::Item]; + fn split_first_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>; + fn split_last_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>; + fn last_mut(&mut self) -> Option<&mut Self::Item>; + fn split_mut

(&mut self, pred: P) -> SplitMut where P: FnMut(&Self::Item) -> bool; fn splitn_mut

(&mut self, n: usize, pred: P) -> SplitNMut where P: FnMut(&Self::Item) -> bool; fn rsplitn_mut

(&mut self, n: usize, pred: P) -> RSplitNMut where P: FnMut(&Self::Item) -> bool; - fn chunks_mut<'a>(&'a mut self, chunk_size: usize) -> ChunksMut<'a, Self::Item>; + fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut; fn swap(&mut self, a: usize, b: usize); - fn split_at_mut<'a>(&'a mut self, mid: usize) -> (&'a mut [Self::Item], &'a mut [Self::Item]); + fn split_at_mut(&mut self, mid: usize) -> (&mut [Self::Item], &mut [Self::Item]); fn reverse(&mut self); - unsafe fn get_unchecked_mut<'a>(&'a mut self, index: usize) -> &'a mut Self::Item; + unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut Self::Item; fn as_mut_ptr(&mut self) -> *mut Self::Item; fn position_elem(&self, t: &Self::Item) -> Option where Self::Item: PartialEq; @@ -163,7 +163,7 @@ impl SliceExt for [T] { } #[inline] - fn iter<'a>(&'a self) -> Iter<'a, T> { + fn iter(&self) -> Iter { unsafe { let p = if mem::size_of::() == 0 { 1 as *const _ @@ -182,7 +182,7 @@ impl SliceExt for [T] { } #[inline] - fn split<'a, P>(&'a self, pred: P) -> Split<'a, T, P> where P: FnMut(&T) -> bool { + fn split

(&self, pred: P) -> Split where P: FnMut(&T) -> bool { Split { v: self, pred: pred, @@ -191,7 +191,7 @@ impl SliceExt for [T] { } #[inline] - fn splitn<'a, P>(&'a self, n: usize, pred: P) -> SplitN<'a, T, P> where + fn splitn

(&self, n: usize, pred: P) -> SplitN where P: FnMut(&T) -> bool, { SplitN { @@ -204,7 +204,7 @@ impl SliceExt for [T] { } #[inline] - fn rsplitn<'a, P>(&'a self, n: usize, pred: P) -> RSplitN<'a, T, P> where + fn rsplitn

(&self, n: usize, pred: P) -> RSplitN where P: FnMut(&T) -> bool, { RSplitN { @@ -311,7 +311,7 @@ impl SliceExt for [T] { } #[inline] - fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> { + fn iter_mut(&mut self) -> IterMut { unsafe { let p = if mem::size_of::() == 0 { 1 as *mut _ @@ -368,12 +368,12 @@ impl SliceExt for [T] { } #[inline] - fn split_mut<'a, P>(&'a mut self, pred: P) -> SplitMut<'a, T, P> where P: FnMut(&T) -> bool { + fn split_mut

(&mut self, pred: P) -> SplitMut where P: FnMut(&T) -> bool { SplitMut { v: self, pred: pred, finished: false } } #[inline] - fn splitn_mut<'a, P>(&'a mut self, n: usize, pred: P) -> SplitNMut<'a, T, P> where + fn splitn_mut

(&mut self, n: usize, pred: P) -> SplitNMut where P: FnMut(&T) -> bool { SplitNMut { @@ -386,7 +386,7 @@ impl SliceExt for [T] { } #[inline] - fn rsplitn_mut<'a, P>(&'a mut self, n: usize, pred: P) -> RSplitNMut<'a, T, P> where + fn rsplitn_mut

(&mut self, n: usize, pred: P) -> RSplitNMut where P: FnMut(&T) -> bool, { RSplitNMut { @@ -1410,7 +1410,7 @@ impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {} /// Converts a pointer to A into a slice of length 1 (without copying). #[unstable(feature = "ref_slice", issue = "27774")] -pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] { +pub fn ref_slice(s: &A) -> &[A] { unsafe { from_raw_parts(s, 1) } @@ -1418,7 +1418,7 @@ pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] { /// Converts a pointer to A into a slice of length 1 (without copying). #[unstable(feature = "ref_slice", issue = "27774")] -pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] { +pub fn mut_ref_slice(s: &mut A) -> &mut [A] { unsafe { from_raw_parts_mut(s, 1) } diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index 7d32f61b3dd71..4612fc8900861 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -142,7 +142,7 @@ pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> { /// that the string contains valid UTF-8. #[inline(always)] #[stable(feature = "rust1", since = "1.0.0")] -pub unsafe fn from_utf8_unchecked<'a>(v: &'a [u8]) -> &'a str { +pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str { mem::transmute(v) } @@ -1270,9 +1270,9 @@ pub trait StrExt { fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool; fn contains_char<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool; - fn chars<'a>(&'a self) -> Chars<'a>; - fn bytes<'a>(&'a self) -> Bytes<'a>; - fn char_indices<'a>(&'a self) -> CharIndices<'a>; + fn chars(&self) -> Chars; + fn bytes(&self) -> Bytes; + fn char_indices(&self) -> CharIndices; fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P>; fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P> where P::Searcher: ReverseSearcher<'a>; @@ -1288,12 +1288,12 @@ pub trait StrExt { fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P>; fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P> where P::Searcher: ReverseSearcher<'a>; - fn lines<'a>(&'a self) -> Lines<'a>; - fn lines_any<'a>(&'a self) -> LinesAny<'a>; + fn lines(&self) -> Lines; + fn lines_any(&self) -> LinesAny; fn char_len(&self) -> usize; - fn slice_chars<'a>(&'a self, begin: usize, end: usize) -> &'a str; - unsafe fn slice_unchecked<'a>(&'a self, begin: usize, end: usize) -> &'a str; - unsafe fn slice_mut_unchecked<'a>(&'a mut self, begin: usize, end: usize) -> &'a mut str; + fn slice_chars(&self, begin: usize, end: usize) -> &str; + unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str; + unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str; fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool; fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool where P::Searcher: ReverseSearcher<'a>; @@ -1307,14 +1307,14 @@ pub trait StrExt { fn char_range_at_reverse(&self, start: usize) -> CharRange; fn char_at(&self, i: usize) -> char; fn char_at_reverse(&self, i: usize) -> char; - fn as_bytes<'a>(&'a self) -> &'a [u8]; + fn as_bytes(&self) -> &[u8]; fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option; fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option where P::Searcher: ReverseSearcher<'a>; fn find_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option; fn split_at(&self, mid: usize) -> (&str, &str); fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str); - fn slice_shift_char<'a>(&'a self) -> Option<(char, &'a str)>; + fn slice_shift_char(&self) -> Option<(char, &str)>; fn subslice_offset(&self, inner: &str) -> usize; fn as_ptr(&self) -> *const u8; fn len(&self) -> usize; From e1f89196a06c9c6689f2b21cc5123a5a8af8f1a2 Mon Sep 17 00:00:00 2001 From: llogiq Date: Thu, 3 Sep 2015 14:50:06 +0200 Subject: [PATCH 10/14] take mapped function by mutable reference --- src/libcore/iter.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index 53b72fe2ba795..97dcb2475a3cf 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -1683,7 +1683,7 @@ impl Iterator for Map where F: FnMut(I::Item) -> B { #[inline] fn next(&mut self) -> Option { - self.iter.next().map(self.f) + self.iter.next().map(&mut self.f) } #[inline] @@ -1698,7 +1698,7 @@ impl DoubleEndedIterator for Map where { #[inline] fn next_back(&mut self) -> Option { - self.iter.next_back().map(self.f) + self.iter.next_back().map(&mut self.f) } } @@ -2210,7 +2210,7 @@ impl Iterator for FlatMap return Some(x) } } - match self.iter.next().map(self.f) { + match self.iter.next().map(&mut self.f) { None => return self.backiter.as_mut().and_then(|it| it.next()), next => self.frontiter = next.map(IntoIterator::into_iter), } @@ -2243,7 +2243,7 @@ impl DoubleEndedIterator for FlatMap wher return Some(y) } } - match self.iter.next_back().map(self.f) { + match self.iter.next_back().map(&mut self.f) { None => return self.frontiter.as_mut().and_then(|it| it.next_back()), next => self.backiter = next.map(IntoIterator::into_iter), } From e5e4744766aee3767749e01c621d299315ee56b0 Mon Sep 17 00:00:00 2001 From: Dave Huseby Date: Thu, 3 Sep 2015 07:25:21 -0700 Subject: [PATCH 11/14] Fixes #27886 -- bitrig does not use jemalloc (yet) --- src/test/compile-fail/allocator-dylib-is-system.rs | 1 + src/test/compile-fail/allocator-rust-dylib-is-jemalloc.rs | 1 + src/test/run-pass/allocator-default.rs | 4 ++-- src/test/run-pass/allocator-jemalloc.rs | 1 + 4 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/test/compile-fail/allocator-dylib-is-system.rs b/src/test/compile-fail/allocator-dylib-is-system.rs index 6c21f77c9a669..35bfc0c7d4fa5 100644 --- a/src/test/compile-fail/allocator-dylib-is-system.rs +++ b/src/test/compile-fail/allocator-dylib-is-system.rs @@ -10,6 +10,7 @@ // ignore-msvc everything is the system allocator on msvc // ignore-musl no dylibs on musl yet +// ignore-bitrig no jemalloc on bitrig // aux-build:allocator-dylib.rs // no-prefer-dynamic // error-pattern: cannot link together two allocators diff --git a/src/test/compile-fail/allocator-rust-dylib-is-jemalloc.rs b/src/test/compile-fail/allocator-rust-dylib-is-jemalloc.rs index 8ba48f6a52530..23f9efa2e6446 100644 --- a/src/test/compile-fail/allocator-rust-dylib-is-jemalloc.rs +++ b/src/test/compile-fail/allocator-rust-dylib-is-jemalloc.rs @@ -10,6 +10,7 @@ // ignore-msvc everything is the system allocator on msvc // ignore-musl no dylibs on musl right now +// ignore-bitrig no jemalloc on bitrig // aux-build:allocator-dylib2.rs // error-pattern: cannot link together two allocators diff --git a/src/test/run-pass/allocator-default.rs b/src/test/run-pass/allocator-default.rs index 1bca39de6635d..1dbdc5e4a5004 100644 --- a/src/test/run-pass/allocator-default.rs +++ b/src/test/run-pass/allocator-default.rs @@ -10,9 +10,9 @@ #![feature(alloc_jemalloc, alloc_system)] -#[cfg(not(target_env = "msvc"))] +#[cfg(not(any(target_env = "msvc", target_os = "bitrig")))] extern crate alloc_jemalloc; -#[cfg(target_env = "msvc")] +#[cfg(any(target_env = "msvc", target_os = "bitrig"))] extern crate alloc_system; fn main() { diff --git a/src/test/run-pass/allocator-jemalloc.rs b/src/test/run-pass/allocator-jemalloc.rs index 77fa64ec3db07..780c5e5884fae 100644 --- a/src/test/run-pass/allocator-jemalloc.rs +++ b/src/test/run-pass/allocator-jemalloc.rs @@ -10,6 +10,7 @@ // no-prefer-dynamic // ignore-msvc no jemalloc on msvc +// ignore-bitrig no jemalloc on bitrig either #![feature(alloc_jemalloc)] From 9e79fc2d220c707471bcfc89e4fafeb5b8b4270b Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Thu, 3 Sep 2015 11:00:33 -0400 Subject: [PATCH 12/14] Add an issue number to this FIXME --- src/librustc/middle/reachable.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustc/middle/reachable.rs b/src/librustc/middle/reachable.rs index 4eef000169668..67da8f42effc8 100644 --- a/src/librustc/middle/reachable.rs +++ b/src/librustc/middle/reachable.rs @@ -351,7 +351,7 @@ impl<'a, 'tcx> ReachableContext<'a, 'tcx> { // Step 3: Mark all destructors as reachable. // - // FIXME(pcwalton): This is a conservative overapproximation, but fixing + // FIXME #10732: This is a conservative overapproximation, but fixing // this properly would result in the necessity of computing *type* // reachability, which might result in a compile time loss. fn mark_destructors_reachable(&mut self) { From 7732ad85df5a8fe0d6176aa08e6b86e6636561d1 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Thu, 3 Sep 2015 18:59:56 +0530 Subject: [PATCH 13/14] Move lints to HIR --- src/librustc/lint/context.rs | 91 ++-- src/librustc/lint/mod.rs | 63 +-- src/librustc_driver/driver.rs | 2 +- src/librustc_lint/builtin.rs | 490 +++++++++---------- src/test/auxiliary/lint_for_crate.rs | 6 +- src/test/auxiliary/lint_group_plugin_test.rs | 6 +- src/test/auxiliary/lint_plugin_test.rs | 7 +- 7 files changed, 328 insertions(+), 337 deletions(-) diff --git a/src/librustc/lint/context.rs b/src/librustc/lint/context.rs index f8a06bab3dd33..67be93cc2bdc6 100644 --- a/src/librustc/lint/context.rs +++ b/src/librustc/lint/context.rs @@ -37,12 +37,14 @@ use std::cell::RefCell; use std::cmp; use std::mem; use syntax::ast_util::IdVisitingOperation; -use syntax::attr::AttrMetaMethods; -use syntax::attr; +use rustc_front::attr::{self, AttrMetaMethods}; +use rustc_front::util; use syntax::codemap::Span; -use syntax::visit::{Visitor, FnKind}; use syntax::parse::token::InternedString; -use syntax::{ast, ast_util, visit}; +use syntax::ast; +use rustc_front::hir; +use rustc_front::visit::{self, Visitor, FnKind}; +use syntax::visit::Visitor as SyntaxVisitor; use syntax::diagnostic; /// Information about the registered lints. @@ -252,7 +254,7 @@ pub struct Context<'a, 'tcx: 'a> { pub tcx: &'a ty::ctxt<'tcx>, /// The crate being checked. - pub krate: &'a ast::Crate, + pub krate: &'a hir::Crate, /// Items exported from the crate being checked. pub exported_items: &'a ExportedItems, @@ -284,7 +286,7 @@ macro_rules! run_lints { ($cx:expr, $f:ident, $($args:expr),*) => ({ /// Parse the lint attributes into a vector, with `Err`s for malformed lint /// attributes. Writing this as an iterator is an enormous mess. // See also the hir version just below. -pub fn gather_attrs(attrs: &[ast::Attribute]) +pub fn gather_attrs(attrs: &[hir::Attribute]) -> Vec> { let mut out = vec!(); for attr in attrs { @@ -297,7 +299,7 @@ pub fn gather_attrs(attrs: &[ast::Attribute]) let meta = &attr.node.value; let metas = match meta.node { - ast::MetaList(_, ref metas) => metas, + hir::MetaList(_, ref metas) => metas, _ => { out.push(Err(meta.span)); continue; @@ -306,7 +308,7 @@ pub fn gather_attrs(attrs: &[ast::Attribute]) for meta in metas { out.push(match meta.node { - ast::MetaWord(ref lint_name) => Ok((lint_name.clone(), level, meta.span)), + hir::MetaWord(ref lint_name) => Ok((lint_name.clone(), level, meta.span)), _ => Err(meta.span), }); } @@ -398,7 +400,7 @@ pub fn raw_emit_lint(sess: &Session, lint: &'static Lint, impl<'a, 'tcx> Context<'a, 'tcx> { fn new(tcx: &'a ty::ctxt<'tcx>, - krate: &'a ast::Crate, + krate: &'a hir::Crate, exported_items: &'a ExportedItems) -> Context<'a, 'tcx> { // We want to own the lint store, so move it out of the session. let lint_store = mem::replace(&mut *tcx.sess.lint_store.borrow_mut(), @@ -452,7 +454,7 @@ impl<'a, 'tcx> Context<'a, 'tcx> { /// current lint context, call the provided function, then reset the /// lints in effect to their previous state. fn with_lint_attrs(&mut self, - attrs: &[ast::Attribute], + attrs: &[hir::Attribute], f: F) where F: FnOnce(&mut Context), { @@ -519,9 +521,9 @@ impl<'a, 'tcx> Context<'a, 'tcx> { } fn visit_ids(&mut self, f: F) where - F: FnOnce(&mut ast_util::IdVisitor) + F: FnOnce(&mut util::IdVisitor) { - let mut v = ast_util::IdVisitor { + let mut v = util::IdVisitor { operation: self, pass_through_items: false, visited_outermost: false, @@ -531,7 +533,7 @@ impl<'a, 'tcx> Context<'a, 'tcx> { } impl<'a, 'tcx, 'v> Visitor<'v> for Context<'a, 'tcx> { - fn visit_item(&mut self, it: &ast::Item) { + fn visit_item(&mut self, it: &hir::Item) { self.with_lint_attrs(&it.attrs, |cx| { run_lints!(cx, check_item, it); cx.visit_ids(|v| v.visit_item(it)); @@ -539,52 +541,52 @@ impl<'a, 'tcx, 'v> Visitor<'v> for Context<'a, 'tcx> { }) } - fn visit_foreign_item(&mut self, it: &ast::ForeignItem) { + fn visit_foreign_item(&mut self, it: &hir::ForeignItem) { self.with_lint_attrs(&it.attrs, |cx| { run_lints!(cx, check_foreign_item, it); visit::walk_foreign_item(cx, it); }) } - fn visit_pat(&mut self, p: &ast::Pat) { + fn visit_pat(&mut self, p: &hir::Pat) { run_lints!(self, check_pat, p); visit::walk_pat(self, p); } - fn visit_expr(&mut self, e: &ast::Expr) { + fn visit_expr(&mut self, e: &hir::Expr) { run_lints!(self, check_expr, e); visit::walk_expr(self, e); } - fn visit_stmt(&mut self, s: &ast::Stmt) { + fn visit_stmt(&mut self, s: &hir::Stmt) { run_lints!(self, check_stmt, s); visit::walk_stmt(self, s); } - fn visit_fn(&mut self, fk: FnKind<'v>, decl: &'v ast::FnDecl, - body: &'v ast::Block, span: Span, id: ast::NodeId) { + fn visit_fn(&mut self, fk: FnKind<'v>, decl: &'v hir::FnDecl, + body: &'v hir::Block, span: Span, id: ast::NodeId) { run_lints!(self, check_fn, fk, decl, body, span, id); visit::walk_fn(self, fk, decl, body, span); } fn visit_struct_def(&mut self, - s: &ast::StructDef, + s: &hir::StructDef, ident: ast::Ident, - g: &ast::Generics, + g: &hir::Generics, id: ast::NodeId) { run_lints!(self, check_struct_def, s, ident, g, id); visit::walk_struct_def(self, s); run_lints!(self, check_struct_def_post, s, ident, g, id); } - fn visit_struct_field(&mut self, s: &ast::StructField) { + fn visit_struct_field(&mut self, s: &hir::StructField) { self.with_lint_attrs(&s.node.attrs, |cx| { run_lints!(cx, check_struct_field, s); visit::walk_struct_field(cx, s); }) } - fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics) { + fn visit_variant(&mut self, v: &hir::Variant, g: &hir::Generics) { self.with_lint_attrs(&v.node.attrs, |cx| { run_lints!(cx, check_variant, v, g); visit::walk_variant(cx, v, g); @@ -592,7 +594,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for Context<'a, 'tcx> { }) } - fn visit_ty(&mut self, t: &ast::Ty) { + fn visit_ty(&mut self, t: &hir::Ty) { run_lints!(self, check_ty, t); visit::walk_ty(self, t); } @@ -601,41 +603,41 @@ impl<'a, 'tcx, 'v> Visitor<'v> for Context<'a, 'tcx> { run_lints!(self, check_ident, sp, id); } - fn visit_mod(&mut self, m: &ast::Mod, s: Span, n: ast::NodeId) { + fn visit_mod(&mut self, m: &hir::Mod, s: Span, n: ast::NodeId) { run_lints!(self, check_mod, m, s, n); visit::walk_mod(self, m); } - fn visit_local(&mut self, l: &ast::Local) { + fn visit_local(&mut self, l: &hir::Local) { run_lints!(self, check_local, l); visit::walk_local(self, l); } - fn visit_block(&mut self, b: &ast::Block) { + fn visit_block(&mut self, b: &hir::Block) { run_lints!(self, check_block, b); visit::walk_block(self, b); } - fn visit_arm(&mut self, a: &ast::Arm) { + fn visit_arm(&mut self, a: &hir::Arm) { run_lints!(self, check_arm, a); visit::walk_arm(self, a); } - fn visit_decl(&mut self, d: &ast::Decl) { + fn visit_decl(&mut self, d: &hir::Decl) { run_lints!(self, check_decl, d); visit::walk_decl(self, d); } - fn visit_expr_post(&mut self, e: &ast::Expr) { + fn visit_expr_post(&mut self, e: &hir::Expr) { run_lints!(self, check_expr_post, e); } - fn visit_generics(&mut self, g: &ast::Generics) { + fn visit_generics(&mut self, g: &hir::Generics) { run_lints!(self, check_generics, g); visit::walk_generics(self, g); } - fn visit_trait_item(&mut self, trait_item: &ast::TraitItem) { + fn visit_trait_item(&mut self, trait_item: &hir::TraitItem) { self.with_lint_attrs(&trait_item.attrs, |cx| { run_lints!(cx, check_trait_item, trait_item); cx.visit_ids(|v| v.visit_trait_item(trait_item)); @@ -643,7 +645,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for Context<'a, 'tcx> { }); } - fn visit_impl_item(&mut self, impl_item: &ast::ImplItem) { + fn visit_impl_item(&mut self, impl_item: &hir::ImplItem) { self.with_lint_attrs(&impl_item.attrs, |cx| { run_lints!(cx, check_impl_item, impl_item); cx.visit_ids(|v| v.visit_impl_item(impl_item)); @@ -651,34 +653,29 @@ impl<'a, 'tcx, 'v> Visitor<'v> for Context<'a, 'tcx> { }); } - fn visit_opt_lifetime_ref(&mut self, sp: Span, lt: &Option) { + fn visit_opt_lifetime_ref(&mut self, sp: Span, lt: &Option) { run_lints!(self, check_opt_lifetime_ref, sp, lt); } - fn visit_lifetime_ref(&mut self, lt: &ast::Lifetime) { + fn visit_lifetime_ref(&mut self, lt: &hir::Lifetime) { run_lints!(self, check_lifetime_ref, lt); } - fn visit_lifetime_def(&mut self, lt: &ast::LifetimeDef) { + fn visit_lifetime_def(&mut self, lt: &hir::LifetimeDef) { run_lints!(self, check_lifetime_def, lt); } - fn visit_explicit_self(&mut self, es: &ast::ExplicitSelf) { + fn visit_explicit_self(&mut self, es: &hir::ExplicitSelf) { run_lints!(self, check_explicit_self, es); visit::walk_explicit_self(self, es); } - fn visit_mac(&mut self, mac: &ast::Mac) { - run_lints!(self, check_mac, mac); - visit::walk_mac(self, mac); - } - - fn visit_path(&mut self, p: &ast::Path, id: ast::NodeId) { + fn visit_path(&mut self, p: &hir::Path, id: ast::NodeId) { run_lints!(self, check_path, p, id); visit::walk_path(self, p); } - fn visit_attribute(&mut self, attr: &ast::Attribute) { + fn visit_attribute(&mut self, attr: &hir::Attribute) { run_lints!(self, check_attribute, attr); } } @@ -709,9 +706,9 @@ impl LintPass for GatherNodeLevels { lint_array!() } - fn check_item(&mut self, cx: &Context, it: &ast::Item) { + fn check_item(&mut self, cx: &Context, it: &hir::Item) { match it.node { - ast::ItemEnum(..) => { + hir::ItemEnum(..) => { let lint_id = LintId::of(builtin::VARIANT_SIZE_DIFFERENCES); let lvlsrc = cx.lints.get_level_source(lint_id); match lvlsrc { @@ -731,7 +728,7 @@ impl LintPass for GatherNodeLevels { /// /// Consumes the `lint_store` field of the `Session`. pub fn check_crate(tcx: &ty::ctxt, - krate: &ast::Crate, + krate: &hir::Crate, exported_items: &ExportedItems) { let mut cx = Context::new(tcx, krate, exported_items); diff --git a/src/librustc/lint/mod.rs b/src/librustc/lint/mod.rs index 54b7aa81af3a6..2b3a6c6e287f9 100644 --- a/src/librustc/lint/mod.rs +++ b/src/librustc/lint/mod.rs @@ -34,8 +34,9 @@ pub use self::LintSource::*; use std::hash; use std::ascii::AsciiExt; use syntax::codemap::Span; -use syntax::visit::FnKind; +use rustc_front::visit::FnKind; use syntax::ast; +use rustc_front::hir; pub use lint::context::{Context, LintStore, raw_emit_lint, check_crate, gather_attrs, gather_attrs_from_hir, GatherNodeLevels}; @@ -125,46 +126,46 @@ pub trait LintPass { /// `Lint`, make it a private `static` item in its own module. fn get_lints(&self) -> LintArray; - fn check_crate(&mut self, _: &Context, _: &ast::Crate) { } + fn check_crate(&mut self, _: &Context, _: &hir::Crate) { } fn check_ident(&mut self, _: &Context, _: Span, _: ast::Ident) { } - fn check_mod(&mut self, _: &Context, _: &ast::Mod, _: Span, _: ast::NodeId) { } - fn check_foreign_item(&mut self, _: &Context, _: &ast::ForeignItem) { } - fn check_item(&mut self, _: &Context, _: &ast::Item) { } - fn check_local(&mut self, _: &Context, _: &ast::Local) { } - fn check_block(&mut self, _: &Context, _: &ast::Block) { } - fn check_stmt(&mut self, _: &Context, _: &ast::Stmt) { } - fn check_arm(&mut self, _: &Context, _: &ast::Arm) { } - fn check_pat(&mut self, _: &Context, _: &ast::Pat) { } - fn check_decl(&mut self, _: &Context, _: &ast::Decl) { } - fn check_expr(&mut self, _: &Context, _: &ast::Expr) { } - fn check_expr_post(&mut self, _: &Context, _: &ast::Expr) { } - fn check_ty(&mut self, _: &Context, _: &ast::Ty) { } - fn check_generics(&mut self, _: &Context, _: &ast::Generics) { } + fn check_mod(&mut self, _: &Context, _: &hir::Mod, _: Span, _: ast::NodeId) { } + fn check_foreign_item(&mut self, _: &Context, _: &hir::ForeignItem) { } + fn check_item(&mut self, _: &Context, _: &hir::Item) { } + fn check_local(&mut self, _: &Context, _: &hir::Local) { } + fn check_block(&mut self, _: &Context, _: &hir::Block) { } + fn check_stmt(&mut self, _: &Context, _: &hir::Stmt) { } + fn check_arm(&mut self, _: &Context, _: &hir::Arm) { } + fn check_pat(&mut self, _: &Context, _: &hir::Pat) { } + fn check_decl(&mut self, _: &Context, _: &hir::Decl) { } + fn check_expr(&mut self, _: &Context, _: &hir::Expr) { } + fn check_expr_post(&mut self, _: &Context, _: &hir::Expr) { } + fn check_ty(&mut self, _: &Context, _: &hir::Ty) { } + fn check_generics(&mut self, _: &Context, _: &hir::Generics) { } fn check_fn(&mut self, _: &Context, - _: FnKind, _: &ast::FnDecl, _: &ast::Block, _: Span, _: ast::NodeId) { } - fn check_trait_item(&mut self, _: &Context, _: &ast::TraitItem) { } - fn check_impl_item(&mut self, _: &Context, _: &ast::ImplItem) { } + _: FnKind, _: &hir::FnDecl, _: &hir::Block, _: Span, _: ast::NodeId) { } + fn check_trait_item(&mut self, _: &Context, _: &hir::TraitItem) { } + fn check_impl_item(&mut self, _: &Context, _: &hir::ImplItem) { } fn check_struct_def(&mut self, _: &Context, - _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { } + _: &hir::StructDef, _: ast::Ident, _: &hir::Generics, _: ast::NodeId) { } fn check_struct_def_post(&mut self, _: &Context, - _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { } - fn check_struct_field(&mut self, _: &Context, _: &ast::StructField) { } - fn check_variant(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) { } - fn check_variant_post(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) { } - fn check_opt_lifetime_ref(&mut self, _: &Context, _: Span, _: &Option) { } - fn check_lifetime_ref(&mut self, _: &Context, _: &ast::Lifetime) { } - fn check_lifetime_def(&mut self, _: &Context, _: &ast::LifetimeDef) { } - fn check_explicit_self(&mut self, _: &Context, _: &ast::ExplicitSelf) { } + _: &hir::StructDef, _: ast::Ident, _: &hir::Generics, _: ast::NodeId) { } + fn check_struct_field(&mut self, _: &Context, _: &hir::StructField) { } + fn check_variant(&mut self, _: &Context, _: &hir::Variant, _: &hir::Generics) { } + fn check_variant_post(&mut self, _: &Context, _: &hir::Variant, _: &hir::Generics) { } + fn check_opt_lifetime_ref(&mut self, _: &Context, _: Span, _: &Option) { } + fn check_lifetime_ref(&mut self, _: &Context, _: &hir::Lifetime) { } + fn check_lifetime_def(&mut self, _: &Context, _: &hir::LifetimeDef) { } + fn check_explicit_self(&mut self, _: &Context, _: &hir::ExplicitSelf) { } fn check_mac(&mut self, _: &Context, _: &ast::Mac) { } - fn check_path(&mut self, _: &Context, _: &ast::Path, _: ast::NodeId) { } - fn check_attribute(&mut self, _: &Context, _: &ast::Attribute) { } + fn check_path(&mut self, _: &Context, _: &hir::Path, _: ast::NodeId) { } + fn check_attribute(&mut self, _: &Context, _: &hir::Attribute) { } /// Called when entering a syntax node that can have lint attributes such /// as `#[allow(...)]`. Called with *all* the attributes of that node. - fn enter_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) { } + fn enter_lint_attrs(&mut self, _: &Context, _: &[hir::Attribute]) { } /// Counterpart to `enter_lint_attrs`. - fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) { } + fn exit_lint_attrs(&mut self, _: &Context, _: &[hir::Attribute]) { } } /// A lint pass boxed up as a trait object. diff --git a/src/librustc_driver/driver.rs b/src/librustc_driver/driver.rs index d12a189e6b164..dad20e0a24fb2 100644 --- a/src/librustc_driver/driver.rs +++ b/src/librustc_driver/driver.rs @@ -761,7 +761,7 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: Session, &tcx.sess, lib_features_used)); time(time_passes, "lint checking", || - lint::check_crate(tcx, ast_crate, &exported_items)); + lint::check_crate(tcx, &lower_crate(ast_crate), &exported_items)); // The above three passes generate errors w/o aborting tcx.sess.abort_if_errors(); diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs index 40f7fbbdef702..c8ffe07660611 100644 --- a/src/librustc_lint/builtin.rs +++ b/src/librustc_lint/builtin.rs @@ -45,21 +45,19 @@ use std::{cmp, slice}; use std::{i8, i16, i32, i64, u8, u16, u32, u64, f32, f64}; use syntax::{abi, ast}; -use syntax::ast_util::is_shift_binop; -use syntax::attr::{self, AttrMetaMethods}; +use syntax::attr as syntax_attr; use syntax::codemap::{self, Span}; use syntax::feature_gate::{KNOWN_ATTRIBUTES, AttributeType}; -use syntax::ast::{TyIs, TyUs, TyI8, TyU8, TyI16, TyU16, TyI32, TyU32, TyI64, TyU64}; +use rustc_front::hir::{TyIs, TyUs, TyI8, TyU8, TyI16, TyU16, TyI32, TyU32, TyI64, TyU64}; use syntax::ptr::P; -use syntax::visit::{self, FnKind, Visitor}; -use rustc_front::lowering::{lower_expr, lower_block, lower_item, lower_path, lower_pat, - lower_trait_ref}; use rustc_front::hir; -use rustc_front::attr as front_attr; -use rustc_front::attr::AttrMetaMethods as FrontAttrMetaMethods; -use rustc_front::visit::Visitor as HirVisitor; -use rustc_front::visit as hir_visit; + +use rustc_front::attr::{self, AttrMetaMethods}; +use rustc_front::visit::{self, FnKind, Visitor}; +use rustc_front::lowering::unlower_attribute; + +use rustc_front::util::is_shift_binop; // hardwired lints from librustc pub use lint::builtin::*; @@ -78,10 +76,10 @@ impl LintPass for WhileTrue { lint_array!(WHILE_TRUE) } - fn check_expr(&mut self, cx: &Context, e: &ast::Expr) { - if let ast::ExprWhile(ref cond, _, _) = e.node { - if let ast::ExprLit(ref lit) = cond.node { - if let ast::LitBool(true) = lit.node { + fn check_expr(&mut self, cx: &Context, e: &hir::Expr) { + if let hir::ExprWhile(ref cond, _, _) = e.node { + if let hir::ExprLit(ref lit) = cond.node { + if let hir::LitBool(true) = lit.node { cx.span_lint(WHILE_TRUE, e.span, "denote infinite loops with loop { ... }"); } @@ -127,16 +125,16 @@ impl LintPass for TypeLimits { lint_array!(UNUSED_COMPARISONS, OVERFLOWING_LITERALS, EXCEEDING_BITSHIFTS) } - fn check_expr(&mut self, cx: &Context, e: &ast::Expr) { + fn check_expr(&mut self, cx: &Context, e: &hir::Expr) { match e.node { - ast::ExprUnary(ast::UnNeg, ref expr) => { + hir::ExprUnary(hir::UnNeg, ref expr) => { match expr.node { - ast::ExprLit(ref lit) => { + hir::ExprLit(ref lit) => { match lit.node { - ast::LitInt(_, ast::UnsignedIntLit(_)) => { + hir::LitInt(_, hir::UnsignedIntLit(_)) => { check_unsigned_negation_feature(cx, e.span); }, - ast::LitInt(_, ast::UnsuffixedIntLit(_)) => { + hir::LitInt(_, hir::UnsuffixedIntLit(_)) => { if let ty::TyUint(_) = cx.tcx.node_id_to_type(e.id).sty { check_unsigned_negation_feature(cx, e.span); } @@ -159,10 +157,10 @@ impl LintPass for TypeLimits { self.negated_expr_id = expr.id; } }, - ast::ExprParen(ref expr) if self.negated_expr_id == e.id => { + hir::ExprParen(ref expr) if self.negated_expr_id == e.id => { self.negated_expr_id = expr.id; }, - ast::ExprBinary(binop, ref l, ref r) => { + hir::ExprBinary(binop, ref l, ref r) => { if is_comparison(binop) && !check_limits(cx.tcx, binop, &**l, &**r) { cx.span_lint(UNUSED_COMPARISONS, e.span, "comparison is useless due to type limits"); @@ -176,11 +174,10 @@ impl LintPass for TypeLimits { }; if let Some(bits) = opt_ty_bits { - let exceeding = if let ast::ExprLit(ref lit) = r.node { - if let ast::LitInt(shift, _) = lit.node { shift >= bits } + let exceeding = if let hir::ExprLit(ref lit) = r.node { + if let hir::LitInt(shift, _) = lit.node { shift >= bits } else { false } } else { - let r = lower_expr(r); match eval_const_expr_partial(cx.tcx, &r, ExprTypeChecked) { Ok(ConstVal::Int(shift)) => { shift as u64 >= bits }, Ok(ConstVal::Uint(shift)) => { shift >= bits }, @@ -194,12 +191,12 @@ impl LintPass for TypeLimits { }; } }, - ast::ExprLit(ref lit) => { + hir::ExprLit(ref lit) => { match cx.tcx.node_id_to_type(e.id).sty { ty::TyInt(t) => { match lit.node { - ast::LitInt(v, ast::SignedIntLit(_, ast::Plus)) | - ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => { + hir::LitInt(v, hir::SignedIntLit(_, hir::Plus)) | + hir::LitInt(v, hir::UnsuffixedIntLit(hir::Plus)) => { let int_type = if let hir::TyIs = t { cx.sess().target.int_type } else { @@ -228,8 +225,8 @@ impl LintPass for TypeLimits { }; let (min, max) = uint_ty_range(uint_type); let lit_val: u64 = match lit.node { - ast::LitByte(_v) => return, // _v is u8, within range by definition - ast::LitInt(v, _) => v, + hir::LitByte(_v) => return, // _v is u8, within range by definition + hir::LitInt(v, _) => v, _ => panic!() }; if lit_val < min || lit_val > max { @@ -240,8 +237,8 @@ impl LintPass for TypeLimits { ty::TyFloat(t) => { let (min, max) = float_ty_range(t); let lit_val: f64 = match lit.node { - ast::LitFloat(ref v, _) | - ast::LitFloatUnsuffixed(ref v) => { + hir::LitFloat(ref v, _) | + hir::LitFloatUnsuffixed(ref v) => { match v.parse() { Ok(f) => f, Err(_) => return @@ -260,24 +257,24 @@ impl LintPass for TypeLimits { _ => () }; - fn is_valid(binop: ast::BinOp, v: T, + fn is_valid(binop: hir::BinOp, v: T, min: T, max: T) -> bool { match binop.node { - ast::BiLt => v > min && v <= max, - ast::BiLe => v >= min && v < max, - ast::BiGt => v >= min && v < max, - ast::BiGe => v > min && v <= max, - ast::BiEq | ast::BiNe => v >= min && v <= max, + hir::BiLt => v > min && v <= max, + hir::BiLe => v >= min && v < max, + hir::BiGt => v >= min && v < max, + hir::BiGe => v > min && v <= max, + hir::BiEq | hir::BiNe => v >= min && v <= max, _ => panic!() } } - fn rev_binop(binop: ast::BinOp) -> ast::BinOp { + fn rev_binop(binop: hir::BinOp) -> hir::BinOp { codemap::respan(binop.span, match binop.node { - ast::BiLt => ast::BiGt, - ast::BiLe => ast::BiGe, - ast::BiGt => ast::BiLt, - ast::BiGe => ast::BiLe, + hir::BiLt => hir::BiGt, + hir::BiLe => hir::BiGe, + hir::BiGt => hir::BiLt, + hir::BiGe => hir::BiLe, _ => return binop }) } @@ -331,11 +328,11 @@ impl LintPass for TypeLimits { } } - fn check_limits(tcx: &ty::ctxt, binop: ast::BinOp, - l: &ast::Expr, r: &ast::Expr) -> bool { + fn check_limits(tcx: &ty::ctxt, binop: hir::BinOp, + l: &hir::Expr, r: &hir::Expr) -> bool { let (lit, expr, swap) = match (&l.node, &r.node) { - (&ast::ExprLit(_), _) => (l, r, true), - (_, &ast::ExprLit(_)) => (r, l, false), + (&hir::ExprLit(_), _) => (l, r, true), + (_, &hir::ExprLit(_)) => (r, l, false), _ => return true }; // Normalize the binop so that the literal is always on the RHS in @@ -349,11 +346,11 @@ impl LintPass for TypeLimits { ty::TyInt(int_ty) => { let (min, max) = int_ty_range(int_ty); let lit_val: i64 = match lit.node { - ast::ExprLit(ref li) => match li.node { - ast::LitInt(v, ast::SignedIntLit(_, ast::Plus)) | - ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => v as i64, - ast::LitInt(v, ast::SignedIntLit(_, ast::Minus)) | - ast::LitInt(v, ast::UnsuffixedIntLit(ast::Minus)) => -(v as i64), + hir::ExprLit(ref li) => match li.node { + hir::LitInt(v, hir::SignedIntLit(_, hir::Plus)) | + hir::LitInt(v, hir::UnsuffixedIntLit(hir::Plus)) => v as i64, + hir::LitInt(v, hir::SignedIntLit(_, hir::Minus)) | + hir::LitInt(v, hir::UnsuffixedIntLit(hir::Minus)) => -(v as i64), _ => return true }, _ => panic!() @@ -363,8 +360,8 @@ impl LintPass for TypeLimits { ty::TyUint(uint_ty) => { let (min, max): (u64, u64) = uint_ty_range(uint_ty); let lit_val: u64 = match lit.node { - ast::ExprLit(ref li) => match li.node { - ast::LitInt(v, _) => v, + hir::ExprLit(ref li) => match li.node { + hir::LitInt(v, _) => v, _ => return true }, _ => panic!() @@ -375,10 +372,10 @@ impl LintPass for TypeLimits { } } - fn is_comparison(binop: ast::BinOp) -> bool { + fn is_comparison(binop: hir::BinOp) -> bool { match binop.node { - ast::BiEq | ast::BiLt | ast::BiLe | - ast::BiNe | ast::BiGe | ast::BiGt => true, + hir::BiEq | hir::BiLt | hir::BiLe | + hir::BiNe | hir::BiGe | hir::BiGt => true, _ => false } } @@ -475,7 +472,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { match ty.sty { ty::TyStruct(def, substs) => { - if !cx.lookup_repr_hints(def.did).contains(&front_attr::ReprExtern) { + if !cx.lookup_repr_hints(def.did).contains(&attr::ReprExtern) { return FfiUnsafe( "found struct without foreign-function-safe \ representation annotation in foreign module, \ @@ -681,17 +678,17 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { } impl<'a, 'tcx, 'v> Visitor<'v> for ImproperCTypesVisitor<'a, 'tcx> { - fn visit_ty(&mut self, ty: &ast::Ty) { + fn visit_ty(&mut self, ty: &hir::Ty) { match ty.node { - ast::TyPath(..) | - ast::TyBareFn(..) => self.check_def(ty.span, ty.id), - ast::TyVec(..) => { + hir::TyPath(..) | + hir::TyBareFn(..) => self.check_def(ty.span, ty.id), + hir::TyVec(..) => { self.cx.span_lint(IMPROPER_CTYPES, ty.span, "found Rust slice type in foreign module, consider \ using a raw pointer instead"); } - ast::TyFixedLengthVec(ref ty, _) => self.visit_ty(ty), - ast::TyTup(..) => { + hir::TyFixedLengthVec(ref ty, _) => self.visit_ty(ty), + hir::TyTup(..) => { self.cx.span_lint(IMPROPER_CTYPES, ty.span, "found Rust tuple type in foreign module; \ consider using a struct instead`") @@ -709,17 +706,17 @@ impl LintPass for ImproperCTypes { lint_array!(IMPROPER_CTYPES) } - fn check_item(&mut self, cx: &Context, it: &ast::Item) { - fn check_ty(cx: &Context, ty: &ast::Ty) { + fn check_item(&mut self, cx: &Context, it: &hir::Item) { + fn check_ty(cx: &Context, ty: &hir::Ty) { let mut vis = ImproperCTypesVisitor { cx: cx }; vis.visit_ty(ty); } - fn check_foreign_fn(cx: &Context, decl: &ast::FnDecl) { + fn check_foreign_fn(cx: &Context, decl: &hir::FnDecl) { for input in &decl.inputs { check_ty(cx, &*input.ty); } - if let ast::Return(ref ret_ty) = decl.output { + if let hir::Return(ref ret_ty) = decl.output { let tty = ast_ty_to_normalized(cx.tcx, ret_ty.id); if !tty.is_nil() { check_ty(cx, &ret_ty); @@ -728,13 +725,13 @@ impl LintPass for ImproperCTypes { } match it.node { - ast::ItemForeignMod(ref nmod) + hir::ItemForeignMod(ref nmod) if nmod.abi != abi::RustIntrinsic && nmod.abi != abi::PlatformIntrinsic => { for ni in &nmod.items { match ni.node { - ast::ForeignItemFn(ref decl, _) => check_foreign_fn(cx, &**decl), - ast::ForeignItemStatic(ref t, _) => check_ty(cx, &**t) + hir::ForeignItemFn(ref decl, _) => check_foreign_fn(cx, &**decl), + hir::ForeignItemStatic(ref t, _) => check_ty(cx, &**t) } } } @@ -769,12 +766,12 @@ impl LintPass for BoxPointers { lint_array!(BOX_POINTERS) } - fn check_item(&mut self, cx: &Context, it: &ast::Item) { + fn check_item(&mut self, cx: &Context, it: &hir::Item) { match it.node { - ast::ItemFn(..) | - ast::ItemTy(..) | - ast::ItemEnum(..) | - ast::ItemStruct(..) => + hir::ItemFn(..) | + hir::ItemTy(..) | + hir::ItemEnum(..) | + hir::ItemStruct(..) => self.check_heap_type(cx, it.span, cx.tcx.node_id_to_type(it.id)), _ => () @@ -782,7 +779,7 @@ impl LintPass for BoxPointers { // If it's a struct, we also have to check the fields' types match it.node { - ast::ItemStruct(ref struct_def, _) => { + hir::ItemStruct(ref struct_def, _) => { for struct_field in &struct_def.fields { self.check_heap_type(cx, struct_field.span, cx.tcx.node_id_to_type(struct_field.node.id)); @@ -792,7 +789,7 @@ impl LintPass for BoxPointers { } } - fn check_expr(&mut self, cx: &Context, e: &ast::Expr) { + fn check_expr(&mut self, cx: &Context, e: &hir::Expr) { let ty = cx.tcx.node_id_to_type(e.id); self.check_heap_type(cx, e.span, ty); } @@ -808,13 +805,13 @@ struct RawPtrDeriveVisitor<'a, 'tcx: 'a> { cx: &'a Context<'a, 'tcx> } -impl<'a, 'tcx, 'v> HirVisitor<'v> for RawPtrDeriveVisitor<'a, 'tcx> { +impl<'a, 'tcx, 'v> Visitor<'v> for RawPtrDeriveVisitor<'a, 'tcx> { fn visit_ty(&mut self, ty: &hir::Ty) { const MSG: &'static str = "use of `#[derive]` with a raw pointer"; if let hir::TyPtr(..) = ty.node { self.cx.span_lint(RAW_POINTER_DERIVE, ty.span, MSG); } - hir_visit::walk_ty(self, ty); + visit::walk_ty(self, ty); } // explicit override to a no-op to reduce code bloat fn visit_expr(&mut self, _: &hir::Expr) {} @@ -838,11 +835,10 @@ impl LintPass for RawPointerDerive { lint_array!(RAW_POINTER_DERIVE) } - fn check_item(&mut self, cx: &Context, item: &ast::Item) { + fn check_item(&mut self, cx: &Context, item: &hir::Item) { if !attr::contains_name(&item.attrs, "automatically_derived") { return; } - let item = lower_item(item); let did = match item.node { hir::ItemImpl(_, _, _, ref t_ref_opt, _, _) => { // Deriving the Copy trait does not cause a warning @@ -874,7 +870,7 @@ impl LintPass for RawPointerDerive { match item.node { hir::ItemStruct(..) | hir::ItemEnum(..) => { let mut visitor = RawPtrDeriveVisitor { cx: cx }; - hir_visit::walk_item(&mut visitor, &item); + visit::walk_item(&mut visitor, &item); } _ => {} } @@ -895,7 +891,7 @@ impl LintPass for UnusedAttributes { lint_array!(UNUSED_ATTRIBUTES) } - fn check_attribute(&mut self, cx: &Context, attr: &ast::Attribute) { + fn check_attribute(&mut self, cx: &Context, attr: &hir::Attribute) { // Note that check_name() marks the attribute as used if it matches. for &(ref name, ty, _) in KNOWN_ATTRIBUTES { match ty { @@ -913,7 +909,7 @@ impl LintPass for UnusedAttributes { } } - if !attr::is_used(attr) { + if !syntax_attr::is_used(&unlower_attribute(attr)) { cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute"); // Is it a builtin attribute that must be used at the crate level? let known_crate = KNOWN_ATTRIBUTES.iter().find(|&&(name, ty, _)| { @@ -930,9 +926,9 @@ impl LintPass for UnusedAttributes { }).is_some(); if known_crate || plugin_crate { let msg = match attr.node.style { - ast::AttrOuter => "crate-level attribute should be an inner \ + hir::AttrOuter => "crate-level attribute should be an inner \ attribute: add an exclamation mark: #![foo]", - ast::AttrInner => "crate-level attribute should be in the \ + hir::AttrInner => "crate-level attribute should be in the \ root module", }; cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg); @@ -955,11 +951,11 @@ impl LintPass for PathStatements { lint_array!(PATH_STATEMENTS) } - fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) { + fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) { match s.node { - ast::StmtSemi(ref expr, _) => { + hir::StmtSemi(ref expr, _) => { match expr.node { - ast::ExprPath(..) => cx.span_lint(PATH_STATEMENTS, s.span, + hir::ExprPath(..) => cx.span_lint(PATH_STATEMENTS, s.span, "path statement with no effect"), _ => () } @@ -989,17 +985,16 @@ impl LintPass for UnusedResults { lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS) } - fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) { + fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) { let expr = match s.node { - ast::StmtSemi(ref expr, _) => &**expr, + hir::StmtSemi(ref expr, _) => &**expr, _ => return }; - if let ast::ExprRet(..) = expr.node { + if let hir::ExprRet(..) = expr.node { return; } - let expr = lower_expr(expr); let t = cx.tcx.expr_ty(&expr); let warned = match t.sty { ty::TyTuple(ref tys) if tys.is_empty() => return, @@ -1096,7 +1091,7 @@ impl LintPass for NonCamelCaseTypes { lint_array!(NON_CAMEL_CASE_TYPES) } - fn check_item(&mut self, cx: &Context, it: &ast::Item) { + fn check_item(&mut self, cx: &Context, it: &hir::Item) { let extern_repr_count = it.attrs.iter().filter(|attr| { attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr).iter() .any(|r| r == &attr::ReprExtern) @@ -1108,13 +1103,13 @@ impl LintPass for NonCamelCaseTypes { } match it.node { - ast::ItemTy(..) | ast::ItemStruct(..) => { + hir::ItemTy(..) | hir::ItemStruct(..) => { self.check_case(cx, "type", it.ident, it.span) } - ast::ItemTrait(..) => { + hir::ItemTrait(..) => { self.check_case(cx, "trait", it.ident, it.span) } - ast::ItemEnum(ref enum_definition, _) => { + hir::ItemEnum(ref enum_definition, _) => { if has_extern_repr { return; } @@ -1127,7 +1122,7 @@ impl LintPass for NonCamelCaseTypes { } } - fn check_generics(&mut self, cx: &Context, it: &ast::Generics) { + fn check_generics(&mut self, cx: &Context, it: &hir::Generics) { for gen in it.ty_params.iter() { self.check_case(cx, "type parameter", gen.ident, gen.span); } @@ -1242,7 +1237,7 @@ impl LintPass for NonSnakeCase { lint_array!(NON_SNAKE_CASE) } - fn check_crate(&mut self, cx: &Context, cr: &ast::Crate) { + fn check_crate(&mut self, cx: &Context, cr: &hir::Crate) { let attr_crate_name = cr.attrs.iter().find(|at| at.check_name("crate_name")) .and_then(|at| at.value_str().map(|s| (at, s))); if let Some(ref name) = cx.tcx.sess.opts.crate_name { @@ -1253,8 +1248,8 @@ impl LintPass for NonSnakeCase { } fn check_fn(&mut self, cx: &Context, - fk: FnKind, _: &ast::FnDecl, - _: &ast::Block, span: Span, id: ast::NodeId) { + fk: FnKind, _: &hir::FnDecl, + _: &hir::Block, span: Span, id: ast::NodeId) { match fk { FnKind::Method(ident, _, _) => match method_context(cx, id, span) { MethodContext::PlainImpl => { @@ -1272,26 +1267,26 @@ impl LintPass for NonSnakeCase { } } - fn check_item(&mut self, cx: &Context, it: &ast::Item) { - if let ast::ItemMod(_) = it.node { + fn check_item(&mut self, cx: &Context, it: &hir::Item) { + if let hir::ItemMod(_) = it.node { self.check_snake_case(cx, "module", &it.ident.name.as_str(), Some(it.span)); } } - fn check_trait_item(&mut self, cx: &Context, trait_item: &ast::TraitItem) { - if let ast::MethodTraitItem(_, None) = trait_item.node { + fn check_trait_item(&mut self, cx: &Context, trait_item: &hir::TraitItem) { + if let hir::MethodTraitItem(_, None) = trait_item.node { self.check_snake_case(cx, "trait method", &trait_item.ident.name.as_str(), Some(trait_item.span)); } } - fn check_lifetime_def(&mut self, cx: &Context, t: &ast::LifetimeDef) { + fn check_lifetime_def(&mut self, cx: &Context, t: &hir::LifetimeDef) { self.check_snake_case(cx, "lifetime", &t.lifetime.name.as_str(), Some(t.lifetime.span)); } - fn check_pat(&mut self, cx: &Context, p: &ast::Pat) { - if let &ast::PatIdent(_, ref path1, _) = &p.node { + fn check_pat(&mut self, cx: &Context, p: &hir::Pat) { + if let &hir::PatIdent(_, ref path1, _) = &p.node { let def = cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def()); if let Some(def::DefLocal(_)) = def { self.check_snake_case(cx, "variable", &path1.node.name.as_str(), Some(p.span)); @@ -1299,10 +1294,10 @@ impl LintPass for NonSnakeCase { } } - fn check_struct_def(&mut self, cx: &Context, s: &ast::StructDef, - _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { + fn check_struct_def(&mut self, cx: &Context, s: &hir::StructDef, + _: ast::Ident, _: &hir::Generics, _: ast::NodeId) { for sf in &s.fields { - if let ast::StructField_ { kind: ast::NamedField(ident, _), .. } = sf.node { + if let hir::StructField_ { kind: hir::NamedField(ident, _), .. } = sf.node { self.check_snake_case(cx, "structure field", &ident.name.as_str(), Some(sf.span)); } @@ -1343,22 +1338,22 @@ impl LintPass for NonUpperCaseGlobals { lint_array!(NON_UPPER_CASE_GLOBALS) } - fn check_item(&mut self, cx: &Context, it: &ast::Item) { + fn check_item(&mut self, cx: &Context, it: &hir::Item) { match it.node { // only check static constants - ast::ItemStatic(_, ast::MutImmutable, _) => { + hir::ItemStatic(_, hir::MutImmutable, _) => { NonUpperCaseGlobals::check_upper_case(cx, "static constant", it.ident, it.span); } - ast::ItemConst(..) => { + hir::ItemConst(..) => { NonUpperCaseGlobals::check_upper_case(cx, "constant", it.ident, it.span); } _ => {} } } - fn check_trait_item(&mut self, cx: &Context, ti: &ast::TraitItem) { + fn check_trait_item(&mut self, cx: &Context, ti: &hir::TraitItem) { match ti.node { - ast::ConstTraitItem(..) => { + hir::ConstTraitItem(..) => { NonUpperCaseGlobals::check_upper_case(cx, "associated constant", ti.ident, ti.span); } @@ -1366,9 +1361,9 @@ impl LintPass for NonUpperCaseGlobals { } } - fn check_impl_item(&mut self, cx: &Context, ii: &ast::ImplItem) { + fn check_impl_item(&mut self, cx: &Context, ii: &hir::ImplItem) { match ii.node { - ast::ConstImplItem(..) => { + hir::ConstImplItem(..) => { NonUpperCaseGlobals::check_upper_case(cx, "associated constant", ii.ident, ii.span); } @@ -1376,10 +1371,10 @@ impl LintPass for NonUpperCaseGlobals { } } - fn check_pat(&mut self, cx: &Context, p: &ast::Pat) { + fn check_pat(&mut self, cx: &Context, p: &hir::Pat) { // Lint for constants that look like binding identifiers (#7526) match (&p.node, cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def())) { - (&ast::PatIdent(_, ref path1, _), Some(def::DefConst(..))) => { + (&hir::PatIdent(_, ref path1, _), Some(def::DefConst(..))) => { NonUpperCaseGlobals::check_upper_case(cx, "constant in pattern", path1.node, p.span); } @@ -1398,9 +1393,9 @@ declare_lint! { pub struct UnusedParens; impl UnusedParens { - fn check_unused_parens_core(&self, cx: &Context, value: &ast::Expr, msg: &str, + fn check_unused_parens_core(&self, cx: &Context, value: &hir::Expr, msg: &str, struct_lit_needs_parens: bool) { - if let ast::ExprParen(ref inner) = value.node { + if let hir::ExprParen(ref inner) = value.node { let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner); if !necessary { cx.span_lint(UNUSED_PARENS, value.span, @@ -1413,27 +1408,27 @@ impl UnusedParens { /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X { /// y: 1 }) == foo` does not. - fn contains_exterior_struct_lit(value: &ast::Expr) -> bool { + fn contains_exterior_struct_lit(value: &hir::Expr) -> bool { match value.node { - ast::ExprStruct(..) => true, + hir::ExprStruct(..) => true, - ast::ExprAssign(ref lhs, ref rhs) | - ast::ExprAssignOp(_, ref lhs, ref rhs) | - ast::ExprBinary(_, ref lhs, ref rhs) => { + hir::ExprAssign(ref lhs, ref rhs) | + hir::ExprAssignOp(_, ref lhs, ref rhs) | + hir::ExprBinary(_, ref lhs, ref rhs) => { // X { y: 1 } + X { y: 2 } contains_exterior_struct_lit(&**lhs) || contains_exterior_struct_lit(&**rhs) } - ast::ExprUnary(_, ref x) | - ast::ExprCast(ref x, _) | - ast::ExprField(ref x, _) | - ast::ExprTupField(ref x, _) | - ast::ExprIndex(ref x, _) => { + hir::ExprUnary(_, ref x) | + hir::ExprCast(ref x, _) | + hir::ExprField(ref x, _) | + hir::ExprTupField(ref x, _) | + hir::ExprIndex(ref x, _) => { // &X { y: 1 }, X { y: 1 }.y contains_exterior_struct_lit(&**x) } - ast::ExprMethodCall(_, _, ref exprs) => { + hir::ExprMethodCall(_, _, ref exprs) => { // X { y: 1 }.bar(...) contains_exterior_struct_lit(&*exprs[0]) } @@ -1449,28 +1444,28 @@ impl LintPass for UnusedParens { lint_array!(UNUSED_PARENS) } - fn check_expr(&mut self, cx: &Context, e: &ast::Expr) { + fn check_expr(&mut self, cx: &Context, e: &hir::Expr) { let (value, msg, struct_lit_needs_parens) = match e.node { - ast::ExprIf(ref cond, _, _) => (cond, "`if` condition", true), - ast::ExprWhile(ref cond, _, _) => (cond, "`while` condition", true), - ast::ExprMatch(ref head, _, source) => match source { - ast::MatchSource::Normal => (head, "`match` head expression", true), - ast::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true), - ast::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true), - ast::MatchSource::ForLoopDesugar => (head, "`for` head expression", true), + hir::ExprIf(ref cond, _, _) => (cond, "`if` condition", true), + hir::ExprWhile(ref cond, _, _) => (cond, "`while` condition", true), + hir::ExprMatch(ref head, _, source) => match source { + hir::MatchSource::Normal => (head, "`match` head expression", true), + hir::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true), + hir::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true), + hir::MatchSource::ForLoopDesugar => (head, "`for` head expression", true), }, - ast::ExprRet(Some(ref value)) => (value, "`return` value", false), - ast::ExprAssign(_, ref value) => (value, "assigned value", false), - ast::ExprAssignOp(_, _, ref value) => (value, "assigned value", false), + hir::ExprRet(Some(ref value)) => (value, "`return` value", false), + hir::ExprAssign(_, ref value) => (value, "assigned value", false), + hir::ExprAssignOp(_, _, ref value) => (value, "assigned value", false), _ => return }; self.check_unused_parens_core(cx, &**value, msg, struct_lit_needs_parens); } - fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) { + fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) { let (value, msg) = match s.node { - ast::StmtDecl(ref decl, _) => match decl.node { - ast::DeclLocal(ref local) => match local.init { + hir::StmtDecl(ref decl, _) => match decl.node { + hir::DeclLocal(ref local) => match local.init { Some(ref value) => (value, "assigned value"), None => return }, @@ -1496,11 +1491,11 @@ impl LintPass for UnusedImportBraces { lint_array!(UNUSED_IMPORT_BRACES) } - fn check_item(&mut self, cx: &Context, item: &ast::Item) { - if let ast::ItemUse(ref view_path) = item.node { - if let ast::ViewPathList(_, ref items) = view_path.node { + fn check_item(&mut self, cx: &Context, item: &hir::Item) { + if let hir::ItemUse(ref view_path) = item.node { + if let hir::ViewPathList(_, ref items) = view_path.node { if items.len() == 1 { - if let ast::PathListIdent {ref name, ..} = items[0].node { + if let hir::PathListIdent {ref name, ..} = items[0].node { let m = format!("braces around {} is unnecessary", name); cx.span_lint(UNUSED_IMPORT_BRACES, item.span, @@ -1526,9 +1521,9 @@ impl LintPass for NonShorthandFieldPatterns { lint_array!(NON_SHORTHAND_FIELD_PATTERNS) } - fn check_pat(&mut self, cx: &Context, pat: &ast::Pat) { + fn check_pat(&mut self, cx: &Context, pat: &hir::Pat) { let def_map = cx.tcx.def_map.borrow(); - if let ast::PatStruct(_, ref v, _) = pat.node { + if let hir::PatStruct(_, ref v, _) = pat.node { let field_pats = v.iter().filter(|fieldpat| { if fieldpat.node.is_shorthand { return false; @@ -1537,7 +1532,7 @@ impl LintPass for NonShorthandFieldPatterns { def == Some(def::DefLocal(fieldpat.node.pat.id)) }); for fieldpat in field_pats { - if let ast::PatIdent(_, ident, None) = fieldpat.node.pat.node { + if let hir::PatIdent(_, ident, None) = fieldpat.node.pat.node { if ident.node.name == fieldpat.node.ident.name { // FIXME: should this comparison really be done on the name? // doing it on the ident will fail during compilation of libcore @@ -1565,10 +1560,10 @@ impl LintPass for UnusedUnsafe { lint_array!(UNUSED_UNSAFE) } - fn check_expr(&mut self, cx: &Context, e: &ast::Expr) { - if let ast::ExprBlock(ref blk) = e.node { + fn check_expr(&mut self, cx: &Context, e: &hir::Expr) { + if let hir::ExprBlock(ref blk) = e.node { // Don't warn about generated blocks, that'll just pollute the output. - if blk.rules == ast::UnsafeBlock(ast::UserProvided) && + if blk.rules == hir::UnsafeBlock(hir::UserProvided) && !cx.tcx.used_unsafe.borrow().contains(&blk.id) { cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block"); } @@ -1590,35 +1585,35 @@ impl LintPass for UnsafeCode { lint_array!(UNSAFE_CODE) } - fn check_expr(&mut self, cx: &Context, e: &ast::Expr) { - if let ast::ExprBlock(ref blk) = e.node { + fn check_expr(&mut self, cx: &Context, e: &hir::Expr) { + if let hir::ExprBlock(ref blk) = e.node { // Don't warn about generated blocks, that'll just pollute the output. - if blk.rules == ast::UnsafeBlock(ast::UserProvided) { + if blk.rules == hir::UnsafeBlock(hir::UserProvided) { cx.span_lint(UNSAFE_CODE, blk.span, "usage of an `unsafe` block"); } } } - fn check_item(&mut self, cx: &Context, it: &ast::Item) { + fn check_item(&mut self, cx: &Context, it: &hir::Item) { match it.node { - ast::ItemTrait(ast::Unsafety::Unsafe, _, _, _) => + hir::ItemTrait(hir::Unsafety::Unsafe, _, _, _) => cx.span_lint(UNSAFE_CODE, it.span, "declaration of an `unsafe` trait"), - ast::ItemImpl(ast::Unsafety::Unsafe, _, _, _, _, _) => + hir::ItemImpl(hir::Unsafety::Unsafe, _, _, _, _, _) => cx.span_lint(UNSAFE_CODE, it.span, "implementation of an `unsafe` trait"), _ => return, } } - fn check_fn(&mut self, cx: &Context, fk: FnKind, _: &ast::FnDecl, - _: &ast::Block, span: Span, _: ast::NodeId) { + fn check_fn(&mut self, cx: &Context, fk: FnKind, _: &hir::FnDecl, + _: &hir::Block, span: Span, _: ast::NodeId) { match fk { - FnKind::ItemFn(_, _, ast::Unsafety::Unsafe, _, _, _) => + FnKind::ItemFn(_, _, hir::Unsafety::Unsafe, _, _, _) => cx.span_lint(UNSAFE_CODE, span, "declaration of an `unsafe` function"), FnKind::Method(_, sig, _) => { - if sig.unsafety == ast::Unsafety::Unsafe { + if sig.unsafety == hir::Unsafety::Unsafe { cx.span_lint(UNSAFE_CODE, span, "implementation of an `unsafe` method") } }, @@ -1627,9 +1622,9 @@ impl LintPass for UnsafeCode { } } - fn check_trait_item(&mut self, cx: &Context, trait_item: &ast::TraitItem) { - if let ast::MethodTraitItem(ref sig, None) = trait_item.node { - if sig.unsafety == ast::Unsafety::Unsafe { + fn check_trait_item(&mut self, cx: &Context, trait_item: &hir::TraitItem) { + if let hir::MethodTraitItem(ref sig, None) = trait_item.node { + if sig.unsafety == hir::Unsafety::Unsafe { cx.span_lint(UNSAFE_CODE, trait_item.span, "declaration of an `unsafe` method") } @@ -1647,13 +1642,13 @@ declare_lint! { pub struct UnusedMut; impl UnusedMut { - fn check_unused_mut_pat(&self, cx: &Context, pats: &[P]) { + fn check_unused_mut_pat(&self, cx: &Context, pats: &[P]) { // collect all mutable pattern and group their NodeIDs by their Identifier to // avoid false warnings in match arms with multiple patterns let mut mutables = FnvHashMap(); for p in pats { - pat_util::pat_bindings(&cx.tcx.def_map, &lower_pat(p), |mode, id, _, path1| { + pat_util::pat_bindings(&cx.tcx.def_map, p, |mode, id, _, path1| { let ident = path1.node; if let hir::BindByValue(hir::MutMutable) = mode { if !ident.name.as_str().starts_with("_") { @@ -1681,25 +1676,25 @@ impl LintPass for UnusedMut { lint_array!(UNUSED_MUT) } - fn check_expr(&mut self, cx: &Context, e: &ast::Expr) { - if let ast::ExprMatch(_, ref arms, _) = e.node { + fn check_expr(&mut self, cx: &Context, e: &hir::Expr) { + if let hir::ExprMatch(_, ref arms, _) = e.node { for a in arms { self.check_unused_mut_pat(cx, &a.pats) } } } - fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) { - if let ast::StmtDecl(ref d, _) = s.node { - if let ast::DeclLocal(ref l) = d.node { + fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) { + if let hir::StmtDecl(ref d, _) = s.node { + if let hir::DeclLocal(ref l) = d.node { self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat)); } } } fn check_fn(&mut self, cx: &Context, - _: FnKind, decl: &ast::FnDecl, - _: &ast::Block, _: Span, _: ast::NodeId) { + _: FnKind, decl: &hir::FnDecl, + _: &hir::Block, _: Span, _: ast::NodeId) { for a in &decl.inputs { self.check_unused_mut_pat(cx, slice::ref_slice(&a.pat)); } @@ -1720,9 +1715,9 @@ impl LintPass for UnusedAllocation { lint_array!(UNUSED_ALLOCATION) } - fn check_expr(&mut self, cx: &Context, e: &ast::Expr) { + fn check_expr(&mut self, cx: &Context, e: &hir::Expr) { match e.node { - ast::ExprUnary(ast::UnUniq, _) => (), + hir::ExprUnary(hir::UnUniq, _) => (), _ => return } @@ -1782,7 +1777,7 @@ impl MissingDoc { fn check_missing_docs_attrs(&self, cx: &Context, id: Option, - attrs: &[ast::Attribute], + attrs: &[hir::Attribute], sp: Span, desc: &'static str) { // If we're building a test harness, then warning about @@ -1807,7 +1802,7 @@ impl MissingDoc { let has_doc = attrs.iter().any(|a| { match a.node.value.node { - ast::MetaNameValue(ref name, _) if *name == "doc" => true, + hir::MetaNameValue(ref name, _) if *name == "doc" => true, _ => false } }); @@ -1823,7 +1818,7 @@ impl LintPass for MissingDoc { lint_array!(MISSING_DOCS) } - fn enter_lint_attrs(&mut self, _: &Context, attrs: &[ast::Attribute]) { + fn enter_lint_attrs(&mut self, _: &Context, attrs: &[hir::Attribute]) { let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| { attr.check_name("doc") && match attr.meta_item_list() { None => false, @@ -1833,34 +1828,34 @@ impl LintPass for MissingDoc { self.doc_hidden_stack.push(doc_hidden); } - fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) { + fn exit_lint_attrs(&mut self, _: &Context, _: &[hir::Attribute]) { self.doc_hidden_stack.pop().expect("empty doc_hidden_stack"); } - fn check_struct_def(&mut self, _: &Context, _: &ast::StructDef, - _: ast::Ident, _: &ast::Generics, id: ast::NodeId) { + fn check_struct_def(&mut self, _: &Context, _: &hir::StructDef, + _: ast::Ident, _: &hir::Generics, id: ast::NodeId) { self.struct_def_stack.push(id); } - fn check_struct_def_post(&mut self, _: &Context, _: &ast::StructDef, - _: ast::Ident, _: &ast::Generics, id: ast::NodeId) { + fn check_struct_def_post(&mut self, _: &Context, _: &hir::StructDef, + _: ast::Ident, _: &hir::Generics, id: ast::NodeId) { let popped = self.struct_def_stack.pop().expect("empty struct_def_stack"); assert!(popped == id); } - fn check_crate(&mut self, cx: &Context, krate: &ast::Crate) { + fn check_crate(&mut self, cx: &Context, krate: &hir::Crate) { self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate"); } - fn check_item(&mut self, cx: &Context, it: &ast::Item) { + fn check_item(&mut self, cx: &Context, it: &hir::Item) { let desc = match it.node { - ast::ItemFn(..) => "a function", - ast::ItemMod(..) => "a module", - ast::ItemEnum(..) => "an enum", - ast::ItemStruct(..) => "a struct", - ast::ItemTrait(_, _, _, ref items) => { + hir::ItemFn(..) => "a function", + hir::ItemMod(..) => "a module", + hir::ItemEnum(..) => "an enum", + hir::ItemStruct(..) => "a struct", + hir::ItemTrait(_, _, _, ref items) => { // Issue #11592, traits are always considered exported, even when private. - if it.vis == ast::Visibility::Inherited { + if it.vis == hir::Visibility::Inherited { self.private_traits.insert(it.id); for itm in items { self.private_traits.insert(itm.id); @@ -1869,11 +1864,11 @@ impl LintPass for MissingDoc { } "a trait" }, - ast::ItemTy(..) => "a type alias", - ast::ItemImpl(_, _, _, Some(ref trait_ref), _, ref impl_items) => { + hir::ItemTy(..) => "a type alias", + hir::ItemImpl(_, _, _, Some(ref trait_ref), _, ref impl_items) => { // If the trait is private, add the impl items to private_traits so they don't get // reported for missing docs. - let real_trait = cx.tcx.trait_ref_to_def_id(&lower_trait_ref(trait_ref)); + let real_trait = cx.tcx.trait_ref_to_def_id(trait_ref); match cx.tcx.map.find(real_trait.node) { Some(hir_map::NodeItem(item)) => if item.vis == hir::Visibility::Inherited { for itm in impl_items { @@ -1884,21 +1879,21 @@ impl LintPass for MissingDoc { } return }, - ast::ItemConst(..) => "a constant", - ast::ItemStatic(..) => "a static", + hir::ItemConst(..) => "a constant", + hir::ItemStatic(..) => "a static", _ => return }; self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc); } - fn check_trait_item(&mut self, cx: &Context, trait_item: &ast::TraitItem) { + fn check_trait_item(&mut self, cx: &Context, trait_item: &hir::TraitItem) { if self.private_traits.contains(&trait_item.id) { return } let desc = match trait_item.node { - ast::ConstTraitItem(..) => "an associated constant", - ast::MethodTraitItem(..) => "a trait method", - ast::TypeTraitItem(..) => "an associated type", + hir::ConstTraitItem(..) => "an associated constant", + hir::MethodTraitItem(..) => "a trait method", + hir::TypeTraitItem(..) => "an associated type", }; self.check_missing_docs_attrs(cx, Some(trait_item.id), @@ -1906,26 +1901,25 @@ impl LintPass for MissingDoc { trait_item.span, desc); } - fn check_impl_item(&mut self, cx: &Context, impl_item: &ast::ImplItem) { + fn check_impl_item(&mut self, cx: &Context, impl_item: &hir::ImplItem) { // If the method is an impl for a trait, don't doc. if method_context(cx, impl_item.id, impl_item.span) == MethodContext::TraitImpl { return; } let desc = match impl_item.node { - ast::ConstImplItem(..) => "an associated constant", - ast::MethodImplItem(..) => "a method", - ast::TypeImplItem(_) => "an associated type", - ast::MacImplItem(_) => "an impl item macro", + hir::ConstImplItem(..) => "an associated constant", + hir::MethodImplItem(..) => "a method", + hir::TypeImplItem(_) => "an associated type", }; self.check_missing_docs_attrs(cx, Some(impl_item.id), &impl_item.attrs, impl_item.span, desc); } - fn check_struct_field(&mut self, cx: &Context, sf: &ast::StructField) { - if let ast::NamedField(_, vis) = sf.node.kind { - if vis == ast::Public || self.in_variant { + fn check_struct_field(&mut self, cx: &Context, sf: &hir::StructField) { + if let hir::NamedField(_, vis) = sf.node.kind { + if vis == hir::Public || self.in_variant { let cur_struct_def = *self.struct_def_stack.last() .expect("empty struct_def_stack"); self.check_missing_docs_attrs(cx, Some(cur_struct_def), @@ -1935,13 +1929,13 @@ impl LintPass for MissingDoc { } } - fn check_variant(&mut self, cx: &Context, v: &ast::Variant, _: &ast::Generics) { + fn check_variant(&mut self, cx: &Context, v: &hir::Variant, _: &hir::Generics) { self.check_missing_docs_attrs(cx, Some(v.node.id), &v.node.attrs, v.span, "a variant"); assert!(!self.in_variant); self.in_variant = true; } - fn check_variant_post(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) { + fn check_variant_post(&mut self, _: &Context, _: &hir::Variant, _: &hir::Generics) { assert!(self.in_variant); self.in_variant = false; } @@ -1961,12 +1955,12 @@ impl LintPass for MissingCopyImplementations { lint_array!(MISSING_COPY_IMPLEMENTATIONS) } - fn check_item(&mut self, cx: &Context, item: &ast::Item) { + fn check_item(&mut self, cx: &Context, item: &hir::Item) { if !cx.exported_items.contains(&item.id) { return; } let (def, ty) = match item.node { - ast::ItemStruct(_, ref ast_generics) => { + hir::ItemStruct(_, ref ast_generics) => { if ast_generics.is_parameterized() { return; } @@ -1974,7 +1968,7 @@ impl LintPass for MissingCopyImplementations { (def, cx.tcx.mk_struct(def, cx.tcx.mk_substs(Substs::empty()))) } - ast::ItemEnum(_, ref ast_generics) => { + hir::ItemEnum(_, ref ast_generics) => { if ast_generics.is_parameterized() { return; } @@ -2023,13 +2017,13 @@ impl LintPass for MissingDebugImplementations { lint_array!(MISSING_DEBUG_IMPLEMENTATIONS) } - fn check_item(&mut self, cx: &Context, item: &ast::Item) { + fn check_item(&mut self, cx: &Context, item: &hir::Item) { if !cx.exported_items.contains(&item.id) { return; } match item.node { - ast::ItemStruct(..) | ast::ItemEnum(..) => {}, + hir::ItemStruct(..) | hir::ItemEnum(..) => {}, _ => return, } @@ -2098,11 +2092,11 @@ impl Stability { } } -fn hir_to_ast_stability(stab: &front_attr::Stability) -> attr::Stability { +fn hir_to_ast_stability(stab: &attr::Stability) -> attr::Stability { attr::Stability { level: match stab.level { - front_attr::Unstable => attr::Unstable, - front_attr::Stable => attr::Stable, + attr::Unstable => attr::Unstable, + attr::Stable => attr::Stable, }, feature: stab.feature.clone(), since: stab.since.clone(), @@ -2117,29 +2111,29 @@ impl LintPass for Stability { lint_array!(DEPRECATED) } - fn check_item(&mut self, cx: &Context, item: &ast::Item) { - stability::check_item(cx.tcx, &lower_item(item), false, + fn check_item(&mut self, cx: &Context, item: &hir::Item) { + stability::check_item(cx.tcx, item, false, &mut |id, sp, stab| self.lint(cx, id, sp, &stab.map(|s| hir_to_ast_stability(s)).as_ref())); } - fn check_expr(&mut self, cx: &Context, e: &ast::Expr) { - stability::check_expr(cx.tcx, &lower_expr(e), + fn check_expr(&mut self, cx: &Context, e: &hir::Expr) { + stability::check_expr(cx.tcx, e, &mut |id, sp, stab| self.lint(cx, id, sp, &stab.map(|s| hir_to_ast_stability(s)).as_ref())); } - fn check_path(&mut self, cx: &Context, path: &ast::Path, id: ast::NodeId) { - stability::check_path(cx.tcx, &lower_path(path), id, + fn check_path(&mut self, cx: &Context, path: &hir::Path, id: ast::NodeId) { + stability::check_path(cx.tcx, path, id, &mut |id, sp, stab| self.lint(cx, id, sp, &stab.map(|s| hir_to_ast_stability(s)).as_ref())); } - fn check_pat(&mut self, cx: &Context, pat: &ast::Pat) { - stability::check_pat(cx.tcx, &lower_pat(pat), + fn check_pat(&mut self, cx: &Context, pat: &hir::Pat) { + stability::check_pat(cx.tcx, pat, &mut |id, sp, stab| self.lint(cx, id, sp, &stab.map(|s| hir_to_ast_stability(s)).as_ref())); @@ -2161,8 +2155,8 @@ impl LintPass for UnconditionalRecursion { lint_array![UNCONDITIONAL_RECURSION] } - fn check_fn(&mut self, cx: &Context, fn_kind: FnKind, _: &ast::FnDecl, - blk: &ast::Block, sp: Span, id: ast::NodeId) { + fn check_fn(&mut self, cx: &Context, fn_kind: FnKind, _: &hir::FnDecl, + blk: &hir::Block, sp: Span, id: ast::NodeId) { type F = for<'tcx> fn(&ty::ctxt<'tcx>, ast::NodeId, ast::NodeId, ast::Ident, ast::NodeId) -> bool; @@ -2201,7 +2195,7 @@ impl LintPass for UnconditionalRecursion { // to have behaviour like the above, rather than // e.g. accidentally recurring after an assert. - let cfg = cfg::CFG::new(cx.tcx, &lower_block(blk)); + let cfg = cfg::CFG::new(cx.tcx, blk); let mut work_queue = vec![cfg.entry]; let mut reached_exit_without_self_call = false; @@ -2408,14 +2402,14 @@ impl LintPass for PluginAsLibrary { lint_array![PLUGIN_AS_LIBRARY] } - fn check_item(&mut self, cx: &Context, it: &ast::Item) { + fn check_item(&mut self, cx: &Context, it: &hir::Item) { if cx.sess().plugin_registrar_fn.get().is_some() { // We're compiling a plugin; it's fine to link other plugins. return; } match it.node { - ast::ItemExternCrate(..) => (), + hir::ItemExternCrate(..) => (), _ => return, }; @@ -2464,9 +2458,9 @@ impl LintPass for InvalidNoMangleItems { NO_MANGLE_CONST_ITEMS) } - fn check_item(&mut self, cx: &Context, it: &ast::Item) { + fn check_item(&mut self, cx: &Context, it: &hir::Item) { match it.node { - ast::ItemFn(..) => { + hir::ItemFn(..) => { if attr::contains_name(&it.attrs, "no_mangle") && !cx.exported_items.contains(&it.id) { let msg = format!("function {} is marked #[no_mangle], but not exported", @@ -2474,7 +2468,7 @@ impl LintPass for InvalidNoMangleItems { cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg); } }, - ast::ItemStatic(..) => { + hir::ItemStatic(..) => { if attr::contains_name(&it.attrs, "no_mangle") && !cx.exported_items.contains(&it.id) { let msg = format!("static {} is marked #[no_mangle], but not exported", @@ -2482,7 +2476,7 @@ impl LintPass for InvalidNoMangleItems { cx.span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, &msg); } }, - ast::ItemConst(..) => { + hir::ItemConst(..) => { if attr::contains_name(&it.attrs, "no_mangle") { // Const items do not refer to a particular location in memory, and therefore // don't have anything to attach a symbol to @@ -2510,7 +2504,7 @@ impl LintPass for MutableTransmutes { lint_array!(MUTABLE_TRANSMUTES) } - fn check_expr(&mut self, cx: &Context, expr: &ast::Expr) { + fn check_expr(&mut self, cx: &Context, expr: &hir::Expr) { use syntax::abi::RustIntrinsic; let msg = "mutating transmuted &mut T from &T may cause undefined behavior,\ @@ -2525,13 +2519,13 @@ impl LintPass for MutableTransmutes { _ => () } - fn get_transmute_from_to<'a, 'tcx>(cx: &Context<'a, 'tcx>, expr: &ast::Expr) + fn get_transmute_from_to<'a, 'tcx>(cx: &Context<'a, 'tcx>, expr: &hir::Expr) -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> { match expr.node { - ast::ExprPath(..) => (), + hir::ExprPath(..) => (), _ => return None } - if let def::DefFn(did, _) = cx.tcx.resolve_expr(&lower_expr(expr)) { + if let def::DefFn(did, _) = cx.tcx.resolve_expr(expr) { if !def_id_is_transmute(cx, did) { return None; } @@ -2576,7 +2570,7 @@ impl LintPass for UnstableFeatures { fn get_lints(&self) -> LintArray { lint_array!(UNSTABLE_FEATURES) } - fn check_attribute(&mut self, ctx: &Context, attr: &ast::Attribute) { + fn check_attribute(&mut self, ctx: &Context, attr: &hir::Attribute) { if attr::contains_name(&[attr.node.value.clone()], "feature") { if let Some(items) = attr.node.value.meta_item_list() { for item in items { @@ -2602,7 +2596,7 @@ impl LintPass for DropWithReprExtern { fn get_lints(&self) -> LintArray { lint_array!(DROP_WITH_REPR_EXTERN) } - fn check_crate(&mut self, ctx: &Context, _: &ast::Crate) { + fn check_crate(&mut self, ctx: &Context, _: &hir::Crate) { for dtor_did in ctx.tcx.destructors.borrow().iter() { let (drop_impl_did, dtor_self_type) = if dtor_did.is_local() { @@ -2618,7 +2612,7 @@ impl LintPass for DropWithReprExtern { ty::TyStruct(self_type_def, _) => { let self_type_did = self_type_def.did; let hints = ctx.tcx.lookup_repr_hints(self_type_did); - if hints.iter().any(|attr| *attr == front_attr::ReprExtern) && + if hints.iter().any(|attr| *attr == attr::ReprExtern) && self_type_def.dtor_kind().has_drop_flag() { let drop_impl_span = ctx.tcx.map.def_id_span(drop_impl_did, codemap::DUMMY_SP); diff --git a/src/test/auxiliary/lint_for_crate.rs b/src/test/auxiliary/lint_for_crate.rs index 3b45b0ae70106..708fcafcb5311 100644 --- a/src/test/auxiliary/lint_for_crate.rs +++ b/src/test/auxiliary/lint_for_crate.rs @@ -13,12 +13,12 @@ #![feature(plugin_registrar, rustc_private)] #![feature(box_syntax)] -extern crate syntax; #[macro_use] extern crate rustc; +extern crate rustc_front; -use syntax::{ast, attr}; use rustc::lint::{Context, LintPass, LintPassObject, LintArray}; use rustc::plugin::Registry; +use rustc_front::{hir, attr}; declare_lint!(CRATE_NOT_OKAY, Warn, "crate not marked with #![crate_okay]"); @@ -29,7 +29,7 @@ impl LintPass for Pass { lint_array!(CRATE_NOT_OKAY) } - fn check_crate(&mut self, cx: &Context, krate: &ast::Crate) { + fn check_crate(&mut self, cx: &Context, krate: &hir::Crate) { if !attr::contains_name(&krate.attrs, "crate_okay") { cx.span_lint(CRATE_NOT_OKAY, krate.span, "crate is not marked with #![crate_okay]"); diff --git a/src/test/auxiliary/lint_group_plugin_test.rs b/src/test/auxiliary/lint_group_plugin_test.rs index 11de43a6b92af..adc194fa45486 100644 --- a/src/test/auxiliary/lint_group_plugin_test.rs +++ b/src/test/auxiliary/lint_group_plugin_test.rs @@ -13,13 +13,13 @@ #![feature(plugin_registrar)] #![feature(box_syntax, rustc_private)] -extern crate syntax; +extern crate rustc_front; // Load rustc as a plugin to get macros #[macro_use] extern crate rustc; -use syntax::ast; +use rustc_front::hir; use rustc::lint::{Context, LintPass, LintPassObject, LintArray}; use rustc::plugin::Registry; @@ -34,7 +34,7 @@ impl LintPass for Pass { lint_array!(TEST_LINT, PLEASE_LINT) } - fn check_item(&mut self, cx: &Context, it: &ast::Item) { + fn check_item(&mut self, cx: &Context, it: &hir::Item) { match &*it.ident.name.as_str() { "lintme" => cx.span_lint(TEST_LINT, it.span, "item is named 'lintme'"), "pleaselintme" => cx.span_lint(PLEASE_LINT, it.span, "item is named 'pleaselintme'"), diff --git a/src/test/auxiliary/lint_plugin_test.rs b/src/test/auxiliary/lint_plugin_test.rs index 967b168d00078..e6f91db230009 100644 --- a/src/test/auxiliary/lint_plugin_test.rs +++ b/src/test/auxiliary/lint_plugin_test.rs @@ -13,16 +13,15 @@ #![feature(plugin_registrar)] #![feature(box_syntax, rustc_private)] -extern crate syntax; +extern crate rustc_front; // Load rustc as a plugin to get macros #[macro_use] extern crate rustc; -use syntax::ast; use rustc::lint::{Context, LintPass, LintPassObject, LintArray}; use rustc::plugin::Registry; - +use rustc_front::hir; declare_lint!(TEST_LINT, Warn, "Warn about items named 'lintme'"); struct Pass; @@ -32,7 +31,7 @@ impl LintPass for Pass { lint_array!(TEST_LINT) } - fn check_item(&mut self, cx: &Context, it: &ast::Item) { + fn check_item(&mut self, cx: &Context, it: &hir::Item) { if it.ident.name == "lintme" { cx.span_lint(TEST_LINT, it.span, "item is named 'lintme'"); } From e6e175b828a86defa5637cdc5980ba94fbddf449 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Fri, 4 Sep 2015 00:03:38 +0530 Subject: [PATCH 14/14] Add ptr import (fixup #28187) --- src/libstd/sys/unix/stack_overflow.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libstd/sys/unix/stack_overflow.rs b/src/libstd/sys/unix/stack_overflow.rs index baff3c6bcbb83..de9e8cf97e68f 100644 --- a/src/libstd/sys/unix/stack_overflow.rs +++ b/src/libstd/sys/unix/stack_overflow.rs @@ -146,7 +146,7 @@ mod imp { target_os = "netbsd", target_os = "openbsd")))] mod imp { - use libc; + use ptr; pub unsafe fn init() { }