diff --git a/src/etc/platform-intrinsics/generator.py b/src/etc/platform-intrinsics/generator.py index e3c08bb35e075..4c8edbef6231c 100644 --- a/src/etc/platform-intrinsics/generator.py +++ b/src/etc/platform-intrinsics/generator.py @@ -801,7 +801,7 @@ def open(platform): // The default inlining settings trigger a pathological behaviour in // LLVM, which causes makes compilation very slow. See #28273. #[inline(never)] -pub fn find(name: &str) -> Option {{ +pub(crate) fn find(name: &str) -> Option {{ if !name.starts_with("{0}") {{ return None }} Some(match &name["{0}".len()..] {{'''.format(platform.platform_prefix()) diff --git a/src/librustc/lib.rs b/src/librustc/lib.rs index e0317e5e7f8a7..fb58cc3315606 100644 --- a/src/librustc/lib.rs +++ b/src/librustc/lib.rs @@ -30,6 +30,7 @@ #![feature(discriminant_value)] #![feature(i128_type)] #![feature(libc)] +#![feature(macro_vis_matcher)] #![feature(never_type)] #![feature(nonzero)] #![feature(quote)] diff --git a/src/librustc/lint/mod.rs b/src/librustc/lint/mod.rs index f9222ac9400af..cfdbc41ef5813 100644 --- a/src/librustc/lint/mod.rs +++ b/src/librustc/lint/mod.rs @@ -92,14 +92,9 @@ macro_rules! lint_initializer { /// Declare a static item of type `&'static Lint`. #[macro_export] macro_rules! declare_lint { - (pub $name:ident, $level:ident, $desc:expr) => ( - pub static $name: &'static ::rustc::lint::Lint - = &lint_initializer!($name, $level, $desc); - ); - ($name:ident, $level:ident, $desc:expr) => ( - static $name: &'static ::rustc::lint::Lint - = &lint_initializer!($name, $level, $desc); - ); + ($vis: vis $name: ident, $level: ident, $desc: expr) => { + $vis static $name: &$crate::lint::Lint = &lint_initializer!($name, $level, $desc); + } } /// Declare a static `LintArray` and return it as an expression. diff --git a/src/librustc_allocator/lib.rs b/src/librustc_allocator/lib.rs index d0ea40d1e361d..e17fce5a2ec0a 100644 --- a/src/librustc_allocator/lib.rs +++ b/src/librustc_allocator/lib.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![deny(warnings)] + #![feature(rustc_private)] extern crate rustc; @@ -22,61 +24,51 @@ pub static ALLOCATOR_METHODS: &[AllocatorMethod] = &[ name: "alloc", inputs: &[AllocatorTy::Layout], output: AllocatorTy::ResultPtr, - is_unsafe: true, }, AllocatorMethod { name: "oom", inputs: &[AllocatorTy::AllocErr], output: AllocatorTy::Bang, - is_unsafe: false, }, AllocatorMethod { name: "dealloc", inputs: &[AllocatorTy::Ptr, AllocatorTy::Layout], output: AllocatorTy::Unit, - is_unsafe: true, }, AllocatorMethod { name: "usable_size", inputs: &[AllocatorTy::LayoutRef], output: AllocatorTy::UsizePair, - is_unsafe: false, }, AllocatorMethod { name: "realloc", inputs: &[AllocatorTy::Ptr, AllocatorTy::Layout, AllocatorTy::Layout], output: AllocatorTy::ResultPtr, - is_unsafe: true, }, AllocatorMethod { name: "alloc_zeroed", inputs: &[AllocatorTy::Layout], output: AllocatorTy::ResultPtr, - is_unsafe: true, }, AllocatorMethod { name: "alloc_excess", inputs: &[AllocatorTy::Layout], output: AllocatorTy::ResultExcess, - is_unsafe: true, }, AllocatorMethod { name: "realloc_excess", inputs: &[AllocatorTy::Ptr, AllocatorTy::Layout, AllocatorTy::Layout], output: AllocatorTy::ResultExcess, - is_unsafe: true, }, AllocatorMethod { name: "grow_in_place", inputs: &[AllocatorTy::Ptr, AllocatorTy::Layout, AllocatorTy::Layout], output: AllocatorTy::ResultUnit, - is_unsafe: true, }, AllocatorMethod { name: "shrink_in_place", inputs: &[AllocatorTy::Ptr, AllocatorTy::Layout, AllocatorTy::Layout], output: AllocatorTy::ResultUnit, - is_unsafe: true, }, ]; @@ -84,7 +76,6 @@ pub struct AllocatorMethod { pub name: &'static str, pub inputs: &'static [AllocatorTy], pub output: AllocatorTy, - pub is_unsafe: bool, } pub enum AllocatorTy { diff --git a/src/librustc_back/dynamic_lib.rs b/src/librustc_back/dynamic_lib.rs index e6f305c22b2d4..e22b8d7ac32e9 100644 --- a/src/librustc_back/dynamic_lib.rs +++ b/src/librustc_back/dynamic_lib.rs @@ -12,9 +12,8 @@ //! //! A simple wrapper over the platform's dynamic library facilities -use std::env; -use std::ffi::{CString, OsString}; -use std::path::{Path, PathBuf}; +use std::ffi::CString; +use std::path::Path; pub struct DynamicLibrary { handle: *mut u8 @@ -43,24 +42,6 @@ impl DynamicLibrary { } } - /// Prepends a path to this process's search path for dynamic libraries - pub fn prepend_search_path(path: &Path) { - let mut search_path = DynamicLibrary::search_path(); - search_path.insert(0, path.to_path_buf()); - env::set_var(DynamicLibrary::envvar(), &DynamicLibrary::create_path(&search_path)); - } - - /// From a slice of paths, create a new vector which is suitable to be an - /// environment variable for this platforms dylib search path. - pub fn create_path(path: &[PathBuf]) -> OsString { - let mut newvar = OsString::new(); - for (i, path) in path.iter().enumerate() { - if i > 0 { newvar.push(DynamicLibrary::separator()); } - newvar.push(path); - } - return newvar; - } - /// Returns the environment variable for this process's dynamic library /// search path pub fn envvar() -> &'static str { @@ -75,19 +56,6 @@ impl DynamicLibrary { } } - fn separator() -> &'static str { - if cfg!(windows) { ";" } else { ":" } - } - - /// Returns the current search path for dynamic libraries being used by this - /// process - pub fn search_path() -> Vec { - match env::var_os(DynamicLibrary::envvar()) { - Some(var) => env::split_paths(&var).collect(), - None => Vec::new(), - } - } - /// Accesses the value at the symbol of the dynamic library. pub unsafe fn symbol(&self, symbol: &str) -> Result<*mut T, String> { // This function should have a lifetime constraint of 'a on @@ -166,7 +134,7 @@ mod dl { use std::ptr; use std::str; - pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> { + pub(crate) fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> { check_for_errors_in(|| { unsafe { match filename { @@ -188,7 +156,7 @@ mod dl { libc::dlopen(ptr::null(), LAZY) as *mut u8 } - pub fn check_for_errors_in(f: F) -> Result where + pub(crate) fn check_for_errors_in(f: F) -> Result where F: FnOnce() -> T, { use std::sync::{Mutex, Once, ONCE_INIT}; @@ -217,14 +185,14 @@ mod dl { } } - pub unsafe fn symbol(handle: *mut u8, - symbol: *const libc::c_char) - -> Result<*mut u8, String> { + pub(crate) unsafe fn symbol(handle: *mut u8, + symbol: *const libc::c_char) + -> Result<*mut u8, String> { check_for_errors_in(|| { libc::dlsym(handle as *mut libc::c_void, symbol) as *mut u8 }) } - pub unsafe fn close(handle: *mut u8) { + pub(crate) unsafe fn close(handle: *mut u8) { libc::dlclose(handle as *mut libc::c_void); () } } @@ -256,7 +224,7 @@ mod dl { fn FreeLibrary(handle: HMODULE) -> BOOL; } - pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> { + pub(crate) fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> { // disable "dll load failed" error dialog. let prev_error_mode = unsafe { // SEM_FAILCRITICALERRORS 0x01 @@ -299,14 +267,14 @@ mod dl { result } - pub unsafe fn symbol(handle: *mut u8, + pub(crate) unsafe fn symbol(handle: *mut u8, symbol: *const c_char) -> Result<*mut u8, String> { let ptr = GetProcAddress(handle as HMODULE, symbol) as *mut u8; ptr_result(ptr) } - pub unsafe fn close(handle: *mut u8) { + pub(crate) unsafe fn close(handle: *mut u8) { FreeLibrary(handle as HMODULE); } diff --git a/src/librustc_back/target/aarch64_apple_ios.rs b/src/librustc_back/target/aarch64_apple_ios.rs index 802a8c77db05b..fc7433b042c21 100644 --- a/src/librustc_back/target/aarch64_apple_ios.rs +++ b/src/librustc_back/target/aarch64_apple_ios.rs @@ -12,7 +12,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; use super::apple_ios_base::{opts, Arch}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let base = opts(Arch::Arm64)?; Ok(Target { llvm_target: "arm64-apple-ios".to_string(), diff --git a/src/librustc_back/target/aarch64_linux_android.rs b/src/librustc_back/target/aarch64_linux_android.rs index 7d8610b4a3684..68bb92ee5480e 100644 --- a/src/librustc_back/target/aarch64_linux_android.rs +++ b/src/librustc_back/target/aarch64_linux_android.rs @@ -14,7 +14,7 @@ use target::{Target, TargetOptions, TargetResult}; // See https://developer.android.com/ndk/guides/abis.html#arm64-v8a // for target ABI requirements. -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::android_base::opts(); base.max_atomic_width = Some(128); // As documented in http://developer.android.com/ndk/guides/cpu-features.html diff --git a/src/librustc_back/target/aarch64_unknown_freebsd.rs b/src/librustc_back/target/aarch64_unknown_freebsd.rs index c5427a13e4c7d..f7c6e56efcfeb 100644 --- a/src/librustc_back/target/aarch64_unknown_freebsd.rs +++ b/src/librustc_back/target/aarch64_unknown_freebsd.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::freebsd_base::opts(); base.max_atomic_width = Some(128); diff --git a/src/librustc_back/target/aarch64_unknown_fuchsia.rs b/src/librustc_back/target/aarch64_unknown_fuchsia.rs index 5d680504a02d0..80a5ab447b117 100644 --- a/src/librustc_back/target/aarch64_unknown_fuchsia.rs +++ b/src/librustc_back/target/aarch64_unknown_fuchsia.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::fuchsia_base::opts(); base.max_atomic_width = Some(128); diff --git a/src/librustc_back/target/aarch64_unknown_linux_gnu.rs b/src/librustc_back/target/aarch64_unknown_linux_gnu.rs index 7c2c45a2843a7..d3af02bd5cd63 100644 --- a/src/librustc_back/target/aarch64_unknown_linux_gnu.rs +++ b/src/librustc_back/target/aarch64_unknown_linux_gnu.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::linux_base::opts(); base.max_atomic_width = Some(128); diff --git a/src/librustc_back/target/android_base.rs b/src/librustc_back/target/android_base.rs index 49baa1b96cee3..c99c492152ea4 100644 --- a/src/librustc_back/target/android_base.rs +++ b/src/librustc_back/target/android_base.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::TargetOptions; -pub fn opts() -> TargetOptions { +pub(crate) fn opts() -> TargetOptions { let mut base = super::linux_base::opts(); // Many of the symbols defined in compiler-rt are also defined in libgcc. // Android's linker doesn't like that by default. diff --git a/src/librustc_back/target/apple_base.rs b/src/librustc_back/target/apple_base.rs index 159f93a74c683..30acc5aca7995 100644 --- a/src/librustc_back/target/apple_base.rs +++ b/src/librustc_back/target/apple_base.rs @@ -12,7 +12,7 @@ use std::env; use target::{LinkArgs, TargetOptions}; -pub fn opts() -> TargetOptions { +pub(crate) fn opts() -> TargetOptions { // ELF TLS is only available in macOS 10.7+. If you try to compile for 10.6 // either the linker will complain if it is used or the binary will end up // segfaulting at runtime when run on 10.6. Rust by default supports macOS diff --git a/src/librustc_back/target/apple_ios_base.rs b/src/librustc_back/target/apple_ios_base.rs index 2e7d30d969ec4..b99de53c8f9b6 100644 --- a/src/librustc_back/target/apple_ios_base.rs +++ b/src/librustc_back/target/apple_ios_base.rs @@ -17,7 +17,7 @@ use self::Arch::*; #[allow(non_camel_case_types)] #[derive(Copy, Clone)] -pub enum Arch { +pub(crate) enum Arch { Armv7, Armv7s, Arm64, @@ -26,7 +26,7 @@ pub enum Arch { } impl Arch { - pub fn to_string(&self) -> &'static str { + pub(crate) fn to_string(&self) -> &'static str { match self { &Armv7 => "armv7", &Armv7s => "armv7s", @@ -37,7 +37,7 @@ impl Arch { } } -pub fn get_sdk_root(sdk_name: &str) -> Result { +pub(crate) fn get_sdk_root(sdk_name: &str) -> Result { let res = Command::new("xcrun") .arg("--show-sdk-path") .arg("-sdk") @@ -91,7 +91,7 @@ fn target_cpu(arch: Arch) -> String { }.to_string() } -pub fn opts(arch: Arch) -> Result { +pub(crate) fn opts(arch: Arch) -> Result { let pre_link_args = build_pre_link_args(arch)?; Ok(TargetOptions { cpu: target_cpu(arch), diff --git a/src/librustc_back/target/arm_base.rs b/src/librustc_back/target/arm_base.rs index 416e5a0e13a88..2d77b1e684cab 100644 --- a/src/librustc_back/target/arm_base.rs +++ b/src/librustc_back/target/arm_base.rs @@ -11,6 +11,6 @@ use syntax::abi::Abi; // All the calling conventions trigger an assertion(Unsupported calling convention) in llvm on arm -pub fn abi_blacklist() -> Vec { +pub(crate) fn abi_blacklist() -> Vec { vec![Abi::Stdcall, Abi::Fastcall, Abi::Vectorcall, Abi::Thiscall, Abi::Win64, Abi::SysV64] } diff --git a/src/librustc_back/target/arm_linux_androideabi.rs b/src/librustc_back/target/arm_linux_androideabi.rs index 6bfe90af2ca16..54c3ed8a4dcc0 100644 --- a/src/librustc_back/target/arm_linux_androideabi.rs +++ b/src/librustc_back/target/arm_linux_androideabi.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::android_base::opts(); // https://developer.android.com/ndk/guides/abis.html#armeabi base.features = "+v5te".to_string(); diff --git a/src/librustc_back/target/arm_unknown_linux_gnueabi.rs b/src/librustc_back/target/arm_unknown_linux_gnueabi.rs index 165d34fe6c7ce..f07e42040ef1f 100644 --- a/src/librustc_back/target/arm_unknown_linux_gnueabi.rs +++ b/src/librustc_back/target/arm_unknown_linux_gnueabi.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::linux_base::opts(); base.max_atomic_width = Some(64); Ok(Target { diff --git a/src/librustc_back/target/arm_unknown_linux_gnueabihf.rs b/src/librustc_back/target/arm_unknown_linux_gnueabihf.rs index 731021d979bc4..bd39190a39635 100644 --- a/src/librustc_back/target/arm_unknown_linux_gnueabihf.rs +++ b/src/librustc_back/target/arm_unknown_linux_gnueabihf.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::linux_base::opts(); base.max_atomic_width = Some(64); Ok(Target { diff --git a/src/librustc_back/target/arm_unknown_linux_musleabi.rs b/src/librustc_back/target/arm_unknown_linux_musleabi.rs index f81bcd78b03aa..9b0cc4a3f57c5 100644 --- a/src/librustc_back/target/arm_unknown_linux_musleabi.rs +++ b/src/librustc_back/target/arm_unknown_linux_musleabi.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::linux_musl_base::opts(); // Most of these settings are copied from the arm_unknown_linux_gnueabi diff --git a/src/librustc_back/target/arm_unknown_linux_musleabihf.rs b/src/librustc_back/target/arm_unknown_linux_musleabihf.rs index 6c47678ede6ad..1550e72f43c42 100644 --- a/src/librustc_back/target/arm_unknown_linux_musleabihf.rs +++ b/src/librustc_back/target/arm_unknown_linux_musleabihf.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::linux_musl_base::opts(); // Most of these settings are copied from the arm_unknown_linux_gnueabihf diff --git a/src/librustc_back/target/armv5te_unknown_linux_gnueabi.rs b/src/librustc_back/target/armv5te_unknown_linux_gnueabi.rs index ef00c9a3278b9..2ea68632fba30 100644 --- a/src/librustc_back/target/armv5te_unknown_linux_gnueabi.rs +++ b/src/librustc_back/target/armv5te_unknown_linux_gnueabi.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let base = super::linux_base::opts(); Ok(Target { llvm_target: "armv5te-unknown-linux-gnueabi".to_string(), diff --git a/src/librustc_back/target/armv7_apple_ios.rs b/src/librustc_back/target/armv7_apple_ios.rs index 4d87458283294..6d6ee1da0d3a8 100644 --- a/src/librustc_back/target/armv7_apple_ios.rs +++ b/src/librustc_back/target/armv7_apple_ios.rs @@ -12,7 +12,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; use super::apple_ios_base::{opts, Arch}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let base = opts(Arch::Armv7)?; Ok(Target { llvm_target: "armv7-apple-ios".to_string(), diff --git a/src/librustc_back/target/armv7_linux_androideabi.rs b/src/librustc_back/target/armv7_linux_androideabi.rs index b49b1d1c2138a..46ccd7639e2e5 100644 --- a/src/librustc_back/target/armv7_linux_androideabi.rs +++ b/src/librustc_back/target/armv7_linux_androideabi.rs @@ -14,7 +14,7 @@ use target::{Target, TargetOptions, TargetResult}; // See https://developer.android.com/ndk/guides/abis.html#v7a // for target ABI requirements. -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::android_base::opts(); base.features = "+v7,+thumb2,+vfp3,+d16,-neon".to_string(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/target/armv7_unknown_linux_gnueabihf.rs b/src/librustc_back/target/armv7_unknown_linux_gnueabihf.rs index d3a6a68449c39..4545116d87511 100644 --- a/src/librustc_back/target/armv7_unknown_linux_gnueabihf.rs +++ b/src/librustc_back/target/armv7_unknown_linux_gnueabihf.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let base = super::linux_base::opts(); Ok(Target { llvm_target: "armv7-unknown-linux-gnueabihf".to_string(), diff --git a/src/librustc_back/target/armv7_unknown_linux_musleabihf.rs b/src/librustc_back/target/armv7_unknown_linux_musleabihf.rs index 5086cd44f7ac9..fb5e9e822bd5c 100644 --- a/src/librustc_back/target/armv7_unknown_linux_musleabihf.rs +++ b/src/librustc_back/target/armv7_unknown_linux_musleabihf.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::linux_musl_base::opts(); // Most of these settings are copied from the armv7_unknown_linux_gnueabihf diff --git a/src/librustc_back/target/armv7s_apple_ios.rs b/src/librustc_back/target/armv7s_apple_ios.rs index 96c89a7ed3bd5..c35c8c81a24af 100644 --- a/src/librustc_back/target/armv7s_apple_ios.rs +++ b/src/librustc_back/target/armv7s_apple_ios.rs @@ -12,7 +12,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; use super::apple_ios_base::{opts, Arch}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let base = opts(Arch::Armv7s)?; Ok(Target { llvm_target: "armv7s-apple-ios".to_string(), diff --git a/src/librustc_back/target/asmjs_unknown_emscripten.rs b/src/librustc_back/target/asmjs_unknown_emscripten.rs index b884d4e54101e..5993d8312f6da 100644 --- a/src/librustc_back/target/asmjs_unknown_emscripten.rs +++ b/src/librustc_back/target/asmjs_unknown_emscripten.rs @@ -12,7 +12,7 @@ use LinkerFlavor; use super::{LinkArgs, Target, TargetOptions}; use super::emscripten_base::{cmd}; -pub fn target() -> Result { +pub(crate) fn target() -> Result { let mut args = LinkArgs::new(); args.insert(LinkerFlavor::Em, vec!["-s".to_string(), diff --git a/src/librustc_back/target/bitrig_base.rs b/src/librustc_back/target/bitrig_base.rs index 45ceb2d5a6046..3ceb398bb4054 100644 --- a/src/librustc_back/target/bitrig_base.rs +++ b/src/librustc_back/target/bitrig_base.rs @@ -11,7 +11,7 @@ use target::{TargetOptions, RelroLevel}; use std::default::Default; -pub fn opts() -> TargetOptions { +pub(crate) fn opts() -> TargetOptions { TargetOptions { dynamic_linking: true, executables: true, diff --git a/src/librustc_back/target/dragonfly_base.rs b/src/librustc_back/target/dragonfly_base.rs index 21dca99aa5005..ba09ea0ce08b5 100644 --- a/src/librustc_back/target/dragonfly_base.rs +++ b/src/librustc_back/target/dragonfly_base.rs @@ -12,7 +12,7 @@ use LinkerFlavor; use target::{LinkArgs, TargetOptions, RelroLevel}; use std::default::Default; -pub fn opts() -> TargetOptions { +pub(crate) fn opts() -> TargetOptions { let mut args = LinkArgs::new(); args.insert(LinkerFlavor::Gcc, vec![ // GNU-style linkers will use this to omit linking to libraries diff --git a/src/librustc_back/target/emscripten_base.rs b/src/librustc_back/target/emscripten_base.rs index bacada3f5ab02..72f01dedd169f 100644 --- a/src/librustc_back/target/emscripten_base.rs +++ b/src/librustc_back/target/emscripten_base.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -pub fn cmd(name: &str) -> String { +pub(crate) fn cmd(name: &str) -> String { if cfg!(windows) { format!("{}.bat", name) } else { diff --git a/src/librustc_back/target/freebsd_base.rs b/src/librustc_back/target/freebsd_base.rs index 21dca99aa5005..ba09ea0ce08b5 100644 --- a/src/librustc_back/target/freebsd_base.rs +++ b/src/librustc_back/target/freebsd_base.rs @@ -12,7 +12,7 @@ use LinkerFlavor; use target::{LinkArgs, TargetOptions, RelroLevel}; use std::default::Default; -pub fn opts() -> TargetOptions { +pub(crate) fn opts() -> TargetOptions { let mut args = LinkArgs::new(); args.insert(LinkerFlavor::Gcc, vec![ // GNU-style linkers will use this to omit linking to libraries diff --git a/src/librustc_back/target/fuchsia_base.rs b/src/librustc_back/target/fuchsia_base.rs index 63ccd21c220f3..27e8db22ad953 100644 --- a/src/librustc_back/target/fuchsia_base.rs +++ b/src/librustc_back/target/fuchsia_base.rs @@ -12,7 +12,7 @@ use LinkerFlavor; use target::{LinkArgs, TargetOptions}; use std::default::Default; -pub fn opts() -> TargetOptions { +pub(crate) fn opts() -> TargetOptions { let mut args = LinkArgs::new(); args.insert(LinkerFlavor::Gcc, vec![ // We want to be able to strip as much executable code as possible diff --git a/src/librustc_back/target/haiku_base.rs b/src/librustc_back/target/haiku_base.rs index 21410dcd41264..86a65df95d60b 100644 --- a/src/librustc_back/target/haiku_base.rs +++ b/src/librustc_back/target/haiku_base.rs @@ -11,7 +11,7 @@ use target::{TargetOptions, RelroLevel}; use std::default::Default; -pub fn opts() -> TargetOptions { +pub(crate) fn opts() -> TargetOptions { TargetOptions { linker: "cc".to_string(), dynamic_linking: true, diff --git a/src/librustc_back/target/i386_apple_ios.rs b/src/librustc_back/target/i386_apple_ios.rs index 0e4e6900024b0..7601c7abc6eed 100644 --- a/src/librustc_back/target/i386_apple_ios.rs +++ b/src/librustc_back/target/i386_apple_ios.rs @@ -12,7 +12,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; use super::apple_ios_base::{opts, Arch}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let base = opts(Arch::I386)?; Ok(Target { llvm_target: "i386-apple-ios".to_string(), diff --git a/src/librustc_back/target/i586_pc_windows_msvc.rs b/src/librustc_back/target/i586_pc_windows_msvc.rs index 9b88cde598937..4af78579276bf 100644 --- a/src/librustc_back/target/i586_pc_windows_msvc.rs +++ b/src/librustc_back/target/i586_pc_windows_msvc.rs @@ -10,7 +10,7 @@ use target::TargetResult; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::i686_pc_windows_msvc::target()?; base.options.cpu = "pentium".to_string(); base.llvm_target = "i586-pc-windows-msvc".to_string(); diff --git a/src/librustc_back/target/i586_unknown_linux_gnu.rs b/src/librustc_back/target/i586_unknown_linux_gnu.rs index 40fb4a67acdf1..e8f991fe7e86e 100644 --- a/src/librustc_back/target/i586_unknown_linux_gnu.rs +++ b/src/librustc_back/target/i586_unknown_linux_gnu.rs @@ -10,7 +10,7 @@ use target::TargetResult; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::i686_unknown_linux_gnu::target()?; base.options.cpu = "pentium".to_string(); base.llvm_target = "i586-unknown-linux-gnu".to_string(); diff --git a/src/librustc_back/target/i686_apple_darwin.rs b/src/librustc_back/target/i686_apple_darwin.rs index 8c931f18411ca..ec09b974c1a05 100644 --- a/src/librustc_back/target/i686_apple_darwin.rs +++ b/src/librustc_back/target/i686_apple_darwin.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::apple_base::opts(); base.cpu = "yonah".to_string(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/target/i686_linux_android.rs b/src/librustc_back/target/i686_linux_android.rs index 565fbe37bf89e..8131c1b887d1f 100644 --- a/src/librustc_back/target/i686_linux_android.rs +++ b/src/librustc_back/target/i686_linux_android.rs @@ -14,7 +14,7 @@ use target::{Target, TargetResult}; // See https://developer.android.com/ndk/guides/abis.html#x86 // for target ABI requirements. -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::android_base::opts(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/target/i686_pc_windows_gnu.rs b/src/librustc_back/target/i686_pc_windows_gnu.rs index 4a736a93be7d7..65d5b17de42c4 100644 --- a/src/librustc_back/target/i686_pc_windows_gnu.rs +++ b/src/librustc_back/target/i686_pc_windows_gnu.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::windows_base::opts(); base.cpu = "pentium4".to_string(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/target/i686_pc_windows_msvc.rs b/src/librustc_back/target/i686_pc_windows_msvc.rs index 17fe306804f4a..6a3f3354fdd80 100644 --- a/src/librustc_back/target/i686_pc_windows_msvc.rs +++ b/src/librustc_back/target/i686_pc_windows_msvc.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::windows_msvc_base::opts(); base.cpu = "pentium4".to_string(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/target/i686_unknown_dragonfly.rs b/src/librustc_back/target/i686_unknown_dragonfly.rs index 9eda49a3709a5..c81241fe5fa30 100644 --- a/src/librustc_back/target/i686_unknown_dragonfly.rs +++ b/src/librustc_back/target/i686_unknown_dragonfly.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::dragonfly_base::opts(); base.cpu = "pentium4".to_string(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/target/i686_unknown_freebsd.rs b/src/librustc_back/target/i686_unknown_freebsd.rs index 041f3070c95bb..9187ffbe0abff 100644 --- a/src/librustc_back/target/i686_unknown_freebsd.rs +++ b/src/librustc_back/target/i686_unknown_freebsd.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::freebsd_base::opts(); base.cpu = "pentium4".to_string(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/target/i686_unknown_haiku.rs b/src/librustc_back/target/i686_unknown_haiku.rs index f21c2f8c77ab0..39c896a0dcf11 100644 --- a/src/librustc_back/target/i686_unknown_haiku.rs +++ b/src/librustc_back/target/i686_unknown_haiku.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::haiku_base::opts(); base.cpu = "pentium4".to_string(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/target/i686_unknown_linux_gnu.rs b/src/librustc_back/target/i686_unknown_linux_gnu.rs index f7b916816b313..d5a4114a34b6d 100644 --- a/src/librustc_back/target/i686_unknown_linux_gnu.rs +++ b/src/librustc_back/target/i686_unknown_linux_gnu.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::linux_base::opts(); base.cpu = "pentium4".to_string(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/target/i686_unknown_linux_musl.rs b/src/librustc_back/target/i686_unknown_linux_musl.rs index 00567d70fd6ce..683a5681537f7 100644 --- a/src/librustc_back/target/i686_unknown_linux_musl.rs +++ b/src/librustc_back/target/i686_unknown_linux_musl.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::linux_musl_base::opts(); base.cpu = "pentium4".to_string(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/target/i686_unknown_netbsd.rs b/src/librustc_back/target/i686_unknown_netbsd.rs index 7a9de529566b5..64e66e1c573be 100644 --- a/src/librustc_back/target/i686_unknown_netbsd.rs +++ b/src/librustc_back/target/i686_unknown_netbsd.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::netbsd_base::opts(); base.cpu = "pentium4".to_string(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/target/i686_unknown_openbsd.rs b/src/librustc_back/target/i686_unknown_openbsd.rs index b19bdbe049bcd..9744b64c894fa 100644 --- a/src/librustc_back/target/i686_unknown_openbsd.rs +++ b/src/librustc_back/target/i686_unknown_openbsd.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::openbsd_base::opts(); base.cpu = "pentium4".to_string(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/target/le32_unknown_nacl.rs b/src/librustc_back/target/le32_unknown_nacl.rs index f4265e0eb1462..131d094da3d81 100644 --- a/src/librustc_back/target/le32_unknown_nacl.rs +++ b/src/librustc_back/target/le32_unknown_nacl.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use super::{LinkArgs, Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut pre_link_args = LinkArgs::new(); pre_link_args.insert(LinkerFlavor::Gcc, vec!["--pnacl-exceptions=sjlj".to_string(), diff --git a/src/librustc_back/target/linux_base.rs b/src/librustc_back/target/linux_base.rs index 52f700ac7519f..1be558c0efacc 100644 --- a/src/librustc_back/target/linux_base.rs +++ b/src/librustc_back/target/linux_base.rs @@ -12,7 +12,7 @@ use LinkerFlavor; use target::{LinkArgs, TargetOptions, RelroLevel}; use std::default::Default; -pub fn opts() -> TargetOptions { +pub(crate) fn opts() -> TargetOptions { let mut args = LinkArgs::new(); args.insert(LinkerFlavor::Gcc, vec![ // We want to be able to strip as much executable code as possible diff --git a/src/librustc_back/target/linux_musl_base.rs b/src/librustc_back/target/linux_musl_base.rs index 236f2c1ef0aa3..0b55e067ab01f 100644 --- a/src/librustc_back/target/linux_musl_base.rs +++ b/src/librustc_back/target/linux_musl_base.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::TargetOptions; -pub fn opts() -> TargetOptions { +pub(crate) fn opts() -> TargetOptions { let mut base = super::linux_base::opts(); // Make sure that the linker/gcc really don't pull in anything, including diff --git a/src/librustc_back/target/mips64_unknown_linux_gnuabi64.rs b/src/librustc_back/target/mips64_unknown_linux_gnuabi64.rs index 2d77902046109..488c9af9879ea 100644 --- a/src/librustc_back/target/mips64_unknown_linux_gnuabi64.rs +++ b/src/librustc_back/target/mips64_unknown_linux_gnuabi64.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { Ok(Target { llvm_target: "mips64-unknown-linux-gnuabi64".to_string(), target_endian: "big".to_string(), diff --git a/src/librustc_back/target/mips64el_unknown_linux_gnuabi64.rs b/src/librustc_back/target/mips64el_unknown_linux_gnuabi64.rs index c26780b9e65ce..88780b61658dc 100644 --- a/src/librustc_back/target/mips64el_unknown_linux_gnuabi64.rs +++ b/src/librustc_back/target/mips64el_unknown_linux_gnuabi64.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { Ok(Target { llvm_target: "mips64el-unknown-linux-gnuabi64".to_string(), target_endian: "little".to_string(), diff --git a/src/librustc_back/target/mips_unknown_linux_gnu.rs b/src/librustc_back/target/mips_unknown_linux_gnu.rs index 24649851d76fd..feeeb1e1579aa 100644 --- a/src/librustc_back/target/mips_unknown_linux_gnu.rs +++ b/src/librustc_back/target/mips_unknown_linux_gnu.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { Ok(Target { llvm_target: "mips-unknown-linux-gnu".to_string(), target_endian: "big".to_string(), diff --git a/src/librustc_back/target/mips_unknown_linux_musl.rs b/src/librustc_back/target/mips_unknown_linux_musl.rs index 6303722945c9f..9c9a349a1c871 100644 --- a/src/librustc_back/target/mips_unknown_linux_musl.rs +++ b/src/librustc_back/target/mips_unknown_linux_musl.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { Ok(Target { llvm_target: "mips-unknown-linux-musl".to_string(), target_endian: "big".to_string(), diff --git a/src/librustc_back/target/mips_unknown_linux_uclibc.rs b/src/librustc_back/target/mips_unknown_linux_uclibc.rs index 1a7a56a977921..b17678fc122ff 100644 --- a/src/librustc_back/target/mips_unknown_linux_uclibc.rs +++ b/src/librustc_back/target/mips_unknown_linux_uclibc.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { Ok(Target { llvm_target: "mips-unknown-linux-uclibc".to_string(), target_endian: "big".to_string(), diff --git a/src/librustc_back/target/mipsel_unknown_linux_gnu.rs b/src/librustc_back/target/mipsel_unknown_linux_gnu.rs index cbf8339993c86..41fd9cc5f3fe3 100644 --- a/src/librustc_back/target/mipsel_unknown_linux_gnu.rs +++ b/src/librustc_back/target/mipsel_unknown_linux_gnu.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { Ok(Target { llvm_target: "mipsel-unknown-linux-gnu".to_string(), target_endian: "little".to_string(), diff --git a/src/librustc_back/target/mipsel_unknown_linux_musl.rs b/src/librustc_back/target/mipsel_unknown_linux_musl.rs index b367bce75a1d9..6fd84e8ea5a18 100644 --- a/src/librustc_back/target/mipsel_unknown_linux_musl.rs +++ b/src/librustc_back/target/mipsel_unknown_linux_musl.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { Ok(Target { llvm_target: "mipsel-unknown-linux-musl".to_string(), target_endian: "little".to_string(), diff --git a/src/librustc_back/target/mipsel_unknown_linux_uclibc.rs b/src/librustc_back/target/mipsel_unknown_linux_uclibc.rs index 686dfbe987d10..391dc1e70f7fd 100644 --- a/src/librustc_back/target/mipsel_unknown_linux_uclibc.rs +++ b/src/librustc_back/target/mipsel_unknown_linux_uclibc.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { Ok(Target { llvm_target: "mipsel-unknown-linux-uclibc".to_string(), target_endian: "little".to_string(), diff --git a/src/librustc_back/target/mod.rs b/src/librustc_back/target/mod.rs index 0dbfdb4d809e0..ad3382e72b3b0 100644 --- a/src/librustc_back/target/mod.rs +++ b/src/librustc_back/target/mod.rs @@ -72,8 +72,8 @@ mod thumb_base; mod fuchsia_base; mod redox_base; -pub type LinkArgs = BTreeMap>; -pub type TargetResult = Result; +pub(crate) type LinkArgs = BTreeMap>; +pub(crate) type TargetResult = Result; macro_rules! supported_targets { ( $(($triple:expr, $module:ident),)+ ) => ( @@ -355,7 +355,7 @@ pub struct TargetOptions { /// number sections that easily exceeds the given limit for larger /// codebases. Consequently we want a way to disallow weak linkage on some /// platforms. - pub allows_weak_linkage: bool, + pub(crate) allows_weak_linkage: bool, /// Whether the linker support rpaths or not. Defaults to false. pub has_rpath: bool, /// Whether to disable linking to the default libraries, typically corresponds @@ -401,17 +401,17 @@ pub struct TargetOptions { pub no_integrated_as: bool, /// Don't use this field; instead use the `.min_atomic_width()` method. - pub min_atomic_width: Option, + pub(crate) min_atomic_width: Option, /// Don't use this field; instead use the `.max_atomic_width()` method. - pub max_atomic_width: Option, + pub(crate) max_atomic_width: Option, /// Panic strategy: "unwind" or "abort" pub panic_strategy: PanicStrategy, /// A blacklist of ABIs unsupported by the current target. Note that generic /// ABIs are considered to be supported on all platforms and cannot be blacklisted. - pub abi_blacklist: Vec, + pub(crate) abi_blacklist: Vec, /// Whether or not the CRT is statically linked by default. pub crt_static_default: bool, @@ -513,7 +513,7 @@ impl Target { } /// Load a target descriptor from a JSON object. - pub fn from_json(obj: Json) -> TargetResult { + pub(crate) fn from_json(obj: Json) -> TargetResult { // While ugly, this code must remain this way to retain // compatibility with existing JSON fields and the internal // expected naming of the Target and TargetOptions structs. diff --git a/src/librustc_back/target/netbsd_base.rs b/src/librustc_back/target/netbsd_base.rs index 1cb311371938e..227dc9c7422f8 100644 --- a/src/librustc_back/target/netbsd_base.rs +++ b/src/librustc_back/target/netbsd_base.rs @@ -12,7 +12,7 @@ use LinkerFlavor; use target::{LinkArgs, TargetOptions, RelroLevel}; use std::default::Default; -pub fn opts() -> TargetOptions { +pub(crate) fn opts() -> TargetOptions { let mut args = LinkArgs::new(); args.insert(LinkerFlavor::Gcc, vec![ // GNU-style linkers will use this to omit linking to libraries diff --git a/src/librustc_back/target/openbsd_base.rs b/src/librustc_back/target/openbsd_base.rs index a5f8e7ae5f91b..3e99f6bce37fe 100644 --- a/src/librustc_back/target/openbsd_base.rs +++ b/src/librustc_back/target/openbsd_base.rs @@ -12,7 +12,7 @@ use LinkerFlavor; use target::{LinkArgs, TargetOptions, RelroLevel}; use std::default::Default; -pub fn opts() -> TargetOptions { +pub(crate) fn opts() -> TargetOptions { let mut args = LinkArgs::new(); args.insert(LinkerFlavor::Gcc, vec![ // GNU-style linkers will use this to omit linking to libraries diff --git a/src/librustc_back/target/powerpc64_unknown_linux_gnu.rs b/src/librustc_back/target/powerpc64_unknown_linux_gnu.rs index 7b038ac007396..dddfcfbb55c7a 100644 --- a/src/librustc_back/target/powerpc64_unknown_linux_gnu.rs +++ b/src/librustc_back/target/powerpc64_unknown_linux_gnu.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult, RelroLevel}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::linux_base::opts(); base.cpu = "ppc64".to_string(); base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string()); diff --git a/src/librustc_back/target/powerpc64le_unknown_linux_gnu.rs b/src/librustc_back/target/powerpc64le_unknown_linux_gnu.rs index 5b50b96837fbe..877867c69a38d 100644 --- a/src/librustc_back/target/powerpc64le_unknown_linux_gnu.rs +++ b/src/librustc_back/target/powerpc64le_unknown_linux_gnu.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::linux_base::opts(); base.cpu = "ppc64le".to_string(); base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string()); diff --git a/src/librustc_back/target/powerpc_unknown_linux_gnu.rs b/src/librustc_back/target/powerpc_unknown_linux_gnu.rs index 8d4ad5f0b447f..889258decb048 100644 --- a/src/librustc_back/target/powerpc_unknown_linux_gnu.rs +++ b/src/librustc_back/target/powerpc_unknown_linux_gnu.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::linux_base::opts(); base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m32".to_string()); base.max_atomic_width = Some(32); diff --git a/src/librustc_back/target/redox_base.rs b/src/librustc_back/target/redox_base.rs index 2eae0a1240823..f44c08183024d 100644 --- a/src/librustc_back/target/redox_base.rs +++ b/src/librustc_back/target/redox_base.rs @@ -12,7 +12,7 @@ use {LinkerFlavor, PanicStrategy}; use target::{LinkArgs, TargetOptions}; use std::default::Default; -pub fn opts() -> TargetOptions { +pub(crate) fn opts() -> TargetOptions { let mut args = LinkArgs::new(); args.insert(LinkerFlavor::Gcc, vec![ // We want to be able to strip as much executable code as possible diff --git a/src/librustc_back/target/s390x_unknown_linux_gnu.rs b/src/librustc_back/target/s390x_unknown_linux_gnu.rs index 78a6bb7933d95..48d0ea6afff68 100644 --- a/src/librustc_back/target/s390x_unknown_linux_gnu.rs +++ b/src/librustc_back/target/s390x_unknown_linux_gnu.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::linux_base::opts(); // z10 is the oldest CPU supported by LLVM base.cpu = "z10".to_string(); diff --git a/src/librustc_back/target/solaris_base.rs b/src/librustc_back/target/solaris_base.rs index 41323c9c26ba7..59d3bf8bb4917 100644 --- a/src/librustc_back/target/solaris_base.rs +++ b/src/librustc_back/target/solaris_base.rs @@ -11,7 +11,7 @@ use target::TargetOptions; use std::default::Default; -pub fn opts() -> TargetOptions { +pub(crate) fn opts() -> TargetOptions { TargetOptions { dynamic_linking: true, executables: true, diff --git a/src/librustc_back/target/sparc64_unknown_linux_gnu.rs b/src/librustc_back/target/sparc64_unknown_linux_gnu.rs index 7f710ad402053..d2d9dd65b0238 100644 --- a/src/librustc_back/target/sparc64_unknown_linux_gnu.rs +++ b/src/librustc_back/target/sparc64_unknown_linux_gnu.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::linux_base::opts(); base.cpu = "v9".to_string(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/target/sparc64_unknown_netbsd.rs b/src/librustc_back/target/sparc64_unknown_netbsd.rs index bc65a17ce6ea9..dccd88e1f1e9f 100644 --- a/src/librustc_back/target/sparc64_unknown_netbsd.rs +++ b/src/librustc_back/target/sparc64_unknown_netbsd.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::netbsd_base::opts(); base.cpu = "v9".to_string(); base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string()); diff --git a/src/librustc_back/target/sparcv9_sun_solaris.rs b/src/librustc_back/target/sparcv9_sun_solaris.rs index 122b38968a9c0..d8fa4660346c8 100644 --- a/src/librustc_back/target/sparcv9_sun_solaris.rs +++ b/src/librustc_back/target/sparcv9_sun_solaris.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::solaris_base::opts(); base.pre_link_args.insert(LinkerFlavor::Gcc, vec!["-m64".to_string()]); // llvm calls this "v9" diff --git a/src/librustc_back/target/thumb_base.rs b/src/librustc_back/target/thumb_base.rs index 6bb496649a858..2f551ed7aacc6 100644 --- a/src/librustc_back/target/thumb_base.rs +++ b/src/librustc_back/target/thumb_base.rs @@ -39,7 +39,7 @@ use PanicStrategy; use std::default::Default; use target::TargetOptions; -pub fn opts() -> TargetOptions { +pub(crate) fn opts() -> TargetOptions { // See rust-lang/rfcs#1645 for a discussion about these defaults TargetOptions { executables: true, diff --git a/src/librustc_back/target/thumbv6m_none_eabi.rs b/src/librustc_back/target/thumbv6m_none_eabi.rs index 08bf145e5518a..18c788a73a8bc 100644 --- a/src/librustc_back/target/thumbv6m_none_eabi.rs +++ b/src/librustc_back/target/thumbv6m_none_eabi.rs @@ -13,7 +13,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { Ok(Target { llvm_target: "thumbv6m-none-eabi".to_string(), target_endian: "little".to_string(), diff --git a/src/librustc_back/target/thumbv7em_none_eabi.rs b/src/librustc_back/target/thumbv7em_none_eabi.rs index 13f9cc5f65fb9..e7e3d14287329 100644 --- a/src/librustc_back/target/thumbv7em_none_eabi.rs +++ b/src/librustc_back/target/thumbv7em_none_eabi.rs @@ -22,7 +22,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { Ok(Target { llvm_target: "thumbv7em-none-eabi".to_string(), target_endian: "little".to_string(), diff --git a/src/librustc_back/target/thumbv7em_none_eabihf.rs b/src/librustc_back/target/thumbv7em_none_eabihf.rs index 929b6db6fb2c6..24c4746b80a3c 100644 --- a/src/librustc_back/target/thumbv7em_none_eabihf.rs +++ b/src/librustc_back/target/thumbv7em_none_eabihf.rs @@ -21,7 +21,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { Ok(Target { llvm_target: "thumbv7em-none-eabihf".to_string(), target_endian: "little".to_string(), diff --git a/src/librustc_back/target/thumbv7m_none_eabi.rs b/src/librustc_back/target/thumbv7m_none_eabi.rs index 8d46e7cb90760..bf28bcdaa8343 100644 --- a/src/librustc_back/target/thumbv7m_none_eabi.rs +++ b/src/librustc_back/target/thumbv7m_none_eabi.rs @@ -13,7 +13,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { Ok(Target { llvm_target: "thumbv7m-none-eabi".to_string(), target_endian: "little".to_string(), diff --git a/src/librustc_back/target/wasm32_experimental_emscripten.rs b/src/librustc_back/target/wasm32_experimental_emscripten.rs index 053fab5425019..46e236abb6271 100644 --- a/src/librustc_back/target/wasm32_experimental_emscripten.rs +++ b/src/librustc_back/target/wasm32_experimental_emscripten.rs @@ -12,7 +12,7 @@ use LinkerFlavor; use super::{LinkArgs, Target, TargetOptions}; use super::emscripten_base::{cmd}; -pub fn target() -> Result { +pub(crate) fn target() -> Result { let mut post_link_args = LinkArgs::new(); post_link_args.insert(LinkerFlavor::Em, vec!["-s".to_string(), diff --git a/src/librustc_back/target/wasm32_unknown_emscripten.rs b/src/librustc_back/target/wasm32_unknown_emscripten.rs index f5fb63038e917..462fa98c6387e 100644 --- a/src/librustc_back/target/wasm32_unknown_emscripten.rs +++ b/src/librustc_back/target/wasm32_unknown_emscripten.rs @@ -12,7 +12,7 @@ use LinkerFlavor; use super::{LinkArgs, Target, TargetOptions}; use super::emscripten_base::{cmd}; -pub fn target() -> Result { +pub(crate) fn target() -> Result { let mut post_link_args = LinkArgs::new(); post_link_args.insert(LinkerFlavor::Em, vec!["-s".to_string(), diff --git a/src/librustc_back/target/windows_base.rs b/src/librustc_back/target/windows_base.rs index 9bde24a28dd9b..277d5125ac2db 100644 --- a/src/librustc_back/target/windows_base.rs +++ b/src/librustc_back/target/windows_base.rs @@ -12,7 +12,7 @@ use LinkerFlavor; use target::{LinkArgs, TargetOptions}; use std::default::Default; -pub fn opts() -> TargetOptions { +pub(crate) fn opts() -> TargetOptions { let mut pre_link_args = LinkArgs::new(); pre_link_args.insert(LinkerFlavor::Gcc, vec![ // And here, we see obscure linker flags #45. On windows, it has been diff --git a/src/librustc_back/target/windows_msvc_base.rs b/src/librustc_back/target/windows_msvc_base.rs index c07321e418e64..3a241b1783c98 100644 --- a/src/librustc_back/target/windows_msvc_base.rs +++ b/src/librustc_back/target/windows_msvc_base.rs @@ -12,7 +12,7 @@ use LinkerFlavor; use target::{LinkArgs, TargetOptions}; use std::default::Default; -pub fn opts() -> TargetOptions { +pub(crate) fn opts() -> TargetOptions { let mut args = LinkArgs::new(); args.insert(LinkerFlavor::Msvc, vec!["/NOLOGO".to_string(), diff --git a/src/librustc_back/target/x86_64_apple_darwin.rs b/src/librustc_back/target/x86_64_apple_darwin.rs index 8ac76679008e9..92c06b3ea2325 100644 --- a/src/librustc_back/target/x86_64_apple_darwin.rs +++ b/src/librustc_back/target/x86_64_apple_darwin.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::apple_base::opts(); base.cpu = "core2".to_string(); base.max_atomic_width = Some(128); // core2 support cmpxchg16b diff --git a/src/librustc_back/target/x86_64_apple_ios.rs b/src/librustc_back/target/x86_64_apple_ios.rs index 61a71da2162a0..2597eed1d908e 100644 --- a/src/librustc_back/target/x86_64_apple_ios.rs +++ b/src/librustc_back/target/x86_64_apple_ios.rs @@ -12,7 +12,7 @@ use LinkerFlavor; use target::{Target, TargetOptions, TargetResult}; use super::apple_ios_base::{opts, Arch}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let base = opts(Arch::X86_64)?; Ok(Target { llvm_target: "x86_64-apple-ios".to_string(), diff --git a/src/librustc_back/target/x86_64_linux_android.rs b/src/librustc_back/target/x86_64_linux_android.rs index 158e2b13604ec..f33cf873ef2b0 100644 --- a/src/librustc_back/target/x86_64_linux_android.rs +++ b/src/librustc_back/target/x86_64_linux_android.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::android_base::opts(); base.cpu = "x86-64".to_string(); // https://developer.android.com/ndk/guides/abis.html#86-64 diff --git a/src/librustc_back/target/x86_64_pc_windows_gnu.rs b/src/librustc_back/target/x86_64_pc_windows_gnu.rs index 10e88d88ee372..36d1c183e0ce7 100644 --- a/src/librustc_back/target/x86_64_pc_windows_gnu.rs +++ b/src/librustc_back/target/x86_64_pc_windows_gnu.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::windows_base::opts(); base.cpu = "x86-64".to_string(); base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string()); diff --git a/src/librustc_back/target/x86_64_pc_windows_msvc.rs b/src/librustc_back/target/x86_64_pc_windows_msvc.rs index 7eb673d8b363c..ca649bb00f98f 100644 --- a/src/librustc_back/target/x86_64_pc_windows_msvc.rs +++ b/src/librustc_back/target/x86_64_pc_windows_msvc.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::windows_msvc_base::opts(); base.cpu = "x86-64".to_string(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/target/x86_64_rumprun_netbsd.rs b/src/librustc_back/target/x86_64_rumprun_netbsd.rs index c7e5edde63db3..04e4f6b5387e6 100644 --- a/src/librustc_back/target/x86_64_rumprun_netbsd.rs +++ b/src/librustc_back/target/x86_64_rumprun_netbsd.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::netbsd_base::opts(); base.cpu = "x86-64".to_string(); base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string()); diff --git a/src/librustc_back/target/x86_64_sun_solaris.rs b/src/librustc_back/target/x86_64_sun_solaris.rs index 38a38ed68bc92..66d6ca967bccf 100644 --- a/src/librustc_back/target/x86_64_sun_solaris.rs +++ b/src/librustc_back/target/x86_64_sun_solaris.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::solaris_base::opts(); base.pre_link_args.insert(LinkerFlavor::Gcc, vec!["-m64".to_string()]); base.cpu = "x86-64".to_string(); diff --git a/src/librustc_back/target/x86_64_unknown_bitrig.rs b/src/librustc_back/target/x86_64_unknown_bitrig.rs index cf4b019dce2df..871eaa9e85575 100644 --- a/src/librustc_back/target/x86_64_unknown_bitrig.rs +++ b/src/librustc_back/target/x86_64_unknown_bitrig.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::bitrig_base::opts(); base.cpu = "x86-64".to_string(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/target/x86_64_unknown_dragonfly.rs b/src/librustc_back/target/x86_64_unknown_dragonfly.rs index 8885d89c6f7a8..8cbd4f74e67af 100644 --- a/src/librustc_back/target/x86_64_unknown_dragonfly.rs +++ b/src/librustc_back/target/x86_64_unknown_dragonfly.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::dragonfly_base::opts(); base.cpu = "x86-64".to_string(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/target/x86_64_unknown_freebsd.rs b/src/librustc_back/target/x86_64_unknown_freebsd.rs index 95870f2be5fc0..aa2ccd8734a40 100644 --- a/src/librustc_back/target/x86_64_unknown_freebsd.rs +++ b/src/librustc_back/target/x86_64_unknown_freebsd.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::freebsd_base::opts(); base.cpu = "x86-64".to_string(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/target/x86_64_unknown_fuchsia.rs b/src/librustc_back/target/x86_64_unknown_fuchsia.rs index 1aebb885595e2..376a9d3cd62a9 100644 --- a/src/librustc_back/target/x86_64_unknown_fuchsia.rs +++ b/src/librustc_back/target/x86_64_unknown_fuchsia.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::fuchsia_base::opts(); base.cpu = "x86-64".to_string(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/target/x86_64_unknown_haiku.rs b/src/librustc_back/target/x86_64_unknown_haiku.rs index 3794a516ec4a8..8b797de0a3abe 100644 --- a/src/librustc_back/target/x86_64_unknown_haiku.rs +++ b/src/librustc_back/target/x86_64_unknown_haiku.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::haiku_base::opts(); base.cpu = "x86-64".to_string(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/target/x86_64_unknown_linux_gnu.rs b/src/librustc_back/target/x86_64_unknown_linux_gnu.rs index d2135f8a0bdce..867330dad30e6 100644 --- a/src/librustc_back/target/x86_64_unknown_linux_gnu.rs +++ b/src/librustc_back/target/x86_64_unknown_linux_gnu.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::linux_base::opts(); base.cpu = "x86-64".to_string(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/target/x86_64_unknown_linux_musl.rs b/src/librustc_back/target/x86_64_unknown_linux_musl.rs index 7d542b4d3cb5a..00669f8f3d38c 100644 --- a/src/librustc_back/target/x86_64_unknown_linux_musl.rs +++ b/src/librustc_back/target/x86_64_unknown_linux_musl.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::linux_musl_base::opts(); base.cpu = "x86-64".to_string(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/target/x86_64_unknown_netbsd.rs b/src/librustc_back/target/x86_64_unknown_netbsd.rs index 5d49fcbd64ab1..47a48057c9527 100644 --- a/src/librustc_back/target/x86_64_unknown_netbsd.rs +++ b/src/librustc_back/target/x86_64_unknown_netbsd.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::netbsd_base::opts(); base.cpu = "x86-64".to_string(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/target/x86_64_unknown_openbsd.rs b/src/librustc_back/target/x86_64_unknown_openbsd.rs index aa289fb577501..d12e70381bffa 100644 --- a/src/librustc_back/target/x86_64_unknown_openbsd.rs +++ b/src/librustc_back/target/x86_64_unknown_openbsd.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::openbsd_base::opts(); base.cpu = "x86-64".to_string(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/target/x86_64_unknown_redox.rs b/src/librustc_back/target/x86_64_unknown_redox.rs index 8d2a7afeeacf0..e6a701bed7de4 100644 --- a/src/librustc_back/target/x86_64_unknown_redox.rs +++ b/src/librustc_back/target/x86_64_unknown_redox.rs @@ -11,7 +11,7 @@ use LinkerFlavor; use target::{Target, TargetResult}; -pub fn target() -> TargetResult { +pub(crate) fn target() -> TargetResult { let mut base = super::redox_base::opts(); base.cpu = "x86-64".to_string(); base.max_atomic_width = Some(64); diff --git a/src/librustc_back/tempdir.rs b/src/librustc_back/tempdir.rs index e3e89223f2d65..8ffaddd7c29f2 100644 --- a/src/librustc_back/tempdir.rs +++ b/src/librustc_back/tempdir.rs @@ -95,15 +95,6 @@ impl TempDir { self.path.as_ref().unwrap() } - /// Close and remove the temporary directory - /// - /// Although `TempDir` removes the directory on drop, in the destructor - /// any errors are ignored. To detect errors cleaning up the temporary - /// directory, call `close` instead. - pub fn close(mut self) -> io::Result<()> { - self.cleanup_dir() - } - fn cleanup_dir(&mut self) -> io::Result<()> { match self.path { Some(ref p) => fs::remove_dir_all(p), diff --git a/src/librustc_borrowck/borrowck/check_loans.rs b/src/librustc_borrowck/borrowck/check_loans.rs index b84cd212c4ab4..6e3b5a2debe3d 100644 --- a/src/librustc_borrowck/borrowck/check_loans.rs +++ b/src/librustc_borrowck/borrowck/check_loans.rs @@ -184,11 +184,11 @@ impl<'a, 'tcx> euv::Delegate<'tcx> for CheckLoanCtxt<'a, 'tcx> { fn decl_without_init(&mut self, _id: ast::NodeId, _span: Span) { } } -pub fn check_loans<'a, 'b, 'c, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, - dfcx_loans: &LoanDataFlow<'b, 'tcx>, - move_data: &move_data::FlowedMoveData<'c, 'tcx>, - all_loans: &[Loan<'tcx>], - body: &hir::Body) { +pub(crate) fn check_loans<'a, 'b, 'c, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, + dfcx_loans: &LoanDataFlow<'b, 'tcx>, + move_data: &move_data::FlowedMoveData<'c, 'tcx>, + all_loans: &[Loan<'tcx>], + body: &hir::Body) { debug!("check_loans(body id={})", body.value.id); let def_id = bccx.tcx.hir.body_owner_def_id(body.id()); @@ -217,9 +217,9 @@ fn compatible_borrow_kinds(borrow_kind1: ty::BorrowKind, } impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> { - pub fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { self.bccx.tcx } + pub(crate) fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { self.bccx.tcx } - pub fn each_issued_loan(&self, node: ast::NodeId, mut op: F) -> bool where + pub(crate) fn each_issued_loan(&self, node: ast::NodeId, mut op: F) -> bool where F: FnMut(&Loan<'tcx>) -> bool, { //! Iterates over each loan that has been issued @@ -234,7 +234,7 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> { }) } - pub fn each_in_scope_loan(&self, scope: region::CodeExtent, mut op: F) -> bool where + pub(crate) fn each_in_scope_loan(&self, scope: region::CodeExtent, mut op: F) -> bool where F: FnMut(&Loan<'tcx>) -> bool, { //! Like `each_issued_loan()`, but only considers loans that are @@ -324,7 +324,7 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> { return true; } - pub fn loans_generated_by(&self, node: ast::NodeId) -> Vec { + pub(crate) fn loans_generated_by(&self, node: ast::NodeId) -> Vec { //! Returns a vector of the loans that are generated as //! we enter `node`. @@ -336,7 +336,7 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> { return result; } - pub fn check_for_conflicting_loans(&self, node: ast::NodeId) { + pub(crate) fn check_for_conflicting_loans(&self, node: ast::NodeId) { //! Checks to see whether any of the loans that are issued //! on entrance to `node` conflict with loans that have already been //! issued when we enter `node` (for example, we do not @@ -368,10 +368,10 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> { } } - pub fn report_error_if_loans_conflict(&self, - old_loan: &Loan<'tcx>, - new_loan: &Loan<'tcx>) - -> bool { + pub(crate) fn report_error_if_loans_conflict(&self, + old_loan: &Loan<'tcx>, + new_loan: &Loan<'tcx>) + -> bool { //! Checks whether `old_loan` and `new_loan` can safely be issued //! simultaneously. @@ -389,12 +389,12 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> { new_loan, old_loan, old_loan, new_loan) } - pub fn report_error_if_loan_conflicts_with_restriction(&self, - loan1: &Loan<'tcx>, - loan2: &Loan<'tcx>, - old_loan: &Loan<'tcx>, - new_loan: &Loan<'tcx>) - -> bool { + pub(crate) fn report_error_if_loan_conflicts_with_restriction(&self, + loan1: &Loan<'tcx>, + loan2: &Loan<'tcx>, + old_loan: &Loan<'tcx>, + new_loan: &Loan<'tcx>) + -> bool { //! Checks whether the restrictions introduced by `loan1` would //! prohibit `loan2`. Returns false if an error is reported. @@ -698,11 +698,11 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> { } } - pub fn analyze_restrictions_on_use(&self, - expr_id: ast::NodeId, - use_path: &LoanPath<'tcx>, - borrow_kind: ty::BorrowKind) - -> UseError<'tcx> { + pub(crate) fn analyze_restrictions_on_use(&self, + expr_id: ast::NodeId, + use_path: &LoanPath<'tcx>, + borrow_kind: ty::BorrowKind) + -> UseError<'tcx> { debug!("analyze_restrictions_on_use(expr_id={}, use_path={:?})", self.tcx().hir.node_to_string(expr_id), use_path); @@ -856,10 +856,10 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> { } } - pub fn report_illegal_mutation(&self, - span: Span, - loan_path: &LoanPath<'tcx>, - loan: &Loan) { + pub(crate) fn report_illegal_mutation(&self, + span: Span, + loan_path: &LoanPath<'tcx>, + loan: &Loan) { struct_span_err!(self.bccx, span, E0506, "cannot assign to `{}` because it is borrowed", self.bccx.loan_path_to_string(loan_path)) diff --git a/src/librustc_borrowck/borrowck/gather_loans/gather_moves.rs b/src/librustc_borrowck/borrowck/gather_loans/gather_moves.rs index 3d98c2a23dc67..0f2bc65710719 100644 --- a/src/librustc_borrowck/borrowck/gather_loans/gather_moves.rs +++ b/src/librustc_borrowck/borrowck/gather_loans/gather_moves.rs @@ -35,7 +35,7 @@ struct GatherMoveInfo<'tcx> { /// Represents the kind of pattern #[derive(Debug, Clone, Copy)] -pub enum PatternSource<'tcx> { +pub(crate) enum PatternSource<'tcx> { MatchExpr(&'tcx Expr), LetDecl(&'tcx Local), Other, @@ -86,20 +86,20 @@ fn get_pattern_source<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, pat: &Pat) -> Patte } } -pub fn gather_decl<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, - move_data: &MoveData<'tcx>, - var_id: ast::NodeId, - var_ty: Ty<'tcx>) { +pub(crate) fn gather_decl<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, + move_data: &MoveData<'tcx>, + var_id: ast::NodeId, + var_ty: Ty<'tcx>) { let loan_path = Rc::new(LoanPath::new(LpVar(var_id), var_ty)); move_data.add_move(bccx.tcx, loan_path, var_id, Declared); } -pub fn gather_move_from_expr<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, - move_data: &MoveData<'tcx>, - move_error_collector: &mut MoveErrorCollector<'tcx>, - move_expr_id: ast::NodeId, - cmt: mc::cmt<'tcx>, - move_reason: euv::MoveReason) { +pub(crate) fn gather_move_from_expr<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, + move_data: &MoveData<'tcx>, + move_error_collector: &mut MoveErrorCollector<'tcx>, + move_expr_id: ast::NodeId, + cmt: mc::cmt<'tcx>, + move_reason: euv::MoveReason) { let kind = match move_reason { euv::DirectRefMove | euv::PatBindingMove => MoveExpr, euv::CaptureMove => Captured @@ -113,42 +113,11 @@ pub fn gather_move_from_expr<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, gather_move(bccx, move_data, move_error_collector, move_info); } -pub fn gather_match_variant<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, - move_data: &MoveData<'tcx>, - _move_error_collector: &mut MoveErrorCollector<'tcx>, - move_pat: &hir::Pat, - cmt: mc::cmt<'tcx>, - mode: euv::MatchMode) { - let tcx = bccx.tcx; - debug!("gather_match_variant(move_pat={}, cmt={:?}, mode={:?})", - move_pat.id, cmt, mode); - - let opt_lp = opt_loan_path(&cmt); - match opt_lp { - Some(lp) => { - match lp.kind { - LpDowncast(ref base_lp, _) => - move_data.add_variant_match( - tcx, lp.clone(), move_pat.id, base_lp.clone(), mode), - _ => bug!("should only call gather_match_variant \ - for cat_downcast cmt"), - } - } - None => { - // We get None when input to match is non-path (e.g. - // temporary result like a function call). Since no - // loan-path is being matched, no need to record a - // downcast. - return; - } - } -} - -pub fn gather_move_from_pat<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, - move_data: &MoveData<'tcx>, - move_error_collector: &mut MoveErrorCollector<'tcx>, - move_pat: &hir::Pat, - cmt: mc::cmt<'tcx>) { +pub(crate) fn gather_move_from_pat<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, + move_data: &MoveData<'tcx>, + move_error_collector: &mut MoveErrorCollector<'tcx>, + move_pat: &hir::Pat, + cmt: mc::cmt<'tcx>) { let source = get_pattern_source(bccx.tcx,move_pat); let pat_span_path_opt = match move_pat.node { PatKind::Binding(_, _, ref path1, _) => { @@ -202,13 +171,13 @@ fn gather_move<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, } } -pub fn gather_assignment<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, - move_data: &MoveData<'tcx>, - assignment_id: ast::NodeId, - assignment_span: Span, - assignee_loan_path: Rc>, - assignee_id: ast::NodeId, - mode: euv::MutateMode) { +pub(crate) fn gather_assignment<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, + move_data: &MoveData<'tcx>, + assignment_id: ast::NodeId, + assignment_span: Span, + assignee_loan_path: Rc>, + assignee_id: ast::NodeId, + mode: euv::MutateMode) { move_data.add_assignment(bccx.tcx, assignee_loan_path, assignment_id, diff --git a/src/librustc_borrowck/borrowck/gather_loans/lifetime.rs b/src/librustc_borrowck/borrowck/gather_loans/lifetime.rs index 89c60da396913..5538d36835ab3 100644 --- a/src/librustc_borrowck/borrowck/gather_loans/lifetime.rs +++ b/src/librustc_borrowck/borrowck/gather_loans/lifetime.rs @@ -23,14 +23,14 @@ use syntax_pos::Span; type R = Result<(),()>; -pub fn guarantee_lifetime<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, - item_scope: region::CodeExtent, - span: Span, - cause: euv::LoanCause, - cmt: mc::cmt<'tcx>, - loan_region: ty::Region<'tcx>, - _: ty::BorrowKind) - -> Result<(),()> { +pub(crate) fn guarantee_lifetime<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, + item_scope: region::CodeExtent, + span: Span, + cause: euv::LoanCause, + cmt: mc::cmt<'tcx>, + loan_region: ty::Region<'tcx>, + _: ty::BorrowKind) + -> Result<(),()> { //! Reports error if `loan_region` is larger than S //! where S is `item_scope` if `cmt` is an upvar, //! and is scope of `cmt` otherwise. diff --git a/src/librustc_borrowck/borrowck/gather_loans/mod.rs b/src/librustc_borrowck/borrowck/gather_loans/mod.rs index 7dcb6ce76a401..a0b3ec22cd979 100644 --- a/src/librustc_borrowck/borrowck/gather_loans/mod.rs +++ b/src/librustc_borrowck/borrowck/gather_loans/mod.rs @@ -35,9 +35,9 @@ mod restrictions; mod gather_moves; mod move_error; -pub fn gather_loans_in_fn<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, - body: hir::BodyId) - -> (Vec>, move_data::MoveData<'tcx>) { +pub(crate) fn gather_loans_in_fn<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, + body: hir::BodyId) + -> (Vec>, move_data::MoveData<'tcx>) { let def_id = bccx.tcx.hir.body_owner_def_id(body); let param_env = bccx.tcx.param_env(def_id); let mut glcx = GatherLoanCtxt { @@ -94,12 +94,6 @@ impl<'a, 'tcx> euv::Delegate<'tcx> for GatherLoanCtxt<'a, 'tcx> { matched_pat, cmt, mode); - - if let Categorization::Downcast(..) = cmt.cat { - gather_moves::gather_match_variant( - self.bccx, &self.move_data, &mut self.move_error_collector, - matched_pat, cmt, mode); - } } fn consume_pat(&mut self, @@ -239,7 +233,7 @@ fn check_mutability<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, } impl<'a, 'tcx> GatherLoanCtxt<'a, 'tcx> { - pub fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { self.bccx.tcx } + pub(crate) fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { self.bccx.tcx } /// Guarantees that `cmt` is assignable, or reports an error. fn guarantee_assignment_valid(&mut self, @@ -432,7 +426,7 @@ impl<'a, 'tcx> GatherLoanCtxt<'a, 'tcx> { // } } - pub fn mark_loan_path_as_mutated(&self, loan_path: &LoanPath) { + pub(crate) fn mark_loan_path_as_mutated(&self, loan_path: &LoanPath) { //! For mutable loans of content whose mutability derives //! from a local variable, mark the mutability decl as necessary. @@ -452,10 +446,10 @@ impl<'a, 'tcx> GatherLoanCtxt<'a, 'tcx> { } } - pub fn compute_gen_scope(&self, - borrow_scope: region::CodeExtent, - loan_scope: region::CodeExtent) - -> region::CodeExtent { + pub(crate) fn compute_gen_scope(&self, + borrow_scope: region::CodeExtent, + loan_scope: region::CodeExtent) + -> region::CodeExtent { //! Determine when to introduce the loan. Typically the loan //! is introduced at the point of the borrow, but in some cases, //! notably method arguments, the loan may be introduced only @@ -468,8 +462,8 @@ impl<'a, 'tcx> GatherLoanCtxt<'a, 'tcx> { } } - pub fn compute_kill_scope(&self, loan_scope: region::CodeExtent, lp: &LoanPath<'tcx>) - -> region::CodeExtent { + pub(crate) fn compute_kill_scope(&self, loan_scope: region::CodeExtent, lp: &LoanPath<'tcx>) + -> region::CodeExtent { //! Determine when the loan restrictions go out of scope. //! This is either when the lifetime expires or when the //! local variable which roots the loan-path goes out of scope, @@ -500,7 +494,7 @@ impl<'a, 'tcx> GatherLoanCtxt<'a, 'tcx> { } } - pub fn report_potential_errors(&self) { + pub(crate) fn report_potential_errors(&self) { self.move_error_collector.report_potential_errors(self.bccx); } } diff --git a/src/librustc_borrowck/borrowck/gather_loans/move_error.rs b/src/librustc_borrowck/borrowck/gather_loans/move_error.rs index cceb4a7b3cc21..de383f54df7b9 100644 --- a/src/librustc_borrowck/borrowck/gather_loans/move_error.rs +++ b/src/librustc_borrowck/borrowck/gather_loans/move_error.rs @@ -19,35 +19,35 @@ use syntax_pos; use errors::DiagnosticBuilder; use borrowck::gather_loans::gather_moves::PatternSource; -pub struct MoveErrorCollector<'tcx> { +pub(crate) struct MoveErrorCollector<'tcx> { errors: Vec> } impl<'tcx> MoveErrorCollector<'tcx> { - pub fn new() -> MoveErrorCollector<'tcx> { + pub(crate) fn new() -> MoveErrorCollector<'tcx> { MoveErrorCollector { errors: Vec::new() } } - pub fn add_error(&mut self, error: MoveError<'tcx>) { + pub(crate) fn add_error(&mut self, error: MoveError<'tcx>) { self.errors.push(error); } - pub fn report_potential_errors<'a>(&self, bccx: &BorrowckCtxt<'a, 'tcx>) { + pub(crate) fn report_potential_errors<'a>(&self, bccx: &BorrowckCtxt<'a, 'tcx>) { report_move_errors(bccx, &self.errors) } } -pub struct MoveError<'tcx> { +pub(crate) struct MoveError<'tcx> { move_from: mc::cmt<'tcx>, move_to: Option> } impl<'tcx> MoveError<'tcx> { - pub fn with_move_info(move_from: mc::cmt<'tcx>, - move_to: Option>) - -> MoveError<'tcx> { + pub(crate) fn with_move_info(move_from: mc::cmt<'tcx>, + move_to: Option>) + -> MoveError<'tcx> { MoveError { move_from: move_from, move_to: move_to, @@ -56,13 +56,13 @@ impl<'tcx> MoveError<'tcx> { } #[derive(Clone)] -pub struct MovePlace<'tcx> { - pub span: syntax_pos::Span, - pub name: ast::Name, - pub pat_source: PatternSource<'tcx>, +pub(crate) struct MovePlace<'tcx> { + pub(crate) span: syntax_pos::Span, + pub(crate) name: ast::Name, + pub(crate) pat_source: PatternSource<'tcx>, } -pub struct GroupedMoveErrors<'tcx> { +pub(crate) struct GroupedMoveErrors<'tcx> { move_from: mc::cmt<'tcx>, move_to_places: Vec> } diff --git a/src/librustc_borrowck/borrowck/gather_loans/restrictions.rs b/src/librustc_borrowck/borrowck/gather_loans/restrictions.rs index b7965f81b8826..bbd495ea628b0 100644 --- a/src/librustc_borrowck/borrowck/gather_loans/restrictions.rs +++ b/src/librustc_borrowck/borrowck/gather_loans/restrictions.rs @@ -22,17 +22,17 @@ use borrowck::ToInteriorKind; use std::rc::Rc; #[derive(Debug)] -pub enum RestrictionResult<'tcx> { +pub(crate) enum RestrictionResult<'tcx> { Safe, SafeIf(Rc>, Vec>>) } -pub fn compute_restrictions<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, - span: Span, - cause: euv::LoanCause, - cmt: mc::cmt<'tcx>, - loan_region: ty::Region<'tcx>) - -> RestrictionResult<'tcx> { +pub(crate) fn compute_restrictions<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, + span: Span, + cause: euv::LoanCause, + cmt: mc::cmt<'tcx>, + loan_region: ty::Region<'tcx>) + -> RestrictionResult<'tcx> { let ctxt = RestrictionsContext { bccx: bccx, span: span, diff --git a/src/librustc_borrowck/borrowck/mod.rs b/src/librustc_borrowck/borrowck/mod.rs index 1bfc5805bc8fd..c2e1e67a9ab64 100644 --- a/src/librustc_borrowck/borrowck/mod.rs +++ b/src/librustc_borrowck/borrowck/mod.rs @@ -12,11 +12,11 @@ #![allow(non_camel_case_types)] -pub use self::LoanPathKind::*; -pub use self::LoanPathElem::*; -pub use self::bckerr_code::*; -pub use self::AliasableViolationKind::*; -pub use self::MovedValueUseKind::*; +pub(crate) use self::LoanPathKind::*; +pub(crate) use self::LoanPathElem::*; +pub(crate) use self::bckerr_code::*; +pub(crate) use self::AliasableViolationKind::*; +pub(crate) use self::MovedValueUseKind::*; use self::InteriorKind::*; @@ -47,16 +47,16 @@ use errors::DiagnosticBuilder; use rustc::hir; use rustc::hir::intravisit::{self, Visitor}; -pub mod check_loans; +pub(crate) mod check_loans; -pub mod gather_loans; +pub(crate) mod gather_loans; -pub mod move_data; +pub(crate) mod move_data; #[derive(Clone, Copy)] -pub struct LoanDataFlowOperator; +pub(crate) struct LoanDataFlowOperator; -pub type LoanDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, LoanDataFlowOperator>; +pub(crate) type LoanDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, LoanDataFlowOperator>; pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { for body_owner_def_id in tcx.body_owners() { @@ -73,9 +73,9 @@ pub fn provide(providers: &mut Providers) { /// Collection of conclusions determined via borrow checker analyses. pub struct AnalysisData<'a, 'tcx: 'a> { - pub all_loans: Vec>, - pub loans: DataFlowContext<'a, 'tcx, LoanDataFlowOperator>, - pub move_data: move_data::FlowedMoveData<'a, 'tcx>, + pub(crate) all_loans: Vec>, + pub(crate) loans: DataFlowContext<'a, 'tcx, LoanDataFlowOperator>, + pub(crate) move_data: move_data::FlowedMoveData<'a, 'tcx>, } fn borrowck<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, owner_def_id: DefId) { @@ -201,7 +201,7 @@ pub struct BorrowckCtxt<'a, 'tcx: 'a> { // Loans and loan paths /// Record of a loan that was issued. -pub struct Loan<'tcx> { +pub(crate) struct Loan<'tcx> { index: usize, loan_path: Rc>, kind: ty::BorrowKind, @@ -224,13 +224,13 @@ pub struct Loan<'tcx> { } impl<'tcx> Loan<'tcx> { - pub fn loan_path(&self) -> Rc> { + pub(crate) fn loan_path(&self) -> Rc> { self.loan_path.clone() } } #[derive(Eq)] -pub struct LoanPath<'tcx> { +pub(crate) struct LoanPath<'tcx> { kind: LoanPathKind<'tcx>, ty: ty::Ty<'tcx>, } @@ -248,7 +248,7 @@ impl<'tcx> Hash for LoanPath<'tcx> { } #[derive(PartialEq, Eq, Hash, Debug)] -pub enum LoanPathKind<'tcx> { +pub(crate) enum LoanPathKind<'tcx> { LpVar(ast::NodeId), // `x` in README.md LpUpvar(ty::UpvarId), // `x` captured by-value into closure LpDowncast(Rc>, DefId), // `x` downcast to particular enum variant @@ -273,7 +273,7 @@ const DOWNCAST_PRINTED_OPERATOR: &'static str = " as "; // particular, the distinction between how precisely an array-element // is tracked is irrelevant here.) #[derive(Clone, Copy, PartialEq, Eq, Hash)] -pub enum InteriorKind { +pub(crate) enum InteriorKind { InteriorField(mc::FieldName), InteriorElement, } @@ -297,13 +297,12 @@ impl ToInteriorKind for mc::InteriorKind { // `enum E { X { foo: u32 }, Y { foo: u32 }}` // each `foo` is qualified by the definitition id of the variant (`X` or `Y`). #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] -pub enum LoanPathElem<'tcx> { +pub(crate) enum LoanPathElem<'tcx> { LpDeref(mc::PointerKind<'tcx>), LpInterior(Option, InteriorKind), } -pub fn closure_to_block(closure_id: ast::NodeId, - tcx: TyCtxt) -> ast::NodeId { +pub(crate) fn closure_to_block(closure_id: ast::NodeId, tcx: TyCtxt) -> ast::NodeId { match tcx.hir.get(closure_id) { hir_map::NodeExpr(expr) => match expr.node { hir::ExprClosure(.., body_id, _) => { @@ -318,7 +317,7 @@ pub fn closure_to_block(closure_id: ast::NodeId, } impl<'a, 'tcx> LoanPath<'tcx> { - pub fn kill_scope(&self, bccx: &BorrowckCtxt<'a, 'tcx>) -> region::CodeExtent { + pub(crate) fn kill_scope(&self, bccx: &BorrowckCtxt<'a, 'tcx>) -> region::CodeExtent { match self.kind { LpVar(local_id) => bccx.region_maps.var_scope(local_id), LpUpvar(upvar_id) => { @@ -394,7 +393,7 @@ impl<'a, 'tcx> LoanPath<'tcx> { } } -pub fn opt_loan_path<'tcx>(cmt: &mc::cmt<'tcx>) -> Option>> { +pub(crate) fn opt_loan_path<'tcx>(cmt: &mc::cmt<'tcx>) -> Option>> { //! Computes the `LoanPath` (if any) for a `cmt`. //! Note that this logic is somewhat duplicated in //! the method `compute()` found in `gather_loans::restrictions`, @@ -447,7 +446,7 @@ pub fn opt_loan_path<'tcx>(cmt: &mc::cmt<'tcx>) -> Option>> { // Errors that can occur #[derive(Debug, PartialEq)] -pub enum bckerr_code<'tcx> { +pub(crate) enum bckerr_code<'tcx> { err_mutbl, /// superscope, subscope, loan cause err_out_of_scope(ty::Region<'tcx>, ty::Region<'tcx>, euv::LoanCause), @@ -457,7 +456,7 @@ pub enum bckerr_code<'tcx> { // Combination of an error code and the categorization of the expression // that caused it #[derive(Debug, PartialEq)] -pub struct BckError<'tcx> { +pub(crate) struct BckError<'tcx> { span: Span, cause: AliasableViolationKind, cmt: mc::cmt<'tcx>, @@ -465,13 +464,13 @@ pub struct BckError<'tcx> { } #[derive(Copy, Clone, Debug, PartialEq)] -pub enum AliasableViolationKind { +pub(crate) enum AliasableViolationKind { MutabilityViolation, BorrowViolation(euv::LoanCause) } #[derive(Copy, Clone, Debug)] -pub enum MovedValueUseKind { +pub(crate) enum MovedValueUseKind { MovedInUse, MovedInCapture, } @@ -480,10 +479,10 @@ pub enum MovedValueUseKind { // Misc impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { - pub fn is_subregion_of(&self, - r_sub: ty::Region<'tcx>, - r_sup: ty::Region<'tcx>) - -> bool + pub(crate) fn is_subregion_of(&self, + r_sub: ty::Region<'tcx>, + r_sup: ty::Region<'tcx>) + -> bool { let region_rels = RegionRelations::new(self.tcx, self.owner_def_id, @@ -492,7 +491,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { region_rels.is_subregion_of(r_sub, r_sup) } - pub fn report(&self, err: BckError<'tcx>) { + pub(crate) fn report(&self, err: BckError<'tcx>) { // Catch and handle some particular cases. match (&err.code, &err.cause) { (&err_out_of_scope(&ty::ReScope(_), &ty::ReStatic, _), @@ -511,13 +510,13 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { db.emit(); } - pub fn report_use_of_moved_value(&self, - use_span: Span, - use_kind: MovedValueUseKind, - lp: &LoanPath<'tcx>, - the_move: &move_data::Move, - moved_lp: &LoanPath<'tcx>, - _param_env: ty::ParamEnv<'tcx>) { + pub(crate) fn report_use_of_moved_value(&self, + use_span: Span, + use_kind: MovedValueUseKind, + lp: &LoanPath<'tcx>, + the_move: &move_data::Move, + moved_lp: &LoanPath<'tcx>, + _param_env: ty::ParamEnv<'tcx>) { let (verb, verb_participle) = match use_kind { MovedInUse => ("use", "used"), MovedInCapture => ("capture", "captured"), @@ -645,7 +644,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { err.emit(); } - pub fn report_partial_reinitialization_of_uninitialized_structure( + pub(crate) fn report_partial_reinitialization_of_uninitialized_structure( &self, span: Span, lp: &LoanPath<'tcx>) { @@ -655,11 +654,11 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { self.loan_path_to_string(lp)); } - pub fn report_reassigned_immutable_variable(&self, - span: Span, - lp: &LoanPath<'tcx>, - assign: - &move_data::Assignment) { + pub(crate) fn report_reassigned_immutable_variable(&self, + span: Span, + lp: &LoanPath<'tcx>, + assign: + &move_data::Assignment) { let mut err = struct_span_err!( self.tcx.sess, span, E0384, "re-assignment of immutable variable `{}`", @@ -672,27 +671,14 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { err.emit(); } - pub fn span_err(&self, s: Span, m: &str) { - self.tcx.sess.span_err(s, m); - } - - pub fn struct_span_err>(&self, s: S, m: &str) - -> DiagnosticBuilder<'a> { - self.tcx.sess.struct_span_err(s, m) - } - - pub fn struct_span_err_with_code>(&self, - s: S, - msg: &str, - code: &str) - -> DiagnosticBuilder<'a> { + pub(crate) fn struct_span_err_with_code>(&self, + s: S, + msg: &str, + code: &str) + -> DiagnosticBuilder<'a> { self.tcx.sess.struct_span_err_with_code(s, msg, code) } - pub fn span_err_with_code>(&self, s: S, msg: &str, code: &str) { - self.tcx.sess.span_err_with_code(s, msg, code); - } - fn bckerr_to_diag(&self, err: &BckError<'tcx>) -> DiagnosticBuilder<'a> { let span = err.span.clone(); @@ -761,11 +747,11 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { } } - pub fn report_aliasability_violation(&self, - span: Span, - kind: AliasableViolationKind, - cause: mc::AliasableReason, - cmt: mc::cmt<'tcx>) { + pub(crate) fn report_aliasability_violation(&self, + span: Span, + kind: AliasableViolationKind, + cause: mc::AliasableReason, + cmt: mc::cmt<'tcx>) { let mut is_closure = false; let prefix = match kind { MutabilityViolation => { @@ -1181,9 +1167,9 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { } } } - pub fn append_loan_path_to_string(&self, - loan_path: &LoanPath<'tcx>, - out: &mut String) { + pub(crate) fn append_loan_path_to_string(&self, + loan_path: &LoanPath<'tcx>, + out: &mut String) { match loan_path.kind { LpUpvar(ty::UpvarId{ var_id: id, closure_expr_id: _ }) | LpVar(id) => { @@ -1224,9 +1210,9 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { } } - pub fn append_autoderefd_loan_path_to_string(&self, - loan_path: &LoanPath<'tcx>, - out: &mut String) { + pub(crate) fn append_autoderefd_loan_path_to_string(&self, + loan_path: &LoanPath<'tcx>, + out: &mut String) { match loan_path.kind { LpExtend(ref lp_base, _, LpDeref(_)) => { // For a path like `(*x).f` or `(*x)[3]`, autoderef @@ -1249,17 +1235,17 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { } } - pub fn loan_path_to_string(&self, loan_path: &LoanPath<'tcx>) -> String { + pub(crate) fn loan_path_to_string(&self, loan_path: &LoanPath<'tcx>) -> String { let mut result = String::new(); self.append_loan_path_to_string(loan_path, &mut result); result } - pub fn cmt_to_string(&self, cmt: &mc::cmt_<'tcx>) -> String { + pub(crate) fn cmt_to_string(&self, cmt: &mc::cmt_<'tcx>) -> String { cmt.descriptive_string(self.tcx) } - pub fn cmt_to_path_or_string(&self, cmt: &mc::cmt<'tcx>) -> String { + pub(crate) fn cmt_to_path_or_string(&self, cmt: &mc::cmt<'tcx>) -> String { match opt_loan_path(cmt) { Some(lp) => format!("`{}`", self.loan_path_to_string(&lp)), None => self.cmt_to_string(cmt), diff --git a/src/librustc_borrowck/borrowck/move_data.rs b/src/librustc_borrowck/borrowck/move_data.rs index 0a31905c7928a..d56a6309a012e 100644 --- a/src/librustc_borrowck/borrowck/move_data.rs +++ b/src/librustc_borrowck/borrowck/move_data.rs @@ -11,7 +11,7 @@ //! Data structures used for tracking moves. Please see the extensive //! comments in the section "Moves and initialization" in `README.md`. -pub use self::MoveKind::*; +pub(crate) use self::MoveKind::*; use borrowck::*; use rustc::cfg; @@ -33,48 +33,44 @@ use syntax_pos::Span; use rustc::hir; use rustc::hir::intravisit::IdRange; -pub struct MoveData<'tcx> { +pub(crate) struct MoveData<'tcx> { /// Move paths. See section "Move paths" in `README.md`. - pub paths: RefCell>>, + pub(crate) paths: RefCell>>, /// Cache of loan path to move path index, for easy lookup. - pub path_map: RefCell>, MovePathIndex>>, + pub(crate) path_map: RefCell>, MovePathIndex>>, /// Each move or uninitialized variable gets an entry here. - pub moves: RefCell>, + pub(crate) moves: RefCell>, /// Assignments to a variable, like `x = foo`. These are assigned /// bits for dataflow, since we must track them to ensure that /// immutable variables are assigned at most once along each path. - pub var_assignments: RefCell>, + pub(crate) var_assignments: RefCell>, /// Assignments to a path, like `x.f = foo`. These are not /// assigned dataflow bits, but we track them because they still /// kill move bits. - pub path_assignments: RefCell>, - - /// Enum variant matched within a pattern on some match arm, like - /// `SomeStruct{ f: Variant1(x, y) } => ...` - pub variant_matches: RefCell>, + pub(crate) path_assignments: RefCell>, /// Assignments to a variable or path, like `x = foo`, but not `x += foo`. - pub assignee_ids: RefCell, + pub(crate) assignee_ids: RefCell, } -pub struct FlowedMoveData<'a, 'tcx: 'a> { - pub move_data: MoveData<'tcx>, +pub(crate) struct FlowedMoveData<'a, 'tcx: 'a> { + pub(crate) move_data: MoveData<'tcx>, - pub dfcx_moves: MoveDataFlow<'a, 'tcx>, + pub(crate) dfcx_moves: MoveDataFlow<'a, 'tcx>, // We could (and maybe should, for efficiency) combine both move // and assign data flow into one, but this way it's easier to // distinguish the bits that correspond to moves and assignments. - pub dfcx_assign: AssignDataFlow<'a, 'tcx> + pub(crate) dfcx_assign: AssignDataFlow<'a, 'tcx> } /// Index into `MoveData.paths`, used like a pointer #[derive(Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] -pub struct MovePathIndex(usize); +pub(crate) struct MovePathIndex(usize); impl MovePathIndex { fn get(&self) -> usize { @@ -93,7 +89,7 @@ const InvalidMovePathIndex: MovePathIndex = MovePathIndex(usize::MAX); /// Index into `MoveData.moves`, used like a pointer #[derive(Copy, Clone, PartialEq)] -pub struct MoveIndex(usize); +pub(crate) struct MoveIndex(usize); impl MoveIndex { fn get(&self) -> usize { @@ -104,27 +100,27 @@ impl MoveIndex { #[allow(non_upper_case_globals)] const InvalidMoveIndex: MoveIndex = MoveIndex(usize::MAX); -pub struct MovePath<'tcx> { +pub(crate) struct MovePath<'tcx> { /// Loan path corresponding to this move path - pub loan_path: Rc>, + pub(crate) loan_path: Rc>, /// Parent pointer, `InvalidMovePathIndex` if root - pub parent: MovePathIndex, + pub(crate) parent: MovePathIndex, /// Head of linked list of moves to this path, /// `InvalidMoveIndex` if not moved - pub first_move: MoveIndex, + pub(crate) first_move: MoveIndex, /// First node in linked list of children, `InvalidMovePathIndex` if leaf - pub first_child: MovePathIndex, + pub(crate) first_child: MovePathIndex, /// Next node in linked list of parent's children (siblings), /// `InvalidMovePathIndex` if none. - pub next_sibling: MovePathIndex, + pub(crate) next_sibling: MovePathIndex, } #[derive(Copy, Clone, PartialEq, Debug)] -pub enum MoveKind { +pub(crate) enum MoveKind { Declared, // When declared, variables start out "moved". MoveExpr, // Expression or binding that moves a variable MovePat, // By-move binding @@ -132,59 +128,44 @@ pub enum MoveKind { } #[derive(Copy, Clone)] -pub struct Move { +pub(crate) struct Move { /// Path being moved. - pub path: MovePathIndex, + pub(crate) path: MovePathIndex, /// id of node that is doing the move. - pub id: ast::NodeId, + pub(crate) id: ast::NodeId, /// Kind of move, for error messages. - pub kind: MoveKind, + pub(crate) kind: MoveKind, /// Next node in linked list of moves from `path`, or `InvalidMoveIndex` - pub next_move: MoveIndex + pub(crate) next_move: MoveIndex } #[derive(Copy, Clone)] -pub struct Assignment { +pub(crate) struct Assignment { /// Path being assigned. - pub path: MovePathIndex, + pub(crate) path: MovePathIndex, /// id where assignment occurs - pub id: ast::NodeId, + pub(crate) id: ast::NodeId, /// span of node where assignment occurs - pub span: Span, - - /// id for l-value expression on lhs of assignment - pub assignee_id: ast::NodeId, + pub(crate) span: Span, } #[derive(Copy, Clone)] -pub struct VariantMatch { - /// downcast to the variant. - pub path: MovePathIndex, - - /// path being downcast to the variant. - pub base_path: MovePathIndex, - - /// id where variant's pattern occurs - pub id: ast::NodeId, - - /// says if variant established by move (and why), by copy, or by borrow. - pub mode: euv::MatchMode -} +pub(crate) struct VariantMatch {} #[derive(Clone, Copy)] -pub struct MoveDataFlowOperator; +pub(crate) struct MoveDataFlowOperator; -pub type MoveDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, MoveDataFlowOperator>; +pub(crate) type MoveDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, MoveDataFlowOperator>; #[derive(Clone, Copy)] -pub struct AssignDataFlowOperator; +pub(crate) struct AssignDataFlowOperator; -pub type AssignDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, AssignDataFlowOperator>; +pub(crate) type AssignDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, AssignDataFlowOperator>; fn loan_path_is_precise(loan_path: &LoanPath) -> bool { match loan_path.kind { @@ -208,19 +189,18 @@ fn loan_path_is_precise(loan_path: &LoanPath) -> bool { } impl<'a, 'tcx> MoveData<'tcx> { - pub fn new() -> MoveData<'tcx> { + pub(crate) fn new() -> MoveData<'tcx> { MoveData { paths: RefCell::new(Vec::new()), path_map: RefCell::new(FxHashMap()), moves: RefCell::new(Vec::new()), path_assignments: RefCell::new(Vec::new()), var_assignments: RefCell::new(Vec::new()), - variant_matches: RefCell::new(Vec::new()), assignee_ids: RefCell::new(NodeSet()), } } - pub fn path_loan_path(&self, index: MovePathIndex) -> Rc> { + pub(crate) fn path_loan_path(&self, index: MovePathIndex) -> Rc> { (*self.paths.borrow())[index.get()].loan_path.clone() } @@ -266,8 +246,8 @@ impl<'a, 'tcx> MoveData<'tcx> { /// Returns the existing move path index for `lp`, if any, and otherwise adds a new index for /// `lp` and any of its base paths that do not yet have an index. - pub fn move_path(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, - lp: Rc>) -> MovePathIndex { + pub(crate) fn move_path(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, + lp: Rc>) -> MovePathIndex { if let Some(&index) = self.path_map.borrow().get(&lp) { return index; } @@ -354,10 +334,10 @@ impl<'a, 'tcx> MoveData<'tcx> { } /// Adds a new move entry for a move of `lp` that occurs at location `id` with kind `kind`. - pub fn add_move(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, - orig_lp: Rc>, - id: ast::NodeId, - kind: MoveKind) { + pub(crate) fn add_move(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, + orig_lp: Rc>, + id: ast::NodeId, + kind: MoveKind) { // Moving one union field automatically moves all its fields. Also move siblings of // all parent union fields, moves do not propagate upwards automatically. let mut lp = orig_lp.clone(); @@ -407,12 +387,12 @@ impl<'a, 'tcx> MoveData<'tcx> { /// Adds a new record for an assignment to `lp` that occurs at location `id` with the given /// `span`. - pub fn add_assignment(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, - lp: Rc>, - assign_id: ast::NodeId, - span: Span, - assignee_id: ast::NodeId, - mode: euv::MutateMode) { + pub(crate) fn add_assignment(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, + lp: Rc>, + assign_id: ast::NodeId, + span: Span, + assignee_id: ast::NodeId, + mode: euv::MutateMode) { // Assigning to one union field automatically assigns to all its fields. if let LpExtend(ref base_lp, mutbl, LpInterior(opt_variant_id, interior)) = lp.kind { if let ty::TyAdt(adt_def, _) = base_lp.ty.sty { @@ -460,7 +440,6 @@ impl<'a, 'tcx> MoveData<'tcx> { path: path_index, id: assign_id, span: span, - assignee_id: assignee_id, }; if self.is_var_path(path_index) { @@ -476,31 +455,6 @@ impl<'a, 'tcx> MoveData<'tcx> { } } - /// Adds a new record for a match of `base_lp`, downcast to - /// variant `lp`, that occurs at location `pattern_id`. (One - /// should be able to recover the span info from the - /// `pattern_id` and the hir_map, I think.) - pub fn add_variant_match(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, - lp: Rc>, - pattern_id: ast::NodeId, - base_lp: Rc>, - mode: euv::MatchMode) { - debug!("add_variant_match(lp={:?}, pattern_id={})", - lp, pattern_id); - - let path_index = self.move_path(tcx, lp.clone()); - let base_path_index = self.move_path(tcx, base_lp.clone()); - - let variant_match = VariantMatch { - path: path_index, - base_path: base_path_index, - id: pattern_id, - mode: mode, - }; - - self.variant_matches.borrow_mut().push(variant_match); - } - /// Adds the gen/kills for the various moves and /// assignments into the provided data flow contexts. /// Moves are generated by moves and killed by assignments and @@ -635,12 +589,12 @@ impl<'a, 'tcx> MoveData<'tcx> { } impl<'a, 'tcx> FlowedMoveData<'a, 'tcx> { - pub fn new(move_data: MoveData<'tcx>, - bccx: &BorrowckCtxt<'a, 'tcx>, - cfg: &cfg::CFG, - id_range: IdRange, - body: &hir::Body) - -> FlowedMoveData<'a, 'tcx> { + pub(crate) fn new(move_data: MoveData<'tcx>, + bccx: &BorrowckCtxt<'a, 'tcx>, + cfg: &cfg::CFG, + id_range: IdRange, + body: &hir::Body) + -> FlowedMoveData<'a, 'tcx> { let tcx = bccx.tcx; let mut dfcx_moves = @@ -677,10 +631,10 @@ impl<'a, 'tcx> FlowedMoveData<'a, 'tcx> { } } - pub fn kind_of_move_of_path(&self, - id: ast::NodeId, - loan_path: &Rc>) - -> Option { + pub(crate) fn kind_of_move_of_path(&self, + id: ast::NodeId, + loan_path: &Rc>) + -> Option { //! Returns the kind of a move of `loan_path` by `id`, if one exists. let mut ret = None; @@ -702,11 +656,11 @@ impl<'a, 'tcx> FlowedMoveData<'a, 'tcx> { /// Iterates through each move of `loan_path` (or some base path of `loan_path`) that *may* /// have occurred on entry to `id` without an intervening assignment. In other words, any moves /// that would invalidate a reference to `loan_path` at location `id`. - pub fn each_move_of(&self, - id: ast::NodeId, - loan_path: &Rc>, - mut f: F) - -> bool where + pub(crate) fn each_move_of(&self, + id: ast::NodeId, + loan_path: &Rc>, + mut f: F) + -> bool where F: FnMut(&Move, &LoanPath<'tcx>) -> bool, { // Bad scenarios: @@ -759,11 +713,11 @@ impl<'a, 'tcx> FlowedMoveData<'a, 'tcx> { /// Iterates through every assignment to `loan_path` that may have occurred on entry to `id`. /// `loan_path` must be a single variable. - pub fn each_assignment_of(&self, - id: ast::NodeId, - loan_path: &Rc>, - mut f: F) - -> bool where + pub(crate) fn each_assignment_of(&self, + id: ast::NodeId, + loan_path: &Rc>, + mut f: F) + -> bool where F: FnMut(&Assignment) -> bool, { let loan_path_index = { diff --git a/src/librustc_borrowck/graphviz.rs b/src/librustc_borrowck/graphviz.rs index e3a2bfa392738..30fd1fed3e75b 100644 --- a/src/librustc_borrowck/graphviz.rs +++ b/src/librustc_borrowck/graphviz.rs @@ -14,7 +14,7 @@ pub use self::Variant::*; -pub use rustc::cfg::graphviz::{Node, Edge}; +pub(crate) use rustc::cfg::graphviz::{Node, Edge}; use rustc::cfg::graphviz as cfg_dot; use borrowck; @@ -33,7 +33,7 @@ pub enum Variant { } impl Variant { - pub fn short_name(&self) -> &'static str { + pub(crate) fn short_name(&self) -> &'static str { match *self { Loans => "loans", Moves => "moves", diff --git a/src/librustc_borrowck/lib.rs b/src/librustc_borrowck/lib.rs index 723df564419a4..596d7c506ea95 100644 --- a/src/librustc_borrowck/lib.rs +++ b/src/librustc_borrowck/lib.rs @@ -39,11 +39,10 @@ extern crate core; // for NonZero pub use borrowck::check_crate; pub use borrowck::build_borrowck_dataflow_data_for_fn; -pub use borrowck::{AnalysisData, BorrowckCtxt}; // NB: This module needs to be declared first so diagnostics are // registered before they are used. -pub mod diagnostics; +mod diagnostics; mod borrowck; diff --git a/src/librustc_const_eval/_match.rs b/src/librustc_const_eval/_match.rs index bae44c0047e2e..b2837324942a5 100644 --- a/src/librustc_const_eval/_match.rs +++ b/src/librustc_const_eval/_match.rs @@ -38,8 +38,8 @@ use std::cmp::{self, Ordering}; use std::fmt; use std::iter::{FromIterator, IntoIterator, repeat}; -pub fn expand_pattern<'a, 'tcx>(cx: &MatchCheckCtxt<'a, 'tcx>, pat: Pattern<'tcx>) - -> &'a Pattern<'tcx> +pub(crate) fn expand_pattern<'a, 'tcx>(cx: &MatchCheckCtxt<'a, 'tcx>, pat: Pattern<'tcx>) + -> &'a Pattern<'tcx> { cx.pattern_arena.alloc(LiteralExpander.fold_pattern(&pat)) } @@ -79,14 +79,14 @@ impl<'tcx> Pattern<'tcx> { } } -pub struct Matrix<'a, 'tcx: 'a>(Vec>>); +pub(crate) struct Matrix<'a, 'tcx: 'a>(Vec>>); impl<'a, 'tcx> Matrix<'a, 'tcx> { - pub fn empty() -> Self { + pub(crate) fn empty() -> Self { Matrix(vec![]) } - pub fn push(&mut self, row: Vec<&'a Pattern<'tcx>>) { + pub(crate) fn push(&mut self, row: Vec<&'a Pattern<'tcx>>) { self.0.push(row) } } @@ -143,21 +143,21 @@ impl<'a, 'tcx> FromIterator>> for Matrix<'a, 'tcx> { } //NOTE: appears to be the only place other then InferCtxt to contain a ParamEnv -pub struct MatchCheckCtxt<'a, 'tcx: 'a> { - pub tcx: TyCtxt<'a, 'tcx, 'tcx>, +pub(crate) struct MatchCheckCtxt<'a, 'tcx: 'a> { + pub(crate) tcx: TyCtxt<'a, 'tcx, 'tcx>, /// The module in which the match occurs. This is necessary for /// checking inhabited-ness of types because whether a type is (visibly) /// inhabited can depend on whether it was defined in the current module or /// not. eg. `struct Foo { _private: ! }` cannot be seen to be empty /// outside it's module and should not be matchable with an empty match /// statement. - pub module: DefId, - pub pattern_arena: &'a TypedArena>, - pub byte_array_map: FxHashMap<*const Pattern<'tcx>, Vec<&'a Pattern<'tcx>>>, + pub(crate) module: DefId, + pub(crate) pattern_arena: &'a TypedArena>, + pub(crate) byte_array_map: FxHashMap<*const Pattern<'tcx>, Vec<&'a Pattern<'tcx>>>, } impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> { - pub fn create_and_enter( + pub(crate) fn create_and_enter( tcx: TyCtxt<'a, 'tcx, 'tcx>, module: DefId, f: F) -> R @@ -221,7 +221,7 @@ impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> { } #[derive(Clone, Debug, PartialEq)] -pub enum Constructor<'tcx> { +pub(crate) enum Constructor<'tcx> { /// The constructor of all patterns that don't vary by constructor, /// e.g. struct patterns and fixed-length arrays. Single, @@ -249,7 +249,7 @@ impl<'tcx> Constructor<'tcx> { } #[derive(Clone)] -pub enum Usefulness<'tcx> { +pub(crate) enum Usefulness<'tcx> { Useful, UsefulWithWitness(Vec>), NotUseful @@ -265,7 +265,7 @@ impl<'tcx> Usefulness<'tcx> { } #[derive(Copy, Clone)] -pub enum WitnessPreference { +pub(crate) enum WitnessPreference { ConstructWitness, LeaveOutWitness } @@ -278,10 +278,10 @@ struct PatternContext<'tcx> { /// A stack of patterns in reverse order of construction #[derive(Clone)] -pub struct Witness<'tcx>(Vec>); +pub(crate) struct Witness<'tcx>(Vec>); impl<'tcx> Witness<'tcx> { - pub fn single_pattern(&self) -> &Pattern<'tcx> { + pub(crate) fn single_pattern(&self) -> &Pattern<'tcx> { assert_eq!(self.0.len(), 1); &self.0[0] } @@ -545,11 +545,11 @@ fn max_slice_length<'p, 'a: 'p, 'tcx: 'a, I>( /// relation to preceding patterns, it is not reachable) and exhaustiveness /// checking (if a wildcard pattern is useful in relation to a matrix, the /// matrix isn't exhaustive). -pub fn is_useful<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>, - matrix: &Matrix<'p, 'tcx>, - v: &[&'p Pattern<'tcx>], - witness: WitnessPreference) - -> Usefulness<'tcx> { +pub(crate) fn is_useful<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>, + matrix: &Matrix<'p, 'tcx>, + v: &[&'p Pattern<'tcx>], + witness: WitnessPreference) + -> Usefulness<'tcx> { let &Matrix(ref rows) = matrix; debug!("is_useful({:?}, {:?})", matrix, v); diff --git a/src/librustc_const_eval/eval.rs b/src/librustc_const_eval/eval.rs index 72fa858e4cba8..07a290de0bad1 100644 --- a/src/librustc_const_eval/eval.rs +++ b/src/librustc_const_eval/eval.rs @@ -720,8 +720,8 @@ fn parse_float<'tcx>(num: &str, fty: ast::FloatTy) }) } -pub fn compare_const_vals(tcx: TyCtxt, span: Span, a: &ConstVal, b: &ConstVal) - -> Result +pub(crate) fn compare_const_vals(tcx: TyCtxt, span: Span, a: &ConstVal, b: &ConstVal) + -> Result { let result = match (a, b) { (&Integral(a), &Integral(b)) => a.try_cmp(b).ok(), diff --git a/src/librustc_const_eval/lib.rs b/src/librustc_const_eval/lib.rs index 5a61f35ed1ce9..3483752d4ff01 100644 --- a/src/librustc_const_eval/lib.rs +++ b/src/librustc_const_eval/lib.rs @@ -41,7 +41,7 @@ extern crate syntax_pos; // NB: This module needs to be declared first so diagnostics are // registered before they are used. -pub mod diagnostics; +mod diagnostics; mod eval; mod _match; diff --git a/src/librustc_const_eval/pattern.rs b/src/librustc_const_eval/pattern.rs index 0a966b0c17071..d1e536e0a4424 100644 --- a/src/librustc_const_eval/pattern.rs +++ b/src/librustc_const_eval/pattern.rs @@ -26,7 +26,7 @@ use syntax::ptr::P; use syntax_pos::Span; #[derive(Clone, Debug)] -pub enum PatternError<'tcx> { +pub(crate) enum PatternError<'tcx> { StaticInPattern(Span), ConstEval(ConstEvalErr<'tcx>), } @@ -266,10 +266,10 @@ impl<'tcx> fmt::Display for Pattern<'tcx> { } } -pub struct PatternContext<'a, 'gcx: 'tcx, 'tcx: 'a> { - pub tcx: TyCtxt<'a, 'gcx, 'tcx>, - pub tables: &'a ty::TypeckTables<'gcx>, - pub errors: Vec>, +pub(crate) struct PatternContext<'a, 'gcx: 'tcx, 'tcx: 'a> { + pub(crate) tcx: TyCtxt<'a, 'gcx, 'tcx>, + pub(crate) tables: &'a ty::TypeckTables<'gcx>, + pub(crate) errors: Vec>, } impl<'a, 'gcx, 'tcx> Pattern<'tcx> { @@ -287,11 +287,11 @@ impl<'a, 'gcx, 'tcx> Pattern<'tcx> { } impl<'a, 'gcx, 'tcx> PatternContext<'a, 'gcx, 'tcx> { - pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>, tables: &'a ty::TypeckTables<'gcx>) -> Self { + pub(crate) fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>, tables: &'a ty::TypeckTables<'gcx>) -> Self { PatternContext { tcx: tcx, tables: tables, errors: vec![] } } - pub fn lower_pattern(&mut self, pat: &hir::Pat) -> Pattern<'tcx> { + pub(crate) fn lower_pattern(&mut self, pat: &hir::Pat) -> Pattern<'tcx> { let mut ty = self.tables.node_id_to_type(pat.id); let kind = match pat.node { @@ -750,7 +750,7 @@ impl<'a, 'gcx, 'tcx> PatternContext<'a, 'gcx, 'tcx> { } } -pub trait PatternFoldable<'tcx> : Sized { +pub(crate) trait PatternFoldable<'tcx> : Sized { fn fold_with>(&self, folder: &mut F) -> Self { self.super_fold_with(folder) } @@ -758,7 +758,7 @@ pub trait PatternFoldable<'tcx> : Sized { fn super_fold_with>(&self, folder: &mut F) -> Self; } -pub trait PatternFolder<'tcx> : Sized { +pub(crate) trait PatternFolder<'tcx> : Sized { fn fold_pattern(&mut self, pattern: &Pattern<'tcx>) -> Pattern<'tcx> { pattern.super_fold_with(self) } diff --git a/src/librustc_const_math/float.rs b/src/librustc_const_math/float.rs index f557edffbda46..34b685bcba0fa 100644 --- a/src/librustc_const_math/float.rs +++ b/src/librustc_const_math/float.rs @@ -30,13 +30,6 @@ impl ConstFloat { } } - pub fn is_nan(&self) -> bool { - match *self { - F32(f) => f.is_nan(), - F64(f) => f.is_nan(), - } - } - /// Compares the values if they are of the same type pub fn try_cmp(self, rhs: Self) -> Result { match (self, rhs) { diff --git a/src/librustc_const_math/int.rs b/src/librustc_const_math/int.rs index d97276da9bf34..eecc5fe6d3004 100644 --- a/src/librustc_const_math/int.rs +++ b/src/librustc_const_math/int.rs @@ -37,14 +37,14 @@ pub use self::ConstInt::*; macro_rules! bounds { ($ct: ty, $($t:ident $min:ident $max:ident)*) => { $( - pub const $min: $ct = $t::min_value() as $ct; - pub const $max: $ct = $t::max_value() as $ct; + pub(crate) const $min: $ct = $t::min_value() as $ct; + pub(crate) const $max: $ct = $t::max_value() as $ct; )* }; ($ct: ty: $min_val: expr, $($t:ident $min:ident $max:ident)*) => { $( - pub const $min: $ct = $min_val; - pub const $max: $ct = $t::max_value() as $ct; + pub(crate) const $min: $ct = $min_val; + pub(crate) const $max: $ct = $t::max_value() as $ct; )* } } @@ -63,8 +63,8 @@ mod ibounds { #![allow(dead_code)] bounds!(i128, u64 U64MIN U64MAX); - pub const U128MIN: i128 = 0; - pub const U128MAX: i128 = i128::max_value(); + pub(crate) const U128MIN: i128 = 0; + pub(crate) const U128MAX: i128 = i128::max_value(); bounds!{i128, i8 I8MIN I8MAX i16 I16MIN I16MAX i32 I32MIN I32MAX i64 I64MIN I64MAX i128 I128MIN I128MAX @@ -171,7 +171,7 @@ impl ConstInt { } /// Converts the value to a `u32` if it's in the range 0...std::u32::MAX - pub fn to_u32(&self) -> Option { + pub(crate) fn to_u32(&self) -> Option { self.to_u128().and_then(|v| if v <= u32::max_value() as u128 { Some(v as u32) } else { @@ -189,7 +189,7 @@ impl ConstInt { } /// Converts the value to a `u128` if it's in the range 0...std::u128::MAX - pub fn to_u128(&self) -> Option { + pub(crate) fn to_u128(&self) -> Option { match *self { I8(v) if v >= 0 => Some(v as u128), I16(v) if v >= 0 => Some(v as u128), diff --git a/src/librustc_data_structures/bitslice.rs b/src/librustc_data_structures/bitslice.rs index ba53578e57918..abdb3ca4e59ad 100644 --- a/src/librustc_data_structures/bitslice.rs +++ b/src/librustc_data_structures/bitslice.rs @@ -12,7 +12,7 @@ use std::mem; -pub type Word = usize; +pub(crate) type Word = usize; /// `BitSlice` provides helper methods for treating a `[Word]` /// as a bitvector. @@ -132,11 +132,11 @@ pub trait BitwiseOperator { fn join(&self, pred1: usize, pred2: usize) -> usize; } -pub struct Union; +pub(crate) struct Union; impl BitwiseOperator for Union { fn join(&self, a: usize, b: usize) -> usize { a | b } } -pub struct Subtract; +pub(crate) struct Subtract; impl BitwiseOperator for Subtract { fn join(&self, a: usize, b: usize) -> usize { a & !b } } diff --git a/src/librustc_data_structures/bitvec.rs b/src/librustc_data_structures/bitvec.rs index ffcd25a4cdd39..0907b8fc9dce3 100644 --- a/src/librustc_data_structures/bitvec.rs +++ b/src/librustc_data_structures/bitvec.rs @@ -139,14 +139,14 @@ impl FromIterator for BitVector { /// one gigantic bitvector. In other words, it is as if you have /// `rows` bitvectors, each of length `columns`. #[derive(Clone)] -pub struct BitMatrix { +pub(crate) struct BitMatrix { columns: usize, vector: Vec, } impl BitMatrix { // Create a new `rows x columns` matrix, initially empty. - pub fn new(rows: usize, columns: usize) -> BitMatrix { + pub(crate) fn new(rows: usize, columns: usize) -> BitMatrix { // For every element, we need one bit for every other // element. Round up to an even number of u64s. let u64s_per_row = u64s(columns); @@ -163,7 +163,7 @@ impl BitMatrix { (start, start + u64s_per_row) } - pub fn add(&mut self, source: usize, target: usize) -> bool { + pub(crate) fn add(&mut self, source: usize, target: usize) -> bool { let (start, _) = self.range(source); let (word, mask) = word_mask(target); let mut vector = &mut self.vector[..]; @@ -177,7 +177,7 @@ impl BitMatrix { /// /// Put another way, if the matrix represents (transitive) /// reachability, can `source` reach `target`? - pub fn contains(&self, source: usize, target: usize) -> bool { + pub(crate) fn contains(&self, source: usize, target: usize) -> bool { let (start, _) = self.range(source); let (word, mask) = word_mask(target); (self.vector[start + word] & mask) != 0 @@ -187,7 +187,7 @@ impl BitMatrix { /// `b`. This is an O(n) operation where `n` is the number of /// elements (somewhat independent from the actual size of the /// intersection, in particular). - pub fn intersection(&self, a: usize, b: usize) -> Vec { + pub(crate) fn intersection(&self, a: usize, b: usize) -> Vec { let (a_start, a_end) = self.range(a); let (b_start, b_end) = self.range(b); let mut result = Vec::with_capacity(self.columns); @@ -213,7 +213,7 @@ impl BitMatrix { /// you have an edge `write -> read`, because in that case /// `write` can reach everything that `read` can (and /// potentially more). - pub fn merge(&mut self, read: usize, write: usize) -> bool { + pub(crate) fn merge(&mut self, read: usize, write: usize) -> bool { let (read_start, read_end) = self.range(read); let (write_start, write_end) = self.range(write); let vector = &mut self.vector[..]; @@ -227,7 +227,7 @@ impl BitMatrix { changed } - pub fn iter<'a>(&'a self, row: usize) -> BitVectorIter<'a> { + pub(crate) fn iter<'a>(&'a self, row: usize) -> BitVectorIter<'a> { let (start, end) = self.range(row); BitVectorIter { iter: self.vector[start..end].iter(), diff --git a/src/librustc_data_structures/blake2b.rs b/src/librustc_data_structures/blake2b.rs index bdef9fefd41e4..365eeee433965 100644 --- a/src/librustc_data_structures/blake2b.rs +++ b/src/librustc_data_structures/blake2b.rs @@ -23,7 +23,7 @@ use std::mem; use std::slice; -pub struct Blake2bCtx { +struct Blake2bCtx { b: [u8; 128], h: [u64; 8], t: [u64; 2], diff --git a/src/librustc_data_structures/control_flow_graph/dominators/mod.rs b/src/librustc_data_structures/control_flow_graph/dominators/mod.rs index ab675db21503e..64d988d431fea 100644 --- a/src/librustc_data_structures/control_flow_graph/dominators/mod.rs +++ b/src/librustc_data_structures/control_flow_graph/dominators/mod.rs @@ -29,9 +29,9 @@ pub fn dominators(graph: &G) -> Dominators { dominators_given_rpo(graph, &rpo) } -pub fn dominators_given_rpo(graph: &G, - rpo: &[G::Node]) - -> Dominators { +pub(crate) fn dominators_given_rpo(graph: &G, + rpo: &[G::Node]) + -> Dominators { let start_node = graph.start_node(); assert_eq!(rpo[0], start_node); @@ -112,16 +112,16 @@ pub struct Dominators { } impl Dominators { - pub fn is_reachable(&self, node: Node) -> bool { + pub(crate) fn is_reachable(&self, node: Node) -> bool { self.immediate_dominators[node].is_some() } - pub fn immediate_dominator(&self, node: Node) -> Node { + pub(crate) fn immediate_dominator(&self, node: Node) -> Node { assert!(self.is_reachable(node), "node {:?} is not reachable", node); self.immediate_dominators[node].unwrap() } - pub fn dominators(&self, node: Node) -> Iter { + pub(crate) fn dominators(&self, node: Node) -> Iter { assert!(self.is_reachable(node), "node {:?} is not reachable", node); Iter { dominators: self, @@ -134,59 +134,13 @@ impl Dominators { self.dominators(node).any(|n| n == dom) } - pub fn mutual_dominator_node(&self, node1: Node, node2: Node) -> Node { - assert!(self.is_reachable(node1), - "node {:?} is not reachable", - node1); - assert!(self.is_reachable(node2), - "node {:?} is not reachable", - node2); - intersect::(&self.post_order_rank, - &self.immediate_dominators, - node1, - node2) - } - - pub fn mutual_dominator(&self, iter: I) -> Option - where I: IntoIterator - { - let mut iter = iter.into_iter(); - iter.next() - .map(|dom| iter.fold(dom, |dom, node| self.mutual_dominator_node(dom, node))) - } - - pub fn all_immediate_dominators(&self) -> &IndexVec> { + #[cfg(test)] + fn all_immediate_dominators(&self) -> &IndexVec> { &self.immediate_dominators } - - pub fn dominator_tree(&self) -> DominatorTree { - let elem: Vec = Vec::new(); - let mut children: IndexVec> = - IndexVec::from_elem_n(elem, self.immediate_dominators.len()); - let mut root = None; - for (index, immed_dom) in self.immediate_dominators.iter().enumerate() { - let node = Node::new(index); - match *immed_dom { - None => { - // node not reachable - } - Some(immed_dom) => { - if node == immed_dom { - root = Some(node); - } else { - children[immed_dom].push(node); - } - } - } - } - DominatorTree { - root: root.unwrap(), - children: children, - } - } } -pub struct Iter<'dom, Node: Idx + 'dom> { +pub(crate) struct Iter<'dom, Node: Idx + 'dom> { dominators: &'dom Dominators, node: Option, } @@ -209,44 +163,15 @@ impl<'dom, Node: Idx> Iterator for Iter<'dom, Node> { } } -pub struct DominatorTree { +pub(crate) struct DominatorTree { root: N, children: IndexVec>, } impl DominatorTree { - pub fn root(&self) -> Node { - self.root - } - - pub fn children(&self, node: Node) -> &[Node] { + pub(crate) fn children(&self, node: Node) -> &[Node] { &self.children[node] } - - pub fn iter_children_of(&self, node: Node) -> IterChildrenOf { - IterChildrenOf { - tree: self, - stack: vec![node], - } - } -} - -pub struct IterChildrenOf<'iter, Node: Idx + 'iter> { - tree: &'iter DominatorTree, - stack: Vec, -} - -impl<'iter, Node: Idx> Iterator for IterChildrenOf<'iter, Node> { - type Item = Node; - - fn next(&mut self) -> Option { - if let Some(node) = self.stack.pop() { - self.stack.extend(self.tree.children(node)); - Some(node) - } else { - None - } - } } impl fmt::Debug for DominatorTree { diff --git a/src/librustc_data_structures/control_flow_graph/iterate/mod.rs b/src/librustc_data_structures/control_flow_graph/iterate/mod.rs index 11b557cbcadb9..3cc4272db681f 100644 --- a/src/librustc_data_structures/control_flow_graph/iterate/mod.rs +++ b/src/librustc_data_structures/control_flow_graph/iterate/mod.rs @@ -14,14 +14,14 @@ use super::super::indexed_vec::IndexVec; #[cfg(test)] mod test; -pub fn post_order_from(graph: &G, start_node: G::Node) -> Vec { +pub(crate) fn post_order_from(graph: &G, start_node: G::Node) -> Vec { post_order_from_to(graph, start_node, None) } -pub fn post_order_from_to(graph: &G, - start_node: G::Node, - end_node: Option) - -> Vec { +pub(crate) fn post_order_from_to(graph: &G, + start_node: G::Node, + end_node: Option) + -> Vec { let mut visited: IndexVec = IndexVec::from_elem_n(false, graph.num_nodes()); let mut result: Vec = Vec::with_capacity(graph.num_nodes()); if let Some(end_node) = end_node { @@ -47,23 +47,8 @@ fn post_order_walk(graph: &G, result.push(node); } -pub fn pre_order_walk(graph: &G, - node: G::Node, - result: &mut Vec, - visited: &mut IndexVec) { - if visited[node] { - return; - } - visited[node] = true; - - result.push(node); - - for successor in graph.successors(node) { - pre_order_walk(graph, successor, result, visited); - } -} - -pub fn reverse_post_order(graph: &G, start_node: G::Node) -> Vec { +pub(crate) fn reverse_post_order(graph: &G, start_node: G::Node) + -> Vec { let mut vec = post_order_from(graph, start_node); vec.reverse(); vec diff --git a/src/librustc_data_structures/control_flow_graph/iterate/test.rs b/src/librustc_data_structures/control_flow_graph/iterate/test.rs index dca45602f17c4..100881ddfdd77 100644 --- a/src/librustc_data_structures/control_flow_graph/iterate/test.rs +++ b/src/librustc_data_structures/control_flow_graph/iterate/test.rs @@ -9,7 +9,6 @@ // except according to those terms. use super::super::test::TestGraph; -use super::super::transpose::TransposedGraph; use super::*; @@ -20,22 +19,3 @@ fn diamond_post_order() { let result = post_order_from(&graph, 0); assert_eq!(result, vec![3, 1, 2, 0]); } - - -#[test] -fn rev_post_order_inner_loop() { - // 0 -> 1 -> 2 -> 3 -> 5 - // ^ ^ v | - // | 6 <- 4 | - // +-----------------+ - let graph = TestGraph::new(0, - &[(0, 1), (1, 2), (2, 3), (3, 5), (3, 1), (2, 4), (4, 6), (6, 2)]); - - let rev_graph = TransposedGraph::new(&graph); - - let result = post_order_from_to(&rev_graph, 6, Some(2)); - assert_eq!(result, vec![4, 6]); - - let result = post_order_from_to(&rev_graph, 3, Some(1)); - assert_eq!(result, vec![4, 6, 2, 3]); -} diff --git a/src/librustc_data_structures/control_flow_graph/mod.rs b/src/librustc_data_structures/control_flow_graph/mod.rs index eb6839df6274f..16d91ff5d4643 100644 --- a/src/librustc_data_structures/control_flow_graph/mod.rs +++ b/src/librustc_data_structures/control_flow_graph/mod.rs @@ -9,13 +9,10 @@ // except according to those terms. use super::indexed_vec::Idx; -pub use std::slice::Iter; pub mod dominators; -pub mod iterate; -pub mod reachable; +pub(crate) mod iterate; mod reference; -pub mod transpose; #[cfg(test)] mod test; diff --git a/src/librustc_data_structures/control_flow_graph/reachable/mod.rs b/src/librustc_data_structures/control_flow_graph/reachable/mod.rs deleted file mode 100644 index 24210ebb95d3d..0000000000000 --- a/src/librustc_data_structures/control_flow_graph/reachable/mod.rs +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2016 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Compute reachability using a simple dataflow propagation. -//! Store end-result in a big NxN bit matrix. - -use super::ControlFlowGraph; -use super::super::bitvec::BitVector; -use super::iterate::reverse_post_order; -use super::super::indexed_vec::{IndexVec, Idx}; - -#[cfg(test)] -mod test; - -pub fn reachable(graph: &G) -> Reachability { - let reverse_post_order = reverse_post_order(graph, graph.start_node()); - reachable_given_rpo(graph, &reverse_post_order) -} - -pub fn reachable_given_rpo(graph: &G, - reverse_post_order: &[G::Node]) - -> Reachability { - let mut reachability = Reachability::new(graph); - let mut changed = true; - while changed { - changed = false; - for &node in reverse_post_order.iter().rev() { - // every node can reach itself - changed |= reachability.bits[node].insert(node.index()); - - // and every pred can reach everything node can reach - for pred in graph.predecessors(node) { - let nodes_bits = reachability.bits[node].clone(); - changed |= reachability.bits[pred].insert_all(&nodes_bits); - } - } - } - reachability -} - -pub struct Reachability { - bits: IndexVec, -} - -impl Reachability { - fn new(graph: &G) -> Self { - let num_nodes = graph.num_nodes(); - Reachability { bits: IndexVec::from_elem_n(BitVector::new(num_nodes), num_nodes) } - } - - pub fn can_reach(&self, source: Node, target: Node) -> bool { - let bit: usize = target.index(); - self.bits[source].contains(bit) - } -} diff --git a/src/librustc_data_structures/control_flow_graph/reachable/test.rs b/src/librustc_data_structures/control_flow_graph/reachable/test.rs deleted file mode 100644 index ef45deeaafc78..0000000000000 --- a/src/librustc_data_structures/control_flow_graph/reachable/test.rs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2016 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use super::super::test::TestGraph; - -use super::*; - -#[test] -fn test1() { - // 0 -> 1 -> 2 -> 3 - // ^ v - // 6 <- 4 -> 5 - let graph = TestGraph::new(0, &[(0, 1), (1, 2), (2, 3), (2, 4), (4, 5), (4, 6), (6, 1)]); - let reachable = reachable(&graph); - assert!((0..6).all(|i| reachable.can_reach(0, i))); - assert!((1..6).all(|i| reachable.can_reach(1, i))); - assert!((1..6).all(|i| reachable.can_reach(2, i))); - assert!((1..6).all(|i| reachable.can_reach(4, i))); - assert!((1..6).all(|i| reachable.can_reach(6, i))); - assert!(reachable.can_reach(3, 3)); - assert!(!reachable.can_reach(3, 5)); - assert!(!reachable.can_reach(5, 3)); -} - -/// use bigger indices to cross between words in the bit set -#[test] -fn test2() { - // 30 -> 31 -> 32 -> 33 - // ^ v - // 36 <- 34 -> 35 - let graph = TestGraph::new(30, - &[(30, 31), (31, 32), (32, 33), (32, 34), (34, 35), (34, 36), - (36, 31)]); - let reachable = reachable(&graph); - assert!((30..36).all(|i| reachable.can_reach(30, i))); - assert!((31..36).all(|i| reachable.can_reach(31, i))); - assert!((31..36).all(|i| reachable.can_reach(32, i))); - assert!((31..36).all(|i| reachable.can_reach(34, i))); - assert!((31..36).all(|i| reachable.can_reach(36, i))); - assert!(reachable.can_reach(33, 33)); - assert!(!reachable.can_reach(33, 35)); - assert!(!reachable.can_reach(35, 33)); -} diff --git a/src/librustc_data_structures/control_flow_graph/test.rs b/src/librustc_data_structures/control_flow_graph/test.rs index d48a6e684ad8e..a45ea3e7f2297 100644 --- a/src/librustc_data_structures/control_flow_graph/test.rs +++ b/src/librustc_data_structures/control_flow_graph/test.rs @@ -15,7 +15,7 @@ use std::iter; use super::{ControlFlowGraph, GraphPredecessors, GraphSuccessors}; -pub struct TestGraph { +pub(crate) struct TestGraph { num_nodes: usize, start_node: usize, successors: HashMap>, @@ -23,7 +23,7 @@ pub struct TestGraph { } impl TestGraph { - pub fn new(start_node: usize, edges: &[(usize, usize)]) -> Self { + pub(crate) fn new(start_node: usize, edges: &[(usize, usize)]) -> Self { let mut graph = TestGraph { num_nodes: start_node + 1, start_node: start_node, diff --git a/src/librustc_data_structures/control_flow_graph/transpose.rs b/src/librustc_data_structures/control_flow_graph/transpose.rs deleted file mode 100644 index a1a117edb94fc..0000000000000 --- a/src/librustc_data_structures/control_flow_graph/transpose.rs +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2016 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use super::*; - -pub struct TransposedGraph { - base_graph: G, - start_node: G::Node, -} - -impl TransposedGraph { - pub fn new(base_graph: G) -> Self { - let start_node = base_graph.start_node(); - Self::with_start(base_graph, start_node) - } - - pub fn with_start(base_graph: G, start_node: G::Node) -> Self { - TransposedGraph { - base_graph: base_graph, - start_node: start_node, - } - } -} - -impl ControlFlowGraph for TransposedGraph { - type Node = G::Node; - - fn num_nodes(&self) -> usize { - self.base_graph.num_nodes() - } - - fn start_node(&self) -> Self::Node { - self.start_node - } - - fn predecessors<'graph>(&'graph self, - node: Self::Node) - -> >::Iter { - self.base_graph.successors(node) - } - - fn successors<'graph>(&'graph self, - node: Self::Node) - -> >::Iter { - self.base_graph.predecessors(node) - } -} - -impl<'graph, G: ControlFlowGraph> GraphPredecessors<'graph> for TransposedGraph { - type Item = G::Node; - type Iter = >::Iter; -} - -impl<'graph, G: ControlFlowGraph> GraphSuccessors<'graph> for TransposedGraph { - type Item = G::Node; - type Iter = >::Iter; -} diff --git a/src/librustc_data_structures/flock.rs b/src/librustc_data_structures/flock.rs index ff1ebb11b7221..00caf5bdcb072 100644 --- a/src/librustc_data_structures/flock.rs +++ b/src/librustc_data_structures/flock.rs @@ -32,22 +32,22 @@ mod imp { use libc; #[repr(C)] - pub struct flock { - pub l_type: libc::c_short, - pub l_whence: libc::c_short, - pub l_start: libc::off_t, - pub l_len: libc::off_t, - pub l_pid: libc::pid_t, + pub(super) struct flock { + pub(super) l_type: libc::c_short, + pub(super) l_whence: libc::c_short, + pub(super) l_start: libc::off_t, + pub(super) l_len: libc::off_t, + pub(super) l_pid: libc::pid_t, // not actually here, but brings in line with freebsd - pub l_sysid: libc::c_int, + pub(super) l_sysid: libc::c_int, } - pub const F_RDLCK: libc::c_short = 0; - pub const F_WRLCK: libc::c_short = 1; - pub const F_UNLCK: libc::c_short = 2; - pub const F_SETLK: libc::c_int = 6; - pub const F_SETLKW: libc::c_int = 7; + pub(super) const F_RDLCK: libc::c_short = 0; + pub(super) const F_WRLCK: libc::c_short = 1; + pub(super) const F_UNLCK: libc::c_short = 2; + pub(super) const F_SETLK: libc::c_int = 6; + pub(super) const F_SETLKW: libc::c_int = 7; } #[cfg(target_os = "freebsd")] @@ -55,20 +55,20 @@ mod imp { use libc; #[repr(C)] - pub struct flock { - pub l_start: libc::off_t, - pub l_len: libc::off_t, - pub l_pid: libc::pid_t, - pub l_type: libc::c_short, - pub l_whence: libc::c_short, - pub l_sysid: libc::c_int, + pub(super) struct flock { + pub(super) l_start: libc::off_t, + pub(super) l_len: libc::off_t, + pub(super) l_pid: libc::pid_t, + pub(super) l_type: libc::c_short, + pub(super) l_whence: libc::c_short, + pub(super) l_sysid: libc::c_int, } - pub const F_RDLCK: libc::c_short = 1; - pub const F_UNLCK: libc::c_short = 2; - pub const F_WRLCK: libc::c_short = 3; - pub const F_SETLK: libc::c_int = 12; - pub const F_SETLKW: libc::c_int = 13; + pub(super) const F_RDLCK: libc::c_short = 1; + pub(super) const F_UNLCK: libc::c_short = 2; + pub(super) const F_WRLCK: libc::c_short = 3; + pub(super) const F_SETLK: libc::c_int = 12; + pub(super) const F_SETLKW: libc::c_int = 13; } #[cfg(any(target_os = "dragonfly", @@ -79,22 +79,22 @@ mod imp { use libc; #[repr(C)] - pub struct flock { - pub l_start: libc::off_t, - pub l_len: libc::off_t, - pub l_pid: libc::pid_t, - pub l_type: libc::c_short, - pub l_whence: libc::c_short, + pub(super) struct flock { + pub(super) l_start: libc::off_t, + pub(super) l_len: libc::off_t, + pub(super) l_pid: libc::pid_t, + pub(super) l_type: libc::c_short, + pub(super) l_whence: libc::c_short, // not actually here, but brings in line with freebsd - pub l_sysid: libc::c_int, + pub(super) l_sysid: libc::c_int, } - pub const F_RDLCK: libc::c_short = 1; - pub const F_UNLCK: libc::c_short = 2; - pub const F_WRLCK: libc::c_short = 3; - pub const F_SETLK: libc::c_int = 8; - pub const F_SETLKW: libc::c_int = 9; + pub(super) const F_RDLCK: libc::c_short = 1; + pub(super) const F_UNLCK: libc::c_short = 2; + pub(super) const F_WRLCK: libc::c_short = 3; + pub(super) const F_SETLK: libc::c_int = 8; + pub(super) const F_SETLKW: libc::c_int = 9; } #[cfg(target_os = "haiku")] @@ -102,22 +102,22 @@ mod imp { use libc; #[repr(C)] - pub struct flock { - pub l_type: libc::c_short, - pub l_whence: libc::c_short, - pub l_start: libc::off_t, - pub l_len: libc::off_t, - pub l_pid: libc::pid_t, + pub(super) struct flock { + pub(super) l_type: libc::c_short, + pub(super) l_whence: libc::c_short, + pub(super) l_start: libc::off_t, + pub(super) l_len: libc::off_t, + pub(super) l_pid: libc::pid_t, // not actually here, but brings in line with freebsd - pub l_sysid: libc::c_int, + pub(super) l_sysid: libc::c_int, } - pub const F_RDLCK: libc::c_short = 0x0040; - pub const F_UNLCK: libc::c_short = 0x0200; - pub const F_WRLCK: libc::c_short = 0x0400; - pub const F_SETLK: libc::c_int = 0x0080; - pub const F_SETLKW: libc::c_int = 0x0100; + pub(super) const F_RDLCK: libc::c_short = 0x0040; + pub(super) const F_UNLCK: libc::c_short = 0x0200; + pub(super) const F_WRLCK: libc::c_short = 0x0400; + pub(super) const F_SETLK: libc::c_int = 0x0080; + pub(super) const F_SETLKW: libc::c_int = 0x0100; } #[cfg(any(target_os = "macos", target_os = "ios"))] @@ -125,22 +125,22 @@ mod imp { use libc; #[repr(C)] - pub struct flock { - pub l_start: libc::off_t, - pub l_len: libc::off_t, - pub l_pid: libc::pid_t, - pub l_type: libc::c_short, - pub l_whence: libc::c_short, + pub(super) struct flock { + pub(super) l_start: libc::off_t, + pub(super) l_len: libc::off_t, + pub(super) l_pid: libc::pid_t, + pub(super) l_type: libc::c_short, + pub(super) l_whence: libc::c_short, // not actually here, but brings in line with freebsd - pub l_sysid: libc::c_int, + pub(super) l_sysid: libc::c_int, } - pub const F_RDLCK: libc::c_short = 1; - pub const F_UNLCK: libc::c_short = 2; - pub const F_WRLCK: libc::c_short = 3; - pub const F_SETLK: libc::c_int = 8; - pub const F_SETLKW: libc::c_int = 9; + pub(super) const F_RDLCK: libc::c_short = 1; + pub(super) const F_UNLCK: libc::c_short = 2; + pub(super) const F_WRLCK: libc::c_short = 3; + pub(super) const F_SETLK: libc::c_int = 8; + pub(super) const F_SETLKW: libc::c_int = 9; } #[cfg(target_os = "solaris")] @@ -148,20 +148,20 @@ mod imp { use libc; #[repr(C)] - pub struct flock { - pub l_type: libc::c_short, - pub l_whence: libc::c_short, - pub l_start: libc::off_t, - pub l_len: libc::off_t, - pub l_sysid: libc::c_int, - pub l_pid: libc::pid_t, + pub(super) struct flock { + pub(super) l_type: libc::c_short, + pub(super) l_whence: libc::c_short, + pub(super) l_start: libc::off_t, + pub(super) l_len: libc::off_t, + pub(super) l_sysid: libc::c_int, + pub(super) l_pid: libc::pid_t, } - pub const F_RDLCK: libc::c_short = 1; - pub const F_WRLCK: libc::c_short = 2; - pub const F_UNLCK: libc::c_short = 3; - pub const F_SETLK: libc::c_int = 6; - pub const F_SETLKW: libc::c_int = 7; + pub(super) const F_RDLCK: libc::c_short = 1; + pub(super) const F_WRLCK: libc::c_short = 2; + pub(super) const F_UNLCK: libc::c_short = 3; + pub(super) const F_SETLK: libc::c_int = 6; + pub(super) const F_SETLKW: libc::c_int = 7; } #[derive(Debug)] diff --git a/src/librustc_data_structures/fmt_wrap.rs b/src/librustc_data_structures/fmt_wrap.rs deleted file mode 100644 index 50fd1d802b7ff..0000000000000 --- a/src/librustc_data_structures/fmt_wrap.rs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2016 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::fmt; - -// Provide some more formatting options for some data types (at the moment -// that's just `{:x}` for slices of u8). - -pub struct FmtWrap(pub T); - -impl<'a> fmt::LowerHex for FmtWrap<&'a [u8]> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - for byte in self.0.iter() { - try!(write!(formatter, "{:02x}", byte)); - } - Ok(()) - } -} - -#[test] -fn test_lower_hex() { - let bytes: &[u8] = &[0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]; - assert_eq!("0123456789abcdef", &format!("{:x}", FmtWrap(bytes))); -} diff --git a/src/librustc_data_structures/fnv.rs b/src/librustc_data_structures/fnv.rs deleted file mode 100644 index 5bd57236e7c28..0000000000000 --- a/src/librustc_data_structures/fnv.rs +++ /dev/null @@ -1,66 +0,0 @@ -// 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::collections::{HashMap, HashSet}; -use std::default::Default; -use std::hash::{Hasher, Hash, BuildHasherDefault}; - -pub type FnvHashMap = HashMap>; -pub type FnvHashSet = HashSet>; - -#[allow(non_snake_case)] -pub fn FnvHashMap() -> FnvHashMap { - HashMap::default() -} - -#[allow(non_snake_case)] -pub fn FnvHashSet() -> FnvHashSet { - HashSet::default() -} - -/// A speedy hash algorithm for node ids and def ids. The hashmap in -/// liballoc by default uses SipHash which isn't quite as speedy as we -/// want. In the compiler we're not really worried about DOS attempts, so we -/// just default to a non-cryptographic hash. -/// -/// This uses FNV hashing, as described here: -/// http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function -pub struct FnvHasher(u64); - -impl Default for FnvHasher { - /// Creates a `FnvHasher`, with a 64-bit hex initial value. - #[inline] - fn default() -> FnvHasher { - FnvHasher(0xcbf29ce484222325) - } -} - -impl Hasher for FnvHasher { - #[inline] - fn write(&mut self, bytes: &[u8]) { - let FnvHasher(mut hash) = *self; - for byte in bytes { - hash = hash ^ (*byte as u64); - hash = hash.wrapping_mul(0x100000001b3); - } - *self = FnvHasher(hash); - } - - #[inline] - fn finish(&self) -> u64 { - self.0 - } -} - -pub fn hash(v: &T) -> u64 { - let mut state = FnvHasher::default(); - v.hash(&mut state); - state.finish() -} diff --git a/src/librustc_data_structures/fx.rs b/src/librustc_data_structures/fx.rs index 00dfc1617a8b6..5bf25437763cc 100644 --- a/src/librustc_data_structures/fx.rs +++ b/src/librustc_data_structures/fx.rs @@ -107,9 +107,3 @@ impl Hasher for FxHasher { self.hash as u64 } } - -pub fn hash(v: &T) -> u64 { - let mut state = FxHasher::default(); - v.hash(&mut state); - state.finish() -} diff --git a/src/librustc_data_structures/graph/mod.rs b/src/librustc_data_structures/graph/mod.rs index f94ed6b720946..dab8606b93e3e 100644 --- a/src/librustc_data_structures/graph/mod.rs +++ b/src/librustc_data_structures/graph/mod.rs @@ -85,9 +85,9 @@ impl Debug for Edge { pub struct NodeIndex(pub usize); #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] -pub struct EdgeIndex(pub usize); +pub struct EdgeIndex(pub(crate) usize); -pub const INVALID_EDGE_INDEX: EdgeIndex = EdgeIndex(usize::MAX); +pub(crate) const INVALID_EDGE_INDEX: EdgeIndex = EdgeIndex(usize::MAX); // Use a private field here to guarantee no more instances are created: #[derive(Copy, Clone, Debug, PartialEq)] @@ -106,13 +106,6 @@ impl NodeIndex { } } -impl EdgeIndex { - /// Returns unique id (unique with respect to the graph holding associated edge). - pub fn edge_id(&self) -> usize { - self.0 - } -} - impl Graph { pub fn new() -> Graph { Graph { @@ -201,43 +194,19 @@ impl Graph { return idx; } - pub fn mut_edge_data(&mut self, idx: EdgeIndex) -> &mut E { - &mut self.edges[idx.0].data - } - - pub fn edge_data(&self, idx: EdgeIndex) -> &E { - &self.edges[idx.0].data - } - pub fn edge(&self, idx: EdgeIndex) -> &Edge { &self.edges[idx.0] } - pub fn first_adjacent(&self, node: NodeIndex, dir: Direction) -> EdgeIndex { - //! Accesses the index of the first edge adjacent to `node`. - //! This is useful if you wish to modify the graph while walking - //! the linked list of edges. - - self.nodes[node.0].first_edge[dir.repr] - } - - pub fn next_adjacent(&self, edge: EdgeIndex, dir: Direction) -> EdgeIndex { - //! Accesses the next edge in a given direction. - //! This is useful if you wish to modify the graph while walking - //! the linked list of edges. - - self.edges[edge.0].next_edge[dir.repr] - } - // # Iterating over nodes, edges - pub fn enumerated_nodes(&self) -> EnumeratedNodes { + pub(crate) fn enumerated_nodes(&self) -> EnumeratedNodes { EnumeratedNodes { iter: self.nodes.iter().enumerate() } } - pub fn enumerated_edges(&self) -> EnumeratedEdges { + pub(crate) fn enumerated_edges(&self) -> EnumeratedEdges { EnumeratedEdges { iter: self.edges.iter().enumerate() } @@ -282,65 +251,17 @@ impl Graph { self.incoming_edges(target).sources() } - /// A common use for graphs in our compiler is to perform - /// fixed-point iteration. In this case, each edge represents a - /// constraint, and the nodes themselves are associated with - /// variables or other bitsets. This method facilitates such a - /// computation. - pub fn iterate_until_fixed_point<'a, F>(&'a self, mut op: F) - where F: FnMut(usize, EdgeIndex, &'a Edge) -> bool - { - let mut iteration = 0; - let mut changed = true; - while changed { - changed = false; - iteration += 1; - for (edge_index, edge) in self.enumerated_edges() { - changed |= op(iteration, edge_index, edge); - } - } - } - pub fn depth_traverse<'a>(&'a self, start: NodeIndex, direction: Direction) -> DepthFirstTraversal<'a, N, E> { DepthFirstTraversal::with_start_node(self, start, direction) } - - /// Whether or not a node can be reached from itself. - pub fn is_node_cyclic(&self, starting_node_index: NodeIndex) -> bool { - // This is similar to depth traversal below, but we - // can't use that, because depth traversal doesn't show - // the starting node a second time. - let mut visited = BitVector::new(self.len_nodes()); - let mut stack = vec![starting_node_index]; - - while let Some(current_node_index) = stack.pop() { - visited.insert(current_node_index.0); - - // Directionality doesn't change the answer, - // so just use outgoing edges. - for (_, edge) in self.outgoing_edges(current_node_index) { - let target_node_index = edge.target(); - - if target_node_index == starting_node_index { - return true; - } - - if !visited.contains(target_node_index.0) { - stack.push(target_node_index); - } - } - } - - false - } } // # Iterators -pub struct EnumeratedNodes<'g, N> +pub(crate) struct EnumeratedNodes<'g, N> where N: 'g, { iter: ::std::iter::Enumerate<::std::slice::Iter<'g, Node>> @@ -354,7 +275,7 @@ impl<'g, N: Debug> Iterator for EnumeratedNodes<'g, N> { } } -pub struct EnumeratedEdges<'g, E> +pub(crate) struct EnumeratedEdges<'g, E> where E: 'g, { iter: ::std::iter::Enumerate<::std::slice::Iter<'g, Edge>> @@ -443,20 +364,10 @@ pub struct DepthFirstTraversal<'g, N, E> } impl<'g, N: Debug, E: Debug> DepthFirstTraversal<'g, N, E> { - pub fn new(graph: &'g Graph, direction: Direction) -> Self { - let visited = BitVector::new(graph.len_nodes()); - DepthFirstTraversal { - graph: graph, - stack: vec![], - visited: visited, - direction: direction, - } - } - - pub fn with_start_node(graph: &'g Graph, - start_node: NodeIndex, - direction: Direction) - -> Self { + pub(crate) fn with_start_node(graph: &'g Graph, + start_node: NodeIndex, + direction: Direction) + -> Self { let mut visited = BitVector::new(graph.len_nodes()); visited.insert(start_node.node_id()); DepthFirstTraversal { @@ -467,13 +378,6 @@ impl<'g, N: Debug, E: Debug> DepthFirstTraversal<'g, N, E> { } } - pub fn reset(&mut self, start_node: NodeIndex) { - self.stack.truncate(0); - self.stack.push(start_node); - self.visited.clear(); - self.visited.insert(start_node.node_id()); - } - fn visit(&mut self, node: NodeIndex) { if self.visited.insert(node.node_id()) { self.stack.push(node); @@ -496,19 +400,6 @@ impl<'g, N: Debug, E: Debug> Iterator for DepthFirstTraversal<'g, N, E> { } } -pub fn each_edge_index(max_edge_index: EdgeIndex, mut f: F) - where F: FnMut(EdgeIndex) -> bool -{ - let mut i = 0; - let n = max_edge_index.0; - while i < n { - if !f(EdgeIndex(i)) { - return; - } - i += 1; - } -} - impl Edge { pub fn source(&self) -> NodeIndex { self.source diff --git a/src/librustc_data_structures/graph/tests.rs b/src/librustc_data_structures/graph/tests.rs index bdefc39a61a85..007704357af4f 100644 --- a/src/librustc_data_structures/graph/tests.rs +++ b/src/librustc_data_structures/graph/tests.rs @@ -43,29 +43,6 @@ fn create_graph() -> TestGraph { return graph; } -fn create_graph_with_cycle() -> TestGraph { - let mut graph = Graph::new(); - - // Create a graph with a cycle. - // - // A --> B <-- + - // | | - // v | - // C --> D - - let a = graph.add_node("A"); - let b = graph.add_node("B"); - let c = graph.add_node("C"); - let d = graph.add_node("D"); - - graph.add_edge(a, b, "AB"); - graph.add_edge(b, c, "BC"); - graph.add_edge(c, d, "CD"); - graph.add_edge(d, b, "DB"); - - return graph; -} - #[test] fn each_node() { let graph = create_graph(); @@ -82,7 +59,6 @@ fn each_edge() { let graph = create_graph(); let expected = ["AB", "BC", "BD", "DE", "EC", "FB"]; graph.each_edge(|idx, edge| { - assert_eq!(&expected[idx.0], graph.edge_data(idx)); assert_eq!(expected[idx.0], edge.data); true }); @@ -97,7 +73,6 @@ fn test_adjacent_edges(graph: &Graph let mut counter = 0; for (edge_index, edge) in graph.incoming_edges(start_index) { - assert!(graph.edge_data(edge_index) == &edge.data); assert!(counter < expected_incoming.len()); debug!("counter={:?} expected={:?} edge_index={:?} edge={:?}", counter, @@ -117,7 +92,6 @@ fn test_adjacent_edges(graph: &Graph let mut counter = 0; for (edge_index, edge) in graph.outgoing_edges(start_index) { - assert!(graph.edge_data(edge_index) == &edge.data); assert!(counter < expected_outgoing.len()); debug!("counter={:?} expected={:?} edge_index={:?} edge={:?}", counter, @@ -163,15 +137,3 @@ fn each_adjacent_from_d() { let graph = create_graph(); test_adjacent_edges(&graph, NodeIndex(3), "D", &[("BD", "B")], &[("DE", "E")]); } - -#[test] -fn is_node_cyclic_a() { - let graph = create_graph_with_cycle(); - assert!(!graph.is_node_cyclic(NodeIndex(0))); -} - -#[test] -fn is_node_cyclic_b() { - let graph = create_graph_with_cycle(); - assert!(graph.is_node_cyclic(NodeIndex(1))); -} diff --git a/src/librustc_data_structures/ivar.rs b/src/librustc_data_structures/ivar.rs deleted file mode 100644 index f842f4a41a118..0000000000000 --- a/src/librustc_data_structures/ivar.rs +++ /dev/null @@ -1,71 +0,0 @@ -// 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::fmt; -use std::cell::Cell; - -/// A write-once variable. When constructed, it is empty, and -/// can only be set once. -/// -/// Ivars ensure that data that can only be initialised once. A full -/// implementation is used for concurrency and blocks on a read of an -/// unfulfilled value. This implementation is more minimal and panics -/// if you attempt to read the value before it has been set. It is also -/// not `Sync`, but may be extended in the future to be usable as a true -/// concurrency type. -/// -/// The `T: Copy` bound is not strictly needed, but it is required by -/// Cell (so removing it would require using UnsafeCell), and it -/// suffices for the current purposes. -#[derive(PartialEq)] -pub struct Ivar { - data: Cell>, -} - -impl Ivar { - pub fn new() -> Ivar { - Ivar { data: Cell::new(None) } - } - - pub fn get(&self) -> Option { - self.data.get() - } - - pub fn fulfill(&self, value: T) { - assert!(self.data.get().is_none(), "Value already set!"); - self.data.set(Some(value)); - } - - pub fn is_fulfilled(&self) -> bool { - self.data.get().is_some() - } - - pub fn unwrap(&self) -> T { - self.get().unwrap() - } -} - -impl fmt::Debug for Ivar { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self.get() { - Some(val) => write!(f, "Ivar({:?})", val), - None => f.write_str("Ivar()"), - } - } -} - -impl Clone for Ivar { - fn clone(&self) -> Ivar { - match self.get() { - Some(val) => Ivar { data: Cell::new(Some(val)) }, - None => Ivar::new(), - } - } -} diff --git a/src/librustc_data_structures/lib.rs b/src/librustc_data_structures/lib.rs index 5d856597cad53..be790b8bc7848 100644 --- a/src/librustc_data_structures/lib.rs +++ b/src/librustc_data_structures/lib.rs @@ -56,11 +56,9 @@ pub mod accumulate_vec; pub mod small_vec; pub mod base_n; pub mod bitslice; -pub mod blake2b; pub mod bitvec; -pub mod fmt_wrap; +pub mod blake2b; pub mod graph; -pub mod ivar; pub mod indexed_set; pub mod indexed_vec; pub mod obligation_forest; @@ -69,7 +67,6 @@ pub mod snapshot_vec; pub mod stable_hasher; pub mod transitive_relation; pub mod unify; -pub mod fnv; pub mod fx; pub mod tuple_slice; pub mod veccell; diff --git a/src/librustc_data_structures/obligation_forest/mod.rs b/src/librustc_data_structures/obligation_forest/mod.rs index 3515e5c5ede35..44bc7af70de44 100644 --- a/src/librustc_data_structures/obligation_forest/mod.rs +++ b/src/librustc_data_structures/obligation_forest/mod.rs @@ -57,11 +57,6 @@ pub trait ObligationProcessor { where I: Clone + Iterator; } -struct SnapshotData { - node_len: usize, - cache_list_len: usize, -} - pub struct ObligationForest { /// The list of obligations. In between calls to /// `process_obligations`, this list only contains nodes in the @@ -83,14 +78,9 @@ pub struct ObligationForest { /// A list of the obligations added in snapshots, to allow /// for their removal. cache_list: Vec, - snapshots: Vec, scratch: Option>, } -pub struct Snapshot { - len: usize, -} - #[derive(Debug)] struct Node { obligation: O, @@ -166,7 +156,6 @@ impl ObligationForest { pub fn new() -> ObligationForest { ObligationForest { nodes: vec![], - snapshots: vec![], done_cache: FxHashSet(), waiting_cache: FxHashMap(), cache_list: vec![], @@ -180,39 +169,6 @@ impl ObligationForest { self.nodes.len() } - pub fn start_snapshot(&mut self) -> Snapshot { - self.snapshots.push(SnapshotData { - node_len: self.nodes.len(), - cache_list_len: self.cache_list.len() - }); - Snapshot { len: self.snapshots.len() } - } - - pub fn commit_snapshot(&mut self, snapshot: Snapshot) { - assert_eq!(snapshot.len, self.snapshots.len()); - let info = self.snapshots.pop().unwrap(); - assert!(self.nodes.len() >= info.node_len); - assert!(self.cache_list.len() >= info.cache_list_len); - } - - pub fn rollback_snapshot(&mut self, snapshot: Snapshot) { - // Check that we are obeying stack discipline. - assert_eq!(snapshot.len, self.snapshots.len()); - let info = self.snapshots.pop().unwrap(); - - for entry in &self.cache_list[info.cache_list_len..] { - self.done_cache.remove(entry); - self.waiting_cache.remove(entry); - } - - self.nodes.truncate(info.node_len); - self.cache_list.truncate(info.cache_list_len); - } - - pub fn in_snapshot(&self) -> bool { - !self.snapshots.is_empty() - } - /// Registers an obligation /// /// This CAN be done in a snapshot @@ -262,7 +218,6 @@ impl ObligationForest { /// /// This cannot be done during a snapshot. pub fn to_errors(&mut self, error: E) -> Vec> { - assert!(!self.in_snapshot()); let mut errors = vec![]; for index in 0..self.nodes.len() { if let NodeState::Pending = self.nodes[index].state.get() { @@ -297,7 +252,6 @@ impl ObligationForest { where P: ObligationProcessor { debug!("process_obligations(len={})", self.nodes.len()); - assert!(!self.in_snapshot()); // cannot unroll this action let mut errors = vec![]; let mut stalled = true; @@ -528,8 +482,6 @@ impl ObligationForest { /// on these nodes may be present. This is done by e.g. `process_cycles`. #[inline(never)] fn compress(&mut self) -> Vec { - assert!(!self.in_snapshot()); // didn't write code to unroll this action - let nodes_len = self.nodes.len(); let mut node_rewrites: Vec<_> = self.scratch.take().unwrap(); node_rewrites.extend(0..nodes_len); diff --git a/src/librustc_data_structures/obligation_forest/node_index.rs b/src/librustc_data_structures/obligation_forest/node_index.rs index 023c56ca59be8..519d9ddadc326 100644 --- a/src/librustc_data_structures/obligation_forest/node_index.rs +++ b/src/librustc_data_structures/obligation_forest/node_index.rs @@ -12,17 +12,17 @@ use core::nonzero::NonZero; use std::u32; #[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub struct NodeIndex { +pub(crate) struct NodeIndex { index: NonZero, } impl NodeIndex { - pub fn new(value: usize) -> NodeIndex { + pub(crate) fn new(value: usize) -> NodeIndex { assert!(value < (u32::MAX as usize)); unsafe { NodeIndex { index: NonZero::new((value as u32) + 1) } } } - pub fn get(self) -> usize { + pub(crate) fn get(self) -> usize { (self.index.get() - 1) as usize } } diff --git a/src/librustc_data_structures/transitive_relation.rs b/src/librustc_data_structures/transitive_relation.rs index 46463944043bd..07c4504c4a059 100644 --- a/src/librustc_data_structures/transitive_relation.rs +++ b/src/librustc_data_structures/transitive_relation.rs @@ -208,7 +208,7 @@ impl TransitiveRelation { /// internal indices). /// /// Note that this set can, in principle, have any size. - pub fn minimal_upper_bounds(&self, a: &T, b: &T) -> Vec<&T> { + pub(crate) fn minimal_upper_bounds(&self, a: &T, b: &T) -> Vec<&T> { let (mut a, mut b) = match (self.index(a), self.index(b)) { (Some(a), Some(b)) => (a, b), (None, _) | (_, None) => { diff --git a/src/librustc_data_structures/tuple_slice.rs b/src/librustc_data_structures/tuple_slice.rs index b7c71dd366469..ebbb66be4abc4 100644 --- a/src/librustc_data_structures/tuple_slice.rs +++ b/src/librustc_data_structures/tuple_slice.rs @@ -11,7 +11,7 @@ use std::slice; /// Allows to view uniform tuples as slices -pub trait TupleSlice { +pub(crate) trait TupleSlice { fn as_slice(&self) -> &[T]; fn as_mut_slice(&mut self) -> &mut [T]; } diff --git a/src/librustc_data_structures/unify/mod.rs b/src/librustc_data_structures/unify/mod.rs index e2d3a4f453749..952d2f70bcfa7 100644 --- a/src/librustc_data_structures/unify/mod.rs +++ b/src/librustc_data_structures/unify/mod.rs @@ -56,7 +56,7 @@ impl Combine for () { /// time of the algorithm under control. For more information, see /// . #[derive(PartialEq,Clone,Debug)] -pub struct VarValue { +pub(crate) struct VarValue { parent: K, // if equal to self, this is a root value: K::Value, // value assigned (only relevant to root) rank: u32, // max depth (only relevant to root) @@ -275,7 +275,8 @@ impl<'tcx, K: UnifyKey> UnificationTable self.get(id).value } - pub fn unioned(&mut self, a_id: K, b_id: K) -> bool { + #[cfg(test)] + fn unioned(&mut self, a_id: K, b_id: K) -> bool { self.find(a_id) == self.find(b_id) } } diff --git a/src/librustc_driver/derive_registrar.rs b/src/librustc_driver/derive_registrar.rs index 9983efce6af0b..0e5dc47c5b7dd 100644 --- a/src/librustc_driver/derive_registrar.rs +++ b/src/librustc_driver/derive_registrar.rs @@ -14,7 +14,7 @@ use rustc::hir; use syntax::ast; use syntax::attr; -pub fn find(hir_map: &Map) -> Option { +pub(crate) fn find(hir_map: &Map) -> Option { let krate = hir_map.krate(); let mut finder = Finder { registrar: None }; diff --git a/src/librustc_driver/driver.rs b/src/librustc_driver/driver.rs index 7faf78ce638ba..cf9c87b13799f 100644 --- a/src/librustc_driver/driver.rs +++ b/src/librustc_driver/driver.rs @@ -104,8 +104,7 @@ pub fn compile_input(sess: &Session, sess, outdir, output, - krate, - &cstore); + krate); controller_entry_point!(after_parse, sess, compile_state, @@ -121,7 +120,7 @@ pub fn compile_input(sess: &Session, sess, &cstore, krate, registry, &crate_name, addl_plugins, control.make_glob_map, |expanded_crate| { let mut state = CompileState::state_after_expand( - input, sess, outdir, output, &cstore, expanded_crate, &crate_name, + input, sess, outdir, output, expanded_crate, &crate_name, ); controller_entry_point!(after_expand, sess, state, Ok(())); Ok(()) @@ -153,7 +152,6 @@ pub fn compile_input(sess: &Session, output, &arena, &arenas, - &cstore, &hir_map, &analysis, &resolutions, @@ -346,9 +344,7 @@ pub struct CompileState<'a, 'tcx: 'a> { pub session: &'tcx Session, pub krate: Option, pub registry: Option>, - pub cstore: Option<&'a CStore>, pub crate_name: Option<&'a str>, - pub output_filenames: Option<&'a OutputFilenames>, pub out_dir: Option<&'a Path>, pub out_file: Option<&'a Path>, pub arena: Option<&'tcx DroplessArena>, @@ -376,9 +372,7 @@ impl<'a, 'tcx> CompileState<'a, 'tcx> { arenas: None, krate: None, registry: None, - cstore: None, crate_name: None, - output_filenames: None, expanded_crate: None, hir_crate: None, hir_map: None, @@ -393,14 +387,12 @@ impl<'a, 'tcx> CompileState<'a, 'tcx> { session: &'tcx Session, out_dir: &'a Option, out_file: &'a Option, - krate: ast::Crate, - cstore: &'a CStore) + krate: ast::Crate) -> Self { CompileState { // Initialize the registry before moving `krate` registry: Some(Registry::new(&session, krate.span)), krate: Some(krate), - cstore: Some(cstore), out_file: out_file.as_ref().map(|s| &**s), ..CompileState::empty(input, session, out_dir) } @@ -410,13 +402,11 @@ impl<'a, 'tcx> CompileState<'a, 'tcx> { session: &'tcx Session, out_dir: &'a Option, out_file: &'a Option, - cstore: &'a CStore, expanded_crate: &'a ast::Crate, crate_name: &'a str) -> Self { CompileState { crate_name: Some(crate_name), - cstore: Some(cstore), expanded_crate: Some(expanded_crate), out_file: out_file.as_ref().map(|s| &**s), ..CompileState::empty(input, session, out_dir) @@ -429,7 +419,6 @@ impl<'a, 'tcx> CompileState<'a, 'tcx> { out_file: &'a Option, arena: &'tcx DroplessArena, arenas: &'tcx GlobalArenas<'tcx>, - cstore: &'a CStore, hir_map: &'a hir_map::Map<'tcx>, analysis: &'a ty::CrateAnalysis, resolutions: &'a Resolutions, @@ -441,7 +430,6 @@ impl<'a, 'tcx> CompileState<'a, 'tcx> { crate_name: Some(crate_name), arena: Some(arena), arenas: Some(arenas), - cstore: Some(cstore), hir_map: Some(hir_map), analysis: Some(analysis), resolutions: Some(resolutions), @@ -1200,7 +1188,8 @@ fn write_out_deps(sess: &Session, outputs: &OutputFilenames, crate_name: &str) { } } -pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec { +pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) + -> Vec { // Unconditionally collect crate types from attributes to make them used let attr_types: Vec = attrs.iter() diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index 1f9f6aad90536..b1ec20e3f34c8 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -102,10 +102,10 @@ use syntax::parse::{self, PResult}; use syntax_pos::{DUMMY_SP, MultiSpan}; #[cfg(test)] -pub mod test; +mod test; pub mod driver; -pub mod pretty; +mod pretty; pub mod target_features; mod derive_registrar; @@ -759,17 +759,17 @@ impl RustcDefaultCalls { } /// Returns a version string such as "0.12.0-dev". -pub fn release_str() -> Option<&'static str> { +fn release_str() -> Option<&'static str> { option_env!("CFG_RELEASE") } /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built. -pub fn commit_hash_str() -> Option<&'static str> { +fn commit_hash_str() -> Option<&'static str> { option_env!("CFG_VER_HASH") } /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string. -pub fn commit_date_str() -> Option<&'static str> { +fn commit_date_str() -> Option<&'static str> { option_env!("CFG_VER_DATE") } diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index 269363fdd2f98..d44c71ade0184 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -10,9 +10,9 @@ //! The various pretty print routines. -pub use self::UserIdentifiedItem::*; -pub use self::PpSourceMode::*; -pub use self::PpMode::*; +pub(crate) use self::UserIdentifiedItem::*; +pub(crate) use self::PpSourceMode::*; +pub(crate) use self::PpMode::*; use self::NodesMatchingUII::*; use {abort_on_err, driver}; @@ -53,7 +53,7 @@ use rustc::hir::print as pprust_hir; use arena::DroplessArena; #[derive(Copy, Clone, PartialEq, Debug)] -pub enum PpSourceMode { +pub(crate) enum PpSourceMode { PpmNormal, PpmEveryBodyLoops, PpmExpanded, @@ -64,7 +64,7 @@ pub enum PpSourceMode { } #[derive(Copy, Clone, PartialEq, Debug)] -pub enum PpFlowGraphMode { +pub(crate) enum PpFlowGraphMode { Default, /// Drops the labels from the edges in the flowgraph output. This /// is mostly for use in the --unpretty flowgraph run-make tests, @@ -73,7 +73,7 @@ pub enum PpFlowGraphMode { UnlabelledEdges, } #[derive(Copy, Clone, PartialEq, Debug)] -pub enum PpMode { +pub(crate) enum PpMode { PpmSource(PpSourceMode), PpmHir(PpSourceMode), PpmFlowGraph(PpFlowGraphMode), @@ -82,7 +82,7 @@ pub enum PpMode { } impl PpMode { - pub fn needs_ast_map(&self, opt_uii: &Option) -> bool { + pub(crate) fn needs_ast_map(&self, opt_uii: &Option) -> bool { match *self { PpmSource(PpmNormal) | PpmSource(PpmEveryBodyLoops) | @@ -99,7 +99,7 @@ impl PpMode { } } - pub fn needs_analysis(&self) -> bool { + pub(crate) fn needs_analysis(&self) -> bool { match *self { PpmMir | PpmMirCFG | PpmFlowGraph(_) => true, _ => false, @@ -107,10 +107,10 @@ impl PpMode { } } -pub fn parse_pretty(sess: &Session, - name: &str, - extended: bool) - -> (PpMode, Option) { +pub(crate) fn parse_pretty(sess: &Session, + name: &str, + extended: bool) + -> (PpMode, Option) { let mut split = name.splitn(2, '='); let first = split.next().unwrap(); let opt_second = split.next(); @@ -542,7 +542,7 @@ fn gather_flowgraph_variants(sess: &Session) -> Vec { } #[derive(Clone, Debug)] -pub enum UserIdentifiedItem { +pub(crate) enum UserIdentifiedItem { ItemViaNode(ast::NodeId), ItemViaPath(Vec), } @@ -773,7 +773,7 @@ fn print_flowgraph<'a, 'tcx, W: Write>(variants: Vec, } } -pub fn fold_crate(krate: ast::Crate, ppm: PpMode) -> ast::Crate { +pub(crate) fn fold_crate(krate: ast::Crate, ppm: PpMode) -> ast::Crate { if let PpmSource(PpmEveryBodyLoops) = ppm { let mut fold = ReplaceBodyWithLoop::new(); fold.fold_crate(krate) @@ -807,11 +807,11 @@ fn write_output(out: Vec, ofile: Option<&Path>) { } } -pub fn print_after_parsing(sess: &Session, - input: &Input, - krate: &ast::Crate, - ppm: PpMode, - ofile: Option<&Path>) { +pub(crate) fn print_after_parsing(sess: &Session, + input: &Input, + krate: &ast::Crate, + ppm: PpMode, + ofile: Option<&Path>) { let dep_graph = DepGraph::new(false); let _ignore = dep_graph.in_ignore(); @@ -843,18 +843,18 @@ pub fn print_after_parsing(sess: &Session, write_output(out, ofile); } -pub fn print_after_hir_lowering<'tcx, 'a: 'tcx>(sess: &'a Session, - hir_map: &hir_map::Map<'tcx>, - analysis: &ty::CrateAnalysis, - resolutions: &Resolutions, - input: &Input, - krate: &ast::Crate, - crate_name: &str, - ppm: PpMode, - arena: &'tcx DroplessArena, - arenas: &'tcx GlobalArenas<'tcx>, - opt_uii: Option, - ofile: Option<&Path>) { +pub(crate) fn print_after_hir_lowering<'tcx, 'a: 'tcx>(sess: &'a Session, + hir_map: &hir_map::Map<'tcx>, + analysis: &ty::CrateAnalysis, + resolutions: &Resolutions, + input: &Input, + krate: &ast::Crate, + crate_name: &str, + ppm: PpMode, + arena: &'tcx DroplessArena, + arenas: &'tcx GlobalArenas<'tcx>, + opt_uii: Option, + ofile: Option<&Path>) { let dep_graph = DepGraph::new(false); let _ignore = dep_graph.in_ignore(); diff --git a/src/librustc_driver/test.rs b/src/librustc_driver/test.rs index 62e20a90f8a08..f3f61f84f5a8c 100644 --- a/src/librustc_driver/test.rs +++ b/src/librustc_driver/test.rs @@ -170,11 +170,11 @@ fn test_env(source_string: &str, } impl<'a, 'gcx, 'tcx> Env<'a, 'gcx, 'tcx> { - pub fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> { + pub(crate) fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> { self.infcx.tcx } - pub fn create_region_hierarchy(&mut self, rh: &RH, parent: CodeExtent) { + pub(crate) fn create_region_hierarchy(&mut self, rh: &RH, parent: CodeExtent) { let me = CodeExtent::Misc(rh.id); self.region_maps.record_code_extent(me, Some(parent)); for child_rh in rh.sub { @@ -182,7 +182,7 @@ impl<'a, 'gcx, 'tcx> Env<'a, 'gcx, 'tcx> { } } - pub fn create_simple_region_hierarchy(&mut self) { + pub(crate) fn create_simple_region_hierarchy(&mut self) { // creates a region hierarchy where 1 is root, 10 and 11 are // children of 1, etc @@ -204,7 +204,7 @@ impl<'a, 'gcx, 'tcx> Env<'a, 'gcx, 'tcx> { } #[allow(dead_code)] // this seems like it could be useful, even if we don't use it now - pub fn lookup_item(&self, names: &[String]) -> ast::NodeId { + pub(crate) fn lookup_item(&self, names: &[String]) -> ast::NodeId { return match search_mod(self, &self.infcx.tcx.hir.krate().module, 0, names) { Some(id) => id, None => { @@ -254,29 +254,29 @@ impl<'a, 'gcx, 'tcx> Env<'a, 'gcx, 'tcx> { } } - pub fn make_subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool { + pub(crate) fn make_subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool { match self.infcx.at(&ObligationCause::dummy(), self.param_env).sub(a, b) { Ok(_) => true, Err(ref e) => panic!("Encountered error: {}", e), } } - pub fn is_subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool { + pub(crate) fn is_subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool { self.infcx.can_sub(self.param_env, a, b).is_ok() } - pub fn assert_subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) { + pub(crate) fn assert_subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) { if !self.is_subtype(a, b) { panic!("{} is not a subtype of {}, but it should be", a, b); } } - pub fn assert_eq(&self, a: Ty<'tcx>, b: Ty<'tcx>) { + pub(crate) fn assert_eq(&self, a: Ty<'tcx>, b: Ty<'tcx>) { self.assert_subtype(a, b); self.assert_subtype(b, a); } - pub fn t_fn(&self, input_tys: &[Ty<'tcx>], output_ty: Ty<'tcx>) -> Ty<'tcx> { + pub(crate) fn t_fn(&self, input_tys: &[Ty<'tcx>], output_ty: Ty<'tcx>) -> Ty<'tcx> { self.infcx.tcx.mk_fn_ptr(ty::Binder(self.infcx.tcx.mk_fn_sig( input_tys.iter().cloned(), output_ty, @@ -286,20 +286,20 @@ impl<'a, 'gcx, 'tcx> Env<'a, 'gcx, 'tcx> { ))) } - pub fn t_nil(&self) -> Ty<'tcx> { + pub(crate) fn t_nil(&self) -> Ty<'tcx> { self.infcx.tcx.mk_nil() } - pub fn t_pair(&self, ty1: Ty<'tcx>, ty2: Ty<'tcx>) -> Ty<'tcx> { + pub(crate) fn t_pair(&self, ty1: Ty<'tcx>, ty2: Ty<'tcx>) -> Ty<'tcx> { self.infcx.tcx.intern_tup(&[ty1, ty2], false) } - pub fn t_param(&self, index: u32) -> Ty<'tcx> { + pub(crate) fn t_param(&self, index: u32) -> Ty<'tcx> { let name = format!("T{}", index); self.infcx.tcx.mk_param(index, Symbol::intern(&name)) } - pub fn re_early_bound(&self, index: u32, name: &'static str) -> ty::Region<'tcx> { + pub(crate) fn re_early_bound(&self, index: u32, name: &'static str) -> ty::Region<'tcx> { let name = Symbol::intern(name); self.infcx.tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: self.infcx.tcx.hir.local_def_id(ast::CRATE_NODE_ID), @@ -308,72 +308,72 @@ impl<'a, 'gcx, 'tcx> Env<'a, 'gcx, 'tcx> { })) } - pub fn re_late_bound_with_debruijn(&self, - id: u32, - debruijn: ty::DebruijnIndex) - -> ty::Region<'tcx> { + pub(crate) fn re_late_bound_with_debruijn(&self, + id: u32, + debruijn: ty::DebruijnIndex) + -> ty::Region<'tcx> { self.infcx.tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(id))) } - pub fn t_rptr(&self, r: ty::Region<'tcx>) -> Ty<'tcx> { + pub(crate) fn t_rptr(&self, r: ty::Region<'tcx>) -> Ty<'tcx> { self.infcx.tcx.mk_imm_ref(r, self.tcx().types.isize) } - pub fn t_rptr_late_bound(&self, id: u32) -> Ty<'tcx> { + pub(crate) fn t_rptr_late_bound(&self, id: u32) -> Ty<'tcx> { let r = self.re_late_bound_with_debruijn(id, ty::DebruijnIndex::new(1)); self.infcx.tcx.mk_imm_ref(r, self.tcx().types.isize) } - pub fn t_rptr_late_bound_with_debruijn(&self, - id: u32, - debruijn: ty::DebruijnIndex) - -> Ty<'tcx> { + pub(crate) fn t_rptr_late_bound_with_debruijn(&self, + id: u32, + debruijn: ty::DebruijnIndex) + -> Ty<'tcx> { let r = self.re_late_bound_with_debruijn(id, debruijn); self.infcx.tcx.mk_imm_ref(r, self.tcx().types.isize) } - pub fn t_rptr_scope(&self, id: u32) -> Ty<'tcx> { + pub(crate) fn t_rptr_scope(&self, id: u32) -> Ty<'tcx> { let r = ty::ReScope(CodeExtent::Misc(ast::NodeId::from_u32(id))); self.infcx.tcx.mk_imm_ref(self.infcx.tcx.mk_region(r), self.tcx().types.isize) } - pub fn re_free(&self, id: u32) -> ty::Region<'tcx> { + pub(crate) fn re_free(&self, id: u32) -> ty::Region<'tcx> { self.infcx.tcx.mk_region(ty::ReFree(ty::FreeRegion { scope: self.infcx.tcx.hir.local_def_id(ast::CRATE_NODE_ID), bound_region: ty::BrAnon(id), })) } - pub fn t_rptr_free(&self, id: u32) -> Ty<'tcx> { + pub(crate) fn t_rptr_free(&self, id: u32) -> Ty<'tcx> { let r = self.re_free(id); self.infcx.tcx.mk_imm_ref(r, self.tcx().types.isize) } - pub fn t_rptr_static(&self) -> Ty<'tcx> { + pub(crate) fn t_rptr_static(&self) -> Ty<'tcx> { self.infcx.tcx.mk_imm_ref(self.infcx.tcx.types.re_static, self.tcx().types.isize) } - pub fn t_rptr_empty(&self) -> Ty<'tcx> { + pub(crate) fn t_rptr_empty(&self) -> Ty<'tcx> { self.infcx.tcx.mk_imm_ref(self.infcx.tcx.types.re_empty, self.tcx().types.isize) } - pub fn sub(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> InferResult<'tcx, ()> { + pub(crate) fn sub(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> InferResult<'tcx, ()> { self.infcx.at(&ObligationCause::dummy(), self.param_env).sub(t1, t2) } - pub fn lub(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> { + pub(crate) fn lub(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> { self.infcx.at(&ObligationCause::dummy(), self.param_env).lub(t1, t2) } - pub fn glb(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> { + pub(crate) fn glb(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> { self.infcx.at(&ObligationCause::dummy(), self.param_env).glb(t1, t2) } /// Checks that `t1 <: t2` is true (this may register additional /// region checks). - pub fn check_sub(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) { + pub(crate) fn check_sub(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) { match self.sub(t1, t2) { Ok(InferOk { obligations, value: () }) => { // None of these tests should require nested obligations: @@ -387,7 +387,7 @@ impl<'a, 'gcx, 'tcx> Env<'a, 'gcx, 'tcx> { /// Checks that `t1 <: t2` is false (this may register additional /// region checks). - pub fn check_not_sub(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) { + pub(crate) fn check_not_sub(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) { match self.sub(t1, t2) { Err(_) => {} Ok(_) => { @@ -397,7 +397,7 @@ impl<'a, 'gcx, 'tcx> Env<'a, 'gcx, 'tcx> { } /// Checks that `LUB(t1,t2) == t_lub` - pub fn check_lub(&self, t1: Ty<'tcx>, t2: Ty<'tcx>, t_lub: Ty<'tcx>) { + pub(crate) fn check_lub(&self, t1: Ty<'tcx>, t2: Ty<'tcx>, t_lub: Ty<'tcx>) { match self.lub(t1, t2) { Ok(InferOk { obligations, value: t }) => { // None of these tests should require nested obligations: @@ -410,7 +410,7 @@ impl<'a, 'gcx, 'tcx> Env<'a, 'gcx, 'tcx> { } /// Checks that `GLB(t1,t2) == t_glb` - pub fn check_glb(&self, t1: Ty<'tcx>, t2: Ty<'tcx>, t_glb: Ty<'tcx>) { + pub(crate) fn check_glb(&self, t1: Ty<'tcx>, t2: Ty<'tcx>, t_glb: Ty<'tcx>) { debug!("check_glb(t1={}, t2={}, t_glb={})", t1, t2, t_glb); match self.glb(t1, t2) { Err(e) => panic!("unexpected error computing LUB: {:?}", e), diff --git a/src/librustc_errors/diagnostic.rs b/src/librustc_errors/diagnostic.rs index ee07b6e909f7d..f056784b8cf5d 100644 --- a/src/librustc_errors/diagnostic.rs +++ b/src/librustc_errors/diagnostic.rs @@ -105,10 +105,6 @@ impl Diagnostic { self.level == Level::Cancelled } - pub fn is_fatal(&self) -> bool { - self.level == Level::Fatal - } - /// Add a span/label to be included in the resulting snippet. /// This is pushed onto the `MultiSpan` that was created when the /// diagnostic was first built. If you don't call this function at @@ -189,9 +185,9 @@ impl Diagnostic { } pub fn span_warn>(&mut self, - sp: S, - msg: &str) - -> &mut Self { + sp: S, + msg: &str) + -> &mut Self { self.sub(Level::Warning, msg, sp.into(), None); self } @@ -202,9 +198,9 @@ impl Diagnostic { } pub fn span_help>(&mut self, - sp: S, - msg: &str) - -> &mut Self { + sp: S, + msg: &str) + -> &mut Self { self.sub(Level::Help, msg, sp.into(), None); self } @@ -235,7 +231,8 @@ impl Diagnostic { self } - pub fn span_suggestions(&mut self, sp: Span, msg: &str, suggestions: Vec) -> &mut Self { + pub fn span_suggestions(&mut self, sp: Span, msg: &str, suggestions: Vec) + -> &mut Self { self.suggestions.push(CodeSuggestion { substitution_parts: vec![Substitution { span: sp, @@ -260,18 +257,10 @@ impl Diagnostic { self.message.iter().map(|i| i.0.to_owned()).collect::() } - pub fn set_message(&mut self, message: &str) { - self.message = vec![(message.to_owned(), Style::NoStyle)]; - } - pub fn styled_message(&self) -> &Vec<(String, Style)> { &self.message } - pub fn level(&self) -> Level { - self.level - } - /// Used by a lint. Copies over all details *but* the "main /// message". pub fn copy_details_not_message(&mut self, from: &Diagnostic) { diff --git a/src/librustc_errors/diagnostic_builder.rs b/src/librustc_errors/diagnostic_builder.rs index 0081339a363f7..8a08d4ca35125 100644 --- a/src/librustc_errors/diagnostic_builder.rs +++ b/src/librustc_errors/diagnostic_builder.rs @@ -161,29 +161,22 @@ impl<'a> DiagnosticBuilder<'a> { /// Convenience function for internal use, clients should use one of the /// struct_* methods on Handler. - pub fn new(handler: &'a Handler, level: Level, message: &str) -> DiagnosticBuilder<'a> { + pub(crate) fn new(handler: &'a Handler, level: Level, message: &str) -> DiagnosticBuilder<'a> { DiagnosticBuilder::new_with_code(handler, level, None, message) } /// Convenience function for internal use, clients should use one of the /// struct_* methods on Handler. - pub fn new_with_code(handler: &'a Handler, - level: Level, - code: Option, - message: &str) - -> DiagnosticBuilder<'a> { + pub(crate) fn new_with_code(handler: &'a Handler, + level: Level, + code: Option, + message: &str) + -> DiagnosticBuilder<'a> { DiagnosticBuilder { handler: handler, diagnostic: Diagnostic::new_with_code(level, code, message) } } - - pub fn into_diagnostic(mut self) -> Diagnostic { - // annoyingly, the Drop impl means we can't actually move - let result = self.diagnostic.clone(); - self.cancel(); - result - } } impl<'a> Debug for DiagnosticBuilder<'a> { diff --git a/src/librustc_errors/emitter.rs b/src/librustc_errors/emitter.rs index ad2562e28fa4f..96f35bf45180f 100644 --- a/src/librustc_errors/emitter.rs +++ b/src/librustc_errors/emitter.rs @@ -80,11 +80,11 @@ impl Emitter for EmitterWriter { } /// maximum number of lines we will print for each error; arbitrary. -pub const MAX_HIGHLIGHT_LINES: usize = 6; +pub(crate) const MAX_HIGHLIGHT_LINES: usize = 6; /// maximum number of suggestions to be shown /// /// Arbitrary, but taken from trait import suggestion limit -pub const MAX_SUGGESTIONS: usize = 4; +pub(crate) const MAX_SUGGESTIONS: usize = 4; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ColorConfig { @@ -1311,10 +1311,12 @@ fn stderr_isatty() -> bool { } } -pub type BufferedStderr = term::Terminal + Send; +pub(crate) type BufferedStderr = term::Terminal + Send; -pub enum Destination { +pub(crate) enum Destination { + #[cfg_attr(not(windows), allow(dead_code))] Terminal(Box), + #[cfg_attr(windows, allow(dead_code))] BufferedTerminal(Box), Raw(Box), } @@ -1322,7 +1324,7 @@ pub enum Destination { /// Buffered writer gives us a way on Unix to buffer up an entire error message before we output /// it. This helps to prevent interleaving of multiple error messages when multiple compiler /// processes error simultaneously -pub struct BufferedWriter { +pub(crate) struct BufferedWriter { buffer: Vec, } diff --git a/src/librustc_errors/lib.rs b/src/librustc_errors/lib.rs index c4beb5ebc42df..017c899431e68 100644 --- a/src/librustc_errors/lib.rs +++ b/src/librustc_errors/lib.rs @@ -38,8 +38,8 @@ use std::cell::{RefCell, Cell}; use std::{error, fmt}; use std::rc::Rc; -pub mod diagnostic; -pub mod diagnostic_builder; +mod diagnostic; +mod diagnostic_builder; pub mod emitter; mod snippet; pub mod registry; @@ -110,7 +110,7 @@ impl CodeSuggestion { } /// Returns the number of substitutions - pub fn substitution_spans<'a>(&'a self) -> impl Iterator + 'a { + fn substitution_spans<'a>(&'a self) -> impl Iterator + 'a { self.substitution_parts.iter().map(|sub| sub.span) } @@ -259,7 +259,7 @@ impl error::Error for ExplicitBug { } } -pub use diagnostic::{Diagnostic, SubDiagnostic, DiagnosticStyledString, StringPart}; +pub use diagnostic::{Diagnostic, SubDiagnostic, DiagnosticStyledString}; pub use diagnostic_builder::DiagnosticBuilder; /// A handler deals with errors; certain errors @@ -492,7 +492,7 @@ impl Handler { self.bug(&format!("unimplemented {}", msg)); } - pub fn bump_err_count(&self) { + fn bump_err_count(&self) { self.err_count.set(self.err_count.get() + 1); } @@ -571,7 +571,7 @@ impl fmt::Display for Level { } impl Level { - pub fn color(self) -> term::color::Color { + fn color(self) -> term::color::Color { match self { Bug | Fatal | PhaseFatal | Error => term::color::BRIGHT_RED, Warning => { @@ -598,12 +598,3 @@ impl Level { } } } - -pub fn expect(diag: &Handler, opt: Option, msg: M) -> T - where M: FnOnce() -> String -{ - match opt { - Some(t) => t, - None => diag.bug(&msg()), - } -} diff --git a/src/librustc_errors/lock.rs b/src/librustc_errors/lock.rs index 4c298228c37c7..20a53ebdba8c4 100644 --- a/src/librustc_errors/lock.rs +++ b/src/librustc_errors/lock.rs @@ -23,7 +23,7 @@ use std::any::Any; #[cfg(windows)] #[allow(bad_style)] -pub fn acquire_global_lock(name: &str) -> Box { +pub(crate) fn acquire_global_lock(name: &str) -> Box { use std::ffi::CString; use std::io; @@ -110,6 +110,6 @@ pub fn acquire_global_lock(name: &str) -> Box { } #[cfg(unix)] -pub fn acquire_global_lock(_name: &str) -> Box { +pub(crate) fn acquire_global_lock(_name: &str) -> Box { Box::new(()) } diff --git a/src/librustc_errors/snippet.rs b/src/librustc_errors/snippet.rs index 3c5a6c031e18c..1913d34c7ea82 100644 --- a/src/librustc_errors/snippet.rs +++ b/src/librustc_errors/snippet.rs @@ -22,7 +22,7 @@ pub struct SnippetData { } #[derive(Clone)] -pub struct FileInfo { +pub(crate) struct FileInfo { file: Rc, /// The "primary file", if any, gets a `-->` marker instead of @@ -36,29 +36,29 @@ pub struct FileInfo { } #[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)] -pub struct Line { - pub line_index: usize, - pub annotations: Vec, +pub(crate) struct Line { + pub(crate) line_index: usize, + pub(crate) annotations: Vec, } #[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)] -pub struct MultilineAnnotation { - pub depth: usize, - pub line_start: usize, - pub line_end: usize, - pub start_col: usize, - pub end_col: usize, - pub is_primary: bool, - pub label: Option, +pub(crate) struct MultilineAnnotation { + pub(crate) depth: usize, + pub(crate) line_start: usize, + pub(crate) line_end: usize, + pub(crate) start_col: usize, + pub(crate) end_col: usize, + pub(crate) is_primary: bool, + pub(crate) label: Option, } impl MultilineAnnotation { - pub fn increase_depth(&mut self) { + pub(crate) fn increase_depth(&mut self) { self.depth += 1; } - pub fn as_start(&self) -> Annotation { + pub(crate) fn as_start(&self) -> Annotation { Annotation { start_col: self.start_col, end_col: self.start_col + 1, @@ -68,7 +68,7 @@ impl MultilineAnnotation { } } - pub fn as_end(&self) -> Annotation { + pub(crate) fn as_end(&self) -> Annotation { Annotation { start_col: self.end_col - 1, end_col: self.end_col, @@ -78,7 +78,7 @@ impl MultilineAnnotation { } } - pub fn as_line(&self) -> Annotation { + pub(crate) fn as_line(&self) -> Annotation { Annotation { start_col: 0, end_col: 0, @@ -90,7 +90,7 @@ impl MultilineAnnotation { } #[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)] -pub enum AnnotationType { +pub(crate) enum AnnotationType { /// Annotation under a single line of code Singleline, @@ -119,30 +119,30 @@ pub enum AnnotationType { } #[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)] -pub struct Annotation { +pub(crate) struct Annotation { /// Start column, 0-based indexing -- counting *characters*, not /// utf-8 bytes. Note that it is important that this field goes /// first, so that when we sort, we sort orderings by start /// column. - pub start_col: usize, + pub(crate) start_col: usize, /// End column within the line (exclusive) - pub end_col: usize, + pub(crate) end_col: usize, /// Is this annotation derived from primary span - pub is_primary: bool, + pub(crate) is_primary: bool, /// Optional label to display adjacent to the annotation. - pub label: Option, + pub(crate) label: Option, /// Is this a single line, multiline or multiline span minimized down to a /// smaller span. - pub annotation_type: AnnotationType, + pub(crate) annotation_type: AnnotationType, } impl Annotation { /// Wether this annotation is a vertical line placeholder. - pub fn is_line(&self) -> bool { + pub(crate) fn is_line(&self) -> bool { if let AnnotationType::MultilineLine(_) = self.annotation_type { true } else { @@ -150,7 +150,7 @@ impl Annotation { } } - pub fn is_multiline(&self) -> bool { + pub(crate) fn is_multiline(&self) -> bool { match self.annotation_type { AnnotationType::Multiline(_) | AnnotationType::MultilineStart(_) | @@ -160,7 +160,7 @@ impl Annotation { } } - pub fn len(&self) -> usize { + pub(crate) fn len(&self) -> usize { // Account for usize underflows if self.end_col > self.start_col { self.end_col - self.start_col @@ -169,7 +169,7 @@ impl Annotation { } } - pub fn has_label(&self) -> bool { + pub(crate) fn has_label(&self) -> bool { if let Some(ref label) = self.label { // Consider labels with no text as effectively not being there // to avoid weird output with unnecessary vertical lines, like: @@ -187,7 +187,7 @@ impl Annotation { } } - pub fn takes_space(&self) -> bool { + pub(crate) fn takes_space(&self) -> bool { // Multiline annotations always have to keep vertical space. match self.annotation_type { AnnotationType::MultilineStart(_) | @@ -198,9 +198,9 @@ impl Annotation { } #[derive(Debug)] -pub struct StyledString { - pub text: String, - pub style: Style, +pub(crate) struct StyledString { + pub(crate) text: String, + pub(crate) style: Style, } #[derive(Copy, Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)] diff --git a/src/librustc_errors/styled_buffer.rs b/src/librustc_errors/styled_buffer.rs index f1f2e6c55e977..6b75c4620cdbe 100644 --- a/src/librustc_errors/styled_buffer.rs +++ b/src/librustc_errors/styled_buffer.rs @@ -13,20 +13,20 @@ use snippet::{Style, StyledString}; #[derive(Debug)] -pub struct StyledBuffer { +pub(crate) struct StyledBuffer { text: Vec>, styles: Vec>, } impl StyledBuffer { - pub fn new() -> StyledBuffer { + pub(crate) fn new() -> StyledBuffer { StyledBuffer { text: vec![], styles: vec![], } } - pub fn copy_tabs(&mut self, row: usize) { + pub(crate) fn copy_tabs(&mut self, row: usize) { if row < self.text.len() { for i in row + 1..self.text.len() { for j in 0..self.text[i].len() { @@ -39,7 +39,7 @@ impl StyledBuffer { } } - pub fn render(&mut self) -> Vec> { + pub(crate) fn render(&mut self) -> Vec> { let mut output: Vec> = vec![]; let mut styled_vec: Vec = vec![]; @@ -86,7 +86,7 @@ impl StyledBuffer { } } - pub fn putc(&mut self, line: usize, col: usize, chr: char, style: Style) { + pub(crate) fn putc(&mut self, line: usize, col: usize, chr: char, style: Style) { self.ensure_lines(line); if col < self.text[line].len() { self.text[line][col] = chr; @@ -103,7 +103,7 @@ impl StyledBuffer { } } - pub fn puts(&mut self, line: usize, col: usize, string: &str, style: Style) { + pub(crate) fn puts(&mut self, line: usize, col: usize, string: &str, style: Style) { let mut n = col; for c in string.chars() { self.putc(line, n, c, style); @@ -111,7 +111,7 @@ impl StyledBuffer { } } - pub fn prepend(&mut self, line: usize, string: &str, style: Style) { + pub(crate) fn prepend(&mut self, line: usize, string: &str, style: Style) { self.ensure_lines(line); let string_len = string.len(); @@ -124,7 +124,7 @@ impl StyledBuffer { self.puts(line, 0, string, style); } - pub fn append(&mut self, line: usize, string: &str, style: Style) { + pub(crate) fn append(&mut self, line: usize, string: &str, style: Style) { if line >= self.text.len() { self.puts(line, 0, string, style); } else { @@ -133,7 +133,7 @@ impl StyledBuffer { } } - pub fn num_lines(&self) -> usize { + pub(crate) fn num_lines(&self) -> usize { self.text.len() } } diff --git a/src/librustc_incremental/assert_dep_graph.rs b/src/librustc_incremental/assert_dep_graph.rs index 04192c35ef3ab..533d740ed58df 100644 --- a/src/librustc_incremental/assert_dep_graph.rs +++ b/src/librustc_incremental/assert_dep_graph.rs @@ -264,8 +264,8 @@ fn dump_graph(tcx: TyCtxt) { } } -pub struct GraphvizDepGraph<'q>(FxHashSet<&'q DepNode>, - Vec<(&'q DepNode, &'q DepNode)>); +pub(crate) struct GraphvizDepGraph<'q>(FxHashSet<&'q DepNode>, + Vec<(&'q DepNode, &'q DepNode)>); impl<'a, 'tcx, 'q> dot::GraphWalk<'a> for GraphvizDepGraph<'q> { type Node = &'q DepNode; diff --git a/src/librustc_incremental/calculate_svh/mod.rs b/src/librustc_incremental/calculate_svh/mod.rs index f30a0f553b982..831e3de8b28c6 100644 --- a/src/librustc_incremental/calculate_svh/mod.rs +++ b/src/librustc_incremental/calculate_svh/mod.rs @@ -51,31 +51,27 @@ pub struct IncrementalHashesMap { // -Z query-dep-graph was specified and are needed for auto-tests using // the #[rustc_metadata_dirty] and #[rustc_metadata_clean] attributes to // check whether some metadata hash has changed in between two revisions. - pub prev_metadata_hashes: RefCell>, + pub(crate) prev_metadata_hashes: RefCell>, } impl IncrementalHashesMap { - pub fn new() -> IncrementalHashesMap { + pub(crate) fn new() -> IncrementalHashesMap { IncrementalHashesMap { hashes: FxHashMap(), prev_metadata_hashes: RefCell::new(FxHashMap()), } } - pub fn get(&self, k: &DepNode) -> Option<&Fingerprint> { - self.hashes.get(k) - } - - pub fn insert(&mut self, k: DepNode, v: Fingerprint) { + pub(crate) fn insert(&mut self, k: DepNode, v: Fingerprint) { assert!(self.hashes.insert(k, v).is_none()); } - pub fn iter<'a>(&'a self) + pub(crate) fn iter<'a>(&'a self) -> ::std::collections::hash_map::Iter<'a, DepNode, Fingerprint> { self.hashes.iter() } - pub fn len(&self) -> usize { + pub(crate) fn len(&self) -> usize { self.hashes.len() } } diff --git a/src/librustc_incremental/lib.rs b/src/librustc_incremental/lib.rs index ac3149b90b8af..c68153140d97c 100644 --- a/src/librustc_incremental/lib.rs +++ b/src/librustc_incremental/lib.rs @@ -44,4 +44,3 @@ pub use persist::save_trans_partition; pub use persist::save_work_products; pub use persist::in_incr_comp_dir; pub use persist::finalize_session_directory; -pub use persist::delete_workproduct_files; diff --git a/src/librustc_incremental/persist/data.rs b/src/librustc_incremental/persist/data.rs index 06acfb5d77807..14e2998175c3c 100644 --- a/src/librustc_incremental/persist/data.rs +++ b/src/librustc_incremental/persist/data.rs @@ -20,21 +20,21 @@ use rustc_data_structures::indexed_vec::{IndexVec, Idx}; /// Data for use when recompiling the **current crate**. #[derive(Debug, RustcEncodable, RustcDecodable)] -pub struct SerializedDepGraph { +pub(crate) struct SerializedDepGraph { /// The set of all DepNodes in the graph - pub nodes: IndexVec, + pub(crate) nodes: IndexVec, /// For each DepNode, stores the list of edges originating from that /// DepNode. Encoded as a [start, end) pair indexing into edge_list_data, /// which holds the actual DepNodeIndices of the target nodes. - pub edge_list_indices: IndexVec, + pub(crate) edge_list_indices: IndexVec, /// A flattened list of all edge targets in the graph. Edge sources are /// implicit in edge_list_indices. - pub edge_list_data: Vec, + pub(crate) edge_list_data: Vec, /// These are output nodes that have no incoming edges. We track /// these separately so that when we reload all edges, we don't /// lose track of these nodes. - pub bootstrap_outputs: Vec, + pub(crate) bootstrap_outputs: Vec, /// These are hashes of two things: /// - the HIR nodes in this crate @@ -55,11 +55,11 @@ pub struct SerializedDepGraph { /// will be different when we next compile) related to each node, /// but rather the `DefPathIndex`. This can then be retraced /// to find the current def-id. - pub hashes: Vec<(DepNodeIndex, Fingerprint)>, + pub(crate) hashes: Vec<(DepNodeIndex, Fingerprint)>, } impl SerializedDepGraph { - pub fn edge_targets_from(&self, source: DepNodeIndex) -> &[DepNodeIndex] { + pub(crate) fn edge_targets_from(&self, source: DepNodeIndex) -> &[DepNodeIndex] { let targets = self.edge_list_indices[source]; &self.edge_list_data[targets.0 as usize .. targets.1 as usize] } @@ -68,11 +68,11 @@ impl SerializedDepGraph { /// The index of a DepNode in the SerializedDepGraph::nodes array. #[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd, Debug, RustcEncodable, RustcDecodable)] -pub struct DepNodeIndex(pub u32); +pub(crate) struct DepNodeIndex(pub(crate) u32); impl DepNodeIndex { #[inline] - pub fn new(idx: usize) -> DepNodeIndex { + pub(crate) fn new(idx: usize) -> DepNodeIndex { assert!(idx <= ::std::u32::MAX as usize); DepNodeIndex(idx as u32) } @@ -92,17 +92,17 @@ impl Idx for DepNodeIndex { } #[derive(Debug, RustcEncodable, RustcDecodable)] -pub struct SerializedWorkProduct { +pub(crate) struct SerializedWorkProduct { /// node that produced the work-product - pub id: WorkProductId, + pub(crate) id: WorkProductId, /// work-product data itself - pub work_product: WorkProduct, + pub(crate) work_product: WorkProduct, } /// Data for use when downstream crates get recompiled. #[derive(Debug, RustcEncodable, RustcDecodable)] -pub struct SerializedMetadataHashes { +pub(crate) struct SerializedMetadataHashes { /// For each def-id defined in this crate that appears in the /// metadata, we hash all the inputs that were used when producing /// the metadata. We save this after compilation is done. Then, @@ -121,7 +121,7 @@ pub struct SerializedMetadataHashes { /// where `X` refers to some item in this crate. That `X` will be /// a `DefPathIndex` that gets retracted to the current `DefId` /// (matching the one found in this structure). - pub entry_hashes: Vec, + pub(crate) entry_hashes: Vec, /// For each DefIndex (as it occurs in SerializedMetadataHash), this /// map stores the DefPathIndex (as it occurs in DefIdDirectory), so @@ -133,5 +133,5 @@ pub struct SerializedMetadataHashes { /// is only populated if -Z query-dep-graph is specified. It will be /// empty otherwise. Importing crates are perfectly happy with just having /// the DefIndex. - pub index_map: FxHashMap + pub(crate) index_map: FxHashMap } diff --git a/src/librustc_incremental/persist/dirty_clean.rs b/src/librustc_incremental/persist/dirty_clean.rs index 3f3dc10365c67..89f981ab8d647 100644 --- a/src/librustc_incremental/persist/dirty_clean.rs +++ b/src/librustc_incremental/persist/dirty_clean.rs @@ -58,9 +58,9 @@ use rustc::ty::TyCtxt; const LABEL: &'static str = "label"; const CFG: &'static str = "cfg"; -pub fn check_dirty_clean_annotations<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - nodes: &IndexVec, - dirty_inputs: &DirtyNodes) { +pub(crate) fn check_dirty_clean_annotations<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, + nodes: &IndexVec, + dirty_inputs: &DirtyNodes) { // can't add `#[rustc_dirty]` etc without opting in to this feature if !tcx.sess.features.borrow().rustc_attrs { return; @@ -103,7 +103,7 @@ pub fn check_dirty_clean_annotations<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, all_attrs.report_unchecked_attrs(&dirty_clean_visitor.checked_attrs); } -pub struct DirtyCleanVisitor<'a, 'tcx:'a> { +pub(crate) struct DirtyCleanVisitor<'a, 'tcx:'a> { tcx: TyCtxt<'a, 'tcx, 'tcx>, query: &'a DepGraphQuery, dirty_inputs: FxHashSet, @@ -231,7 +231,7 @@ impl<'a, 'tcx> ItemLikeVisitor<'tcx> for DirtyCleanVisitor<'a, 'tcx> { } } -pub fn check_dirty_clean_metadata<'a, 'tcx>( +pub(crate) fn check_dirty_clean_metadata<'a, 'tcx>( tcx: TyCtxt<'a, 'tcx, 'tcx>, prev_metadata_hashes: &FxHashMap, current_metadata_hashes: &FxHashMap) @@ -264,7 +264,7 @@ pub fn check_dirty_clean_metadata<'a, 'tcx>( }); } -pub struct DirtyCleanMetadataVisitor<'a, 'tcx: 'a, 'm> { +pub(crate) struct DirtyCleanMetadataVisitor<'a, 'tcx: 'a, 'm> { tcx: TyCtxt<'a, 'tcx, 'tcx>, prev_metadata_hashes: &'m FxHashMap, current_metadata_hashes: &'m FxHashMap, @@ -420,7 +420,7 @@ fn expect_associated_value(tcx: TyCtxt, item: &NestedMetaItem) -> ast::Name { // A visitor that collects all #[rustc_dirty]/#[rustc_clean] attributes from // the HIR. It is used to verfiy that we really ran checks for all annotated // nodes. -pub struct FindAllAttrs<'a, 'tcx:'a> { +pub(crate) struct FindAllAttrs<'a, 'tcx:'a> { tcx: TyCtxt<'a, 'tcx, 'tcx>, attr_names: Vec<&'static str>, found_attrs: Vec<&'tcx Attribute>, diff --git a/src/librustc_incremental/persist/file_format.rs b/src/librustc_incremental/persist/file_format.rs index 13b019af2eaa1..f47f67ac702a8 100644 --- a/src/librustc_incremental/persist/file_format.rs +++ b/src/librustc_incremental/persist/file_format.rs @@ -38,7 +38,7 @@ const HEADER_FORMAT_VERSION: u16 = 0; /// the git commit hash. const RUSTC_VERSION: Option<&'static str> = option_env!("CFG_VERSION"); -pub fn write_file_header(stream: &mut W) -> io::Result<()> { +pub(crate) fn write_file_header(stream: &mut W) -> io::Result<()> { stream.write_all(FILE_MAGIC)?; stream.write_all(&[(HEADER_FORMAT_VERSION >> 0) as u8, (HEADER_FORMAT_VERSION >> 8) as u8])?; @@ -60,7 +60,7 @@ pub fn write_file_header(stream: &mut W) -> io::Result<()> { /// incompatible version of the compiler. /// - Returns `Err(..)` if some kind of IO error occurred while reading the /// file. -pub fn read_file(sess: &Session, path: &Path) -> io::Result>> { +pub(crate) fn read_file(sess: &Session, path: &Path) -> io::Result>> { if !path.exists() { return Ok(None); } diff --git a/src/librustc_incremental/persist/fs.rs b/src/librustc_incremental/persist/fs.rs index 28d33d9528692..cc6871c93d7f2 100644 --- a/src/librustc_incremental/persist/fs.rs +++ b/src/librustc_incremental/persist/fs.rs @@ -141,23 +141,23 @@ const METADATA_HASHES_FILENAME: &'static str = "metadata.bin"; // case-sensitive (as opposed to base64, for example). const INT_ENCODE_BASE: u64 = 36; -pub fn dep_graph_path(sess: &Session) -> PathBuf { +pub(crate) fn dep_graph_path(sess: &Session) -> PathBuf { in_incr_comp_dir_sess(sess, DEP_GRAPH_FILENAME) } -pub fn work_products_path(sess: &Session) -> PathBuf { +pub(crate) fn work_products_path(sess: &Session) -> PathBuf { in_incr_comp_dir_sess(sess, WORK_PRODUCTS_FILENAME) } -pub fn metadata_hash_export_path(sess: &Session) -> PathBuf { +pub(crate) fn metadata_hash_export_path(sess: &Session) -> PathBuf { in_incr_comp_dir_sess(sess, METADATA_HASHES_FILENAME) } -pub fn metadata_hash_import_path(import_session_dir: &Path) -> PathBuf { +pub(crate) fn metadata_hash_import_path(import_session_dir: &Path) -> PathBuf { import_session_dir.join(METADATA_HASHES_FILENAME) } -pub fn lock_file_path(session_dir: &Path) -> PathBuf { +pub(crate) fn lock_file_path(session_dir: &Path) -> PathBuf { let crate_dir = session_dir.parent().unwrap(); let directory_name = session_dir.file_name().unwrap().to_string_lossy(); @@ -176,7 +176,7 @@ pub fn lock_file_path(session_dir: &Path) -> PathBuf { .with_extension(&LOCK_FILE_EXT[1..]) } -pub fn in_incr_comp_dir_sess(sess: &Session, file_name: &str) -> PathBuf { +pub(crate) fn in_incr_comp_dir_sess(sess: &Session, file_name: &str) -> PathBuf { in_incr_comp_dir(&sess.incr_comp_session_dir(), file_name) } @@ -193,7 +193,7 @@ pub fn in_incr_comp_dir(incr_comp_session_dir: &Path, file_name: &str) -> PathBu /// a dep-graph and work products from a previous session. /// If the call fails, the fn may leave behind an invalid session directory. /// The garbage collection will take care of it. -pub fn prepare_session_directory(tcx: TyCtxt) -> Result { +pub(crate) fn prepare_session_directory(tcx: TyCtxt) -> Result { debug!("prepare_session_directory"); // {incr-comp-dir}/{crate-name-and-disambiguator} @@ -375,7 +375,7 @@ pub fn finalize_session_directory(sess: &Session, svh: Svh) { let _ = garbage_collect_session_directories(sess); } -pub fn delete_all_session_dir_contents(sess: &Session) -> io::Result<()> { +pub(crate) fn delete_all_session_dir_contents(sess: &Session) -> io::Result<()> { let sess_dir_iterator = sess.incr_comp_session_dir().read_dir()?; for entry in sess_dir_iterator { let entry = entry?; @@ -615,7 +615,7 @@ fn crate_path_tcx(tcx: TyCtxt, cnum: CrateNum) -> PathBuf { /// crate's (name, disambiguator) pair. The metadata hashes are only valid for /// the exact version of the binary we are reading from now (i.e. the hashes /// are part of the dependency graph of a specific compilation session). -pub fn find_metadata_hashes_for(tcx: TyCtxt, cnum: CrateNum) -> Option { +pub(crate) fn find_metadata_hashes_for(tcx: TyCtxt, cnum: CrateNum) -> Option { let crate_directory = crate_path_tcx(tcx, cnum); if !crate_directory.exists() { @@ -697,7 +697,7 @@ fn is_old_enough_to_be_collected(timestamp: SystemTime) -> bool { timestamp < SystemTime::now() - Duration::from_secs(10) } -pub fn garbage_collect_session_directories(sess: &Session) -> io::Result<()> { +pub(crate) fn garbage_collect_session_directories(sess: &Session) -> io::Result<()> { debug!("garbage_collect_session_directories() - begin"); let session_directory = sess.incr_comp_session_dir(); diff --git a/src/librustc_incremental/persist/hash.rs b/src/librustc_incremental/persist/hash.rs index 0e8ffb9ee3c96..258d8494ca7ec 100644 --- a/src/librustc_incremental/persist/hash.rs +++ b/src/librustc_incremental/persist/hash.rs @@ -26,17 +26,17 @@ use super::file_format; use std::hash::Hash; use std::fmt::Debug; -pub struct HashContext<'a, 'tcx: 'a> { - pub tcx: TyCtxt<'a, 'tcx, 'tcx>, +pub(crate) struct HashContext<'a, 'tcx: 'a> { + pub(crate) tcx: TyCtxt<'a, 'tcx, 'tcx>, incremental_hashes_map: &'a IncrementalHashesMap, metadata_hashes: FxHashMap, crate_hashes: FxHashMap, } impl<'a, 'tcx> HashContext<'a, 'tcx> { - pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, - incremental_hashes_map: &'a IncrementalHashesMap) - -> Self { + pub(crate) fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, + incremental_hashes_map: &'a IncrementalHashesMap) + -> Self { HashContext { tcx: tcx, incremental_hashes_map: incremental_hashes_map, @@ -45,7 +45,7 @@ impl<'a, 'tcx> HashContext<'a, 'tcx> { } } - pub fn is_hashable(tcx: TyCtxt, dep_node: &DepNode) -> bool { + pub(crate) fn is_hashable(tcx: TyCtxt, dep_node: &DepNode) -> bool { match dep_node.kind { DepKind::Krate | DepKind::Hir | @@ -59,7 +59,7 @@ impl<'a, 'tcx> HashContext<'a, 'tcx> { } } - pub fn hash(&mut self, dep_node: &DepNode) -> Option { + pub(crate) fn hash(&mut self, dep_node: &DepNode) -> Option { match dep_node.kind { DepKind::Krate => { Some(self.incremental_hashes_map[dep_node]) diff --git a/src/librustc_incremental/persist/load.rs b/src/librustc_incremental/persist/load.rs index 2c43896ec73d2..87864d2ee9b0c 100644 --- a/src/librustc_incremental/persist/load.rs +++ b/src/librustc_incremental/persist/load.rs @@ -32,7 +32,7 @@ use super::work_product; // The key is a dirty node. The value is **some** base-input that we // can blame it on. -pub type DirtyNodes = FxHashMap; +pub(crate) type DirtyNodes = FxHashMap; /// If we are in incremental mode, and a previous dep-graph exists, /// then load up those nodes/edges that are still valid into the @@ -135,11 +135,11 @@ fn does_still_exist(tcx: TyCtxt, dep_node: &DepNode) -> bool { /// Decode the dep graph and load the edges/nodes that are still clean /// into `tcx.dep_graph`. -pub fn decode_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - incremental_hashes_map: &IncrementalHashesMap, - dep_graph_data: &[u8], - work_products_data: &[u8]) - -> Result<(), String> +pub(crate) fn decode_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, + incremental_hashes_map: &IncrementalHashesMap, + dep_graph_data: &[u8], + work_products_data: &[u8]) + -> Result<(), String> { // Decode the list of work_products let mut work_product_decoder = Decoder::new(work_products_data, 0); diff --git a/src/librustc_incremental/persist/mod.rs b/src/librustc_incremental/persist/mod.rs index c03a0ab4ba2c1..5c1582daa78fa 100644 --- a/src/librustc_incremental/persist/mod.rs +++ b/src/librustc_incremental/persist/mod.rs @@ -28,4 +28,3 @@ pub use self::load::load_dep_graph; pub use self::save::save_dep_graph; pub use self::save::save_work_products; pub use self::work_product::save_trans_partition; -pub use self::work_product::delete_workproduct_files; diff --git a/src/librustc_incremental/persist/preds/compress/classify/mod.rs b/src/librustc_incremental/persist/preds/compress/classify/mod.rs index 559bdbdd1e2e5..9cd5f9bd88973 100644 --- a/src/librustc_incremental/persist/preds/compress/classify/mod.rs +++ b/src/librustc_incremental/persist/preds/compress/classify/mod.rs @@ -15,7 +15,7 @@ use super::*; #[cfg(test)] mod test; -pub struct Classify<'a, 'g: 'a, N: 'g, I: 'a, O: 'a> +pub(crate) struct Classify<'a, 'g: 'a, N: 'g, I: 'a, O: 'a> where N: Debug + Clone + 'g, I: Fn(&N) -> bool, O: Fn(&N) -> bool, diff --git a/src/librustc_incremental/persist/preds/compress/dag_id.rs b/src/librustc_incremental/persist/preds/compress/dag_id.rs index a286862e9551f..233ce9d6eec20 100644 --- a/src/librustc_incremental/persist/preds/compress/dag_id.rs +++ b/src/librustc_incremental/persist/preds/compress/dag_id.rs @@ -12,16 +12,16 @@ use rustc_data_structures::graph::NodeIndex; use rustc_data_structures::unify::UnifyKey; #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] -pub struct DagId { +pub(crate) struct DagId { index: u32, } impl DagId { - pub fn from_input_index(n: NodeIndex) -> Self { + pub(crate) fn from_input_index(n: NodeIndex) -> Self { DagId { index: n.0 as u32 } } - pub fn as_input_index(&self) -> NodeIndex { + pub(crate) fn as_input_index(&self) -> NodeIndex { NodeIndex(self.index as usize) } } diff --git a/src/librustc_incremental/persist/preds/compress/mod.rs b/src/librustc_incremental/persist/preds/compress/mod.rs index 974a2221a4575..2cbcd0cd25f50 100644 --- a/src/librustc_incremental/persist/preds/compress/mod.rs +++ b/src/librustc_incremental/persist/preds/compress/mod.rs @@ -29,9 +29,9 @@ use self::dag_id::DagId; #[cfg(test)] mod test; -pub fn reduce_graph(graph: &Graph, - is_input: I, - is_output: O) -> Reduction +pub(crate) fn reduce_graph(graph: &Graph, + is_input: I, + is_output: O) -> Reduction where N: Debug + Clone, I: Fn(&N) -> bool, O: Fn(&N) -> bool, @@ -39,9 +39,9 @@ pub fn reduce_graph(graph: &Graph, GraphReduce::new(graph, is_input, is_output).compute() } -pub struct Reduction<'q, N> where N: 'q + Debug + Clone { - pub graph: Graph<&'q N, ()>, - pub input_nodes: Vec, +pub(crate) struct Reduction<'q, N> where N: 'q + Debug + Clone { + pub(crate) graph: Graph<&'q N, ()>, + pub(crate) input_nodes: Vec, } struct GraphReduce<'q, N, I, O> diff --git a/src/librustc_incremental/persist/preds/mod.rs b/src/librustc_incremental/persist/preds/mod.rs index f7b6b7376d1fa..a9f09557aebc6 100644 --- a/src/librustc_incremental/persist/preds/mod.rs +++ b/src/librustc_incremental/persist/preds/mod.rs @@ -19,13 +19,13 @@ mod compress; /// A data-structure that makes it easy to enumerate the hashable /// predecessors of any given dep-node. -pub struct Predecessors<'query> { +pub(crate) struct Predecessors<'query> { // A reduced version of the input graph that contains fewer nodes. // This is intended to keep all of the base inputs (i.e., HIR // nodes) and all of the "work-products" we may care about // later. Other nodes may be retained if it keeps the overall size // of the graph down. - pub reduced_graph: Graph<&'query DepNode, ()>, + pub(crate) reduced_graph: Graph<&'query DepNode, ()>, // These are output nodes that have no incoming edges. We have to // track these specially because, when we load the data back up @@ -33,14 +33,14 @@ pub struct Predecessors<'query> { // to recreate the nodes where all incoming edges are clean; but // since we ordinarily just serialize edges, we wind up just // forgetting that bootstrap outputs even exist in that case.) - pub bootstrap_outputs: Vec<&'query DepNode>, + pub(crate) bootstrap_outputs: Vec<&'query DepNode>, // For the inputs (hir/foreign-metadata), we include hashes. - pub hashes: FxHashMap<&'query DepNode, Fingerprint>, + pub(crate) hashes: FxHashMap<&'query DepNode, Fingerprint>, } impl<'q> Predecessors<'q> { - pub fn new(query: &'q DepGraphQuery, hcx: &mut HashContext) -> Self { + pub(crate) fn new(query: &'q DepGraphQuery, hcx: &mut HashContext) -> Self { let tcx = hcx.tcx; // Find the set of "start nodes". These are nodes that we will diff --git a/src/librustc_incremental/persist/save.rs b/src/librustc_incremental/persist/save.rs index 1bdd4f851fb13..ace5caf1f918e 100644 --- a/src/librustc_incremental/persist/save.rs +++ b/src/librustc_incremental/persist/save.rs @@ -166,10 +166,10 @@ fn save_in(sess: &Session, path_buf: PathBuf, encode: F) } } -pub fn encode_dep_graph(tcx: TyCtxt, - preds: &Predecessors, - encoder: &mut Encoder) - -> io::Result<()> { +pub(crate) fn encode_dep_graph(tcx: TyCtxt, + preds: &Predecessors, + encoder: &mut Encoder) + -> io::Result<()> { // First encode the commandline arguments hash tcx.sess.opts.dep_tracking_hash().encode(encoder)?; @@ -272,12 +272,12 @@ pub fn encode_dep_graph(tcx: TyCtxt, Ok(()) } -pub fn encode_metadata_hashes(tcx: TyCtxt, - svh: Svh, - metadata_hashes: &EncodedMetadataHashes, - current_metadata_hashes: &mut FxHashMap, - encoder: &mut Encoder) - -> io::Result<()> { +pub(crate) fn encode_metadata_hashes(tcx: TyCtxt, + svh: Svh, + metadata_hashes: &EncodedMetadataHashes, + current_metadata_hashes: &mut FxHashMap, + encoder: &mut Encoder) + -> io::Result<()> { assert_eq!(metadata_hashes.hashes.len(), metadata_hashes.hashes.iter().map(|x| (x.def_index, ())).collect::>().len()); @@ -309,7 +309,7 @@ pub fn encode_metadata_hashes(tcx: TyCtxt, Ok(()) } -pub fn encode_work_products(sess: &Session, encoder: &mut Encoder) -> io::Result<()> { +pub(crate) fn encode_work_products(sess: &Session, encoder: &mut Encoder) -> io::Result<()> { let work_products: Vec<_> = sess.dep_graph .work_products() .iter() diff --git a/src/librustc_incremental/persist/work_product.rs b/src/librustc_incremental/persist/work_product.rs index 8f99ce91a67a9..a6b7cc6ca8bb7 100644 --- a/src/librustc_incremental/persist/work_product.rs +++ b/src/librustc_incremental/persist/work_product.rs @@ -63,7 +63,7 @@ pub fn save_trans_partition(sess: &Session, sess.dep_graph.insert_work_product(&work_product_id, work_product); } -pub fn delete_workproduct_files(sess: &Session, work_product: &WorkProduct) { +pub(crate) fn delete_workproduct_files(sess: &Session, work_product: &WorkProduct) { for &(_, ref file_name) in &work_product.saved_files { let path = in_incr_comp_dir_sess(sess, file_name); match std_fs::remove_file(&path) { diff --git a/src/librustc_lint/bad_style.rs b/src/librustc_lint/bad_style.rs index d4b8f0a492461..0e3671f63178d 100644 --- a/src/librustc_lint/bad_style.rs +++ b/src/librustc_lint/bad_style.rs @@ -21,13 +21,13 @@ use rustc::hir::{self, PatKind}; use rustc::hir::intravisit::FnKind; #[derive(PartialEq)] -pub enum MethodLateContext { +pub(crate) enum MethodLateContext { TraitDefaultImpl, TraitImpl, PlainImpl, } -pub fn method_context(cx: &LateContext, id: ast::NodeId) -> MethodLateContext { +pub(crate) fn method_context(cx: &LateContext, id: ast::NodeId) -> MethodLateContext { let def_id = cx.tcx.hir.local_def_id(id); let item = cx.tcx.associated_item(def_id); match item.container { @@ -42,13 +42,13 @@ pub fn method_context(cx: &LateContext, id: ast::NodeId) -> MethodLateContext { } declare_lint! { - pub NON_CAMEL_CASE_TYPES, + pub(crate) NON_CAMEL_CASE_TYPES, Warn, "types, variants, traits and type parameters should have camel case names" } #[derive(Copy, Clone)] -pub struct NonCamelCaseTypes; +pub(crate) struct NonCamelCaseTypes; impl NonCamelCaseTypes { fn check_case(&self, cx: &LateContext, sort: &str, name: ast::Name, span: Span) { @@ -133,13 +133,13 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonCamelCaseTypes { } declare_lint! { - pub NON_SNAKE_CASE, + pub(crate) NON_SNAKE_CASE, Warn, "variables, methods, functions, lifetime parameters and modules should have snake case names" } #[derive(Copy, Clone)] -pub struct NonSnakeCase; +pub(crate) struct NonSnakeCase; impl NonSnakeCase { fn to_snake_case(mut str: &str) -> String { @@ -301,13 +301,13 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase { } declare_lint! { - pub NON_UPPER_CASE_GLOBALS, + pub(crate) NON_UPPER_CASE_GLOBALS, Warn, "static constants should have uppercase identifiers" } #[derive(Copy, Clone)] -pub struct NonUpperCaseGlobals; +pub(crate) struct NonUpperCaseGlobals; impl NonUpperCaseGlobals { fn check_upper_case(cx: &LateContext, sort: &str, name: ast::Name, span: Span) { diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs index 02d68a41b4cc4..e523c3f07c60e 100644 --- a/src/librustc_lint/builtin.rs +++ b/src/librustc_lint/builtin.rs @@ -53,7 +53,7 @@ use rustc::hir::intravisit::FnKind; use bad_style::{MethodLateContext, method_context}; // hardwired lints from librustc -pub use lint::builtin::*; +pub(crate) use lint::builtin::*; declare_lint! { WHILE_TRUE, @@ -62,7 +62,7 @@ declare_lint! { } #[derive(Copy, Clone)] -pub struct WhileTrue; +pub(crate) struct WhileTrue; impl LintPass for WhileTrue { fn get_lints(&self) -> LintArray { @@ -91,7 +91,7 @@ declare_lint! { } #[derive(Copy, Clone)] -pub struct BoxPointers; +pub(crate) struct BoxPointers; impl BoxPointers { fn check_heap_type<'a, 'tcx>(&self, cx: &LateContext, span: Span, ty: Ty) { @@ -151,7 +151,7 @@ declare_lint! { } #[derive(Copy, Clone)] -pub struct NonShorthandFieldPatterns; +pub(crate) struct NonShorthandFieldPatterns; impl LintPass for NonShorthandFieldPatterns { fn get_lints(&self) -> LintArray { @@ -187,7 +187,7 @@ declare_lint! { } #[derive(Copy, Clone)] -pub struct UnsafeCode; +pub(crate) struct UnsafeCode; impl LintPass for UnsafeCode { fn get_lints(&self) -> LintArray { @@ -258,7 +258,7 @@ declare_lint! { "detects missing documentation for public members" } -pub struct MissingDoc { +pub(crate) struct MissingDoc { /// Stack of whether #[doc(hidden)] is set /// at each level which has lint attributes. doc_hidden_stack: Vec, @@ -268,7 +268,7 @@ pub struct MissingDoc { } impl MissingDoc { - pub fn new() -> MissingDoc { + pub(crate) fn new() -> MissingDoc { MissingDoc { doc_hidden_stack: vec![false], private_traits: HashSet::new(), @@ -442,13 +442,13 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc { } declare_lint! { - pub MISSING_COPY_IMPLEMENTATIONS, + pub(crate) MISSING_COPY_IMPLEMENTATIONS, Allow, "detects potentially-forgotten implementations of `Copy`" } #[derive(Copy, Clone)] -pub struct MissingCopyImplementations; +pub(crate) struct MissingCopyImplementations; impl LintPass for MissingCopyImplementations { fn get_lints(&self) -> LintArray { @@ -507,12 +507,12 @@ declare_lint! { "detects missing implementations of fmt::Debug" } -pub struct MissingDebugImplementations { +pub(crate) struct MissingDebugImplementations { impling_types: Option, } impl MissingDebugImplementations { - pub fn new() -> MissingDebugImplementations { + pub(crate) fn new() -> MissingDebugImplementations { MissingDebugImplementations { impling_types: None } } } @@ -566,14 +566,14 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations { } declare_lint! { - pub ANONYMOUS_PARAMETERS, + pub(crate) ANONYMOUS_PARAMETERS, Allow, "detects anonymous parameters" } /// Checks for use of anonymous parameters (RFC 1685) #[derive(Clone)] -pub struct AnonymousParameters; +pub(crate) struct AnonymousParameters; impl LintPass for AnonymousParameters { fn get_lints(&self) -> LintArray { @@ -611,14 +611,14 @@ declare_lint! { /// Checks for use of attributes which have been deprecated. #[derive(Clone)] -pub struct DeprecatedAttr { +pub(crate) struct DeprecatedAttr { // This is not free to compute, so we want to keep it around, rather than // compute it for every attribute. depr_attrs: Vec<&'static (&'static str, AttributeType, AttributeGate)>, } impl DeprecatedAttr { - pub fn new() -> DeprecatedAttr { + pub(crate) fn new() -> DeprecatedAttr { DeprecatedAttr { depr_attrs: deprecated_attributes(), } @@ -652,14 +652,14 @@ impl EarlyLintPass for DeprecatedAttr { } declare_lint! { - pub ILLEGAL_FLOATING_POINT_LITERAL_PATTERN, + pub(crate) ILLEGAL_FLOATING_POINT_LITERAL_PATTERN, Warn, "floating-point literals cannot be used in patterns" } /// Checks for floating point literals in patterns. #[derive(Clone)] -pub struct IllegalFloatLiteralPattern; +pub(crate) struct IllegalFloatLiteralPattern; impl LintPass for IllegalFloatLiteralPattern { fn get_lints(&self) -> LintArray { @@ -723,13 +723,13 @@ impl EarlyLintPass for IllegalFloatLiteralPattern { } declare_lint! { - pub UNCONDITIONAL_RECURSION, + pub(crate) UNCONDITIONAL_RECURSION, Warn, "functions that cannot return without calling themselves" } #[derive(Copy, Clone)] -pub struct UnconditionalRecursion; +pub(crate) struct UnconditionalRecursion; impl LintPass for UnconditionalRecursion { @@ -993,7 +993,7 @@ declare_lint! { } #[derive(Copy, Clone)] -pub struct PluginAsLibrary; +pub(crate) struct PluginAsLibrary; impl LintPass for PluginAsLibrary { fn get_lints(&self) -> LintArray { @@ -1056,7 +1056,7 @@ declare_lint! { } #[derive(Copy, Clone)] -pub struct InvalidNoMangleItems; +pub(crate) struct InvalidNoMangleItems; impl LintPass for InvalidNoMangleItems { fn get_lints(&self) -> LintArray { @@ -1108,7 +1108,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems { } #[derive(Clone, Copy)] -pub struct MutableTransmutes; +pub(crate) struct MutableTransmutes; declare_lint! { MUTABLE_TRANSMUTES, @@ -1168,7 +1168,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes { /// Forbids using the `#[feature(...)]` attribute #[derive(Copy, Clone)] -pub struct UnstableFeatures; +pub(crate) struct UnstableFeatures; declare_lint! { UNSTABLE_FEATURES, @@ -1195,7 +1195,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures { } /// Lint for unions that contain fields with possibly non-trivial destructors. -pub struct UnionsWithDropFields; +pub(crate) struct UnionsWithDropFields; declare_lint! { UNIONS_WITH_DROP_FIELDS, diff --git a/src/librustc_lint/lib.rs b/src/librustc_lint/lib.rs index 21dca7f6c61c4..5d3c84084160e 100644 --- a/src/librustc_lint/lib.rs +++ b/src/librustc_lint/lib.rs @@ -31,6 +31,7 @@ #![feature(box_patterns)] #![feature(box_syntax)] #![feature(i128_type)] +#![feature(macro_vis_matcher)] #![feature(quote)] #![feature(rustc_diagnostic_macros)] #![feature(slice_patterns)] @@ -45,10 +46,10 @@ extern crate rustc_back; extern crate rustc_const_eval; extern crate syntax_pos; -pub use rustc::lint; -pub use rustc::middle; -pub use rustc::session; -pub use rustc::util; +use rustc::lint; +use rustc::middle; +use rustc::session; +use rustc::util; use session::Session; use lint::LintId; diff --git a/src/librustc_lint/types.rs b/src/librustc_lint/types.rs index ac3977bd216e7..59f31b3ae4cdd 100644 --- a/src/librustc_lint/types.rs +++ b/src/librustc_lint/types.rs @@ -56,13 +56,13 @@ declare_lint! { } #[derive(Copy, Clone)] -pub struct TypeLimits { +pub(crate) struct TypeLimits { /// Id of the last visited negated expression negated_expr_id: ast::NodeId, } impl TypeLimits { - pub fn new() -> TypeLimits { + pub(crate) fn new() -> TypeLimits { TypeLimits { negated_expr_id: ast::DUMMY_NODE_ID } } } @@ -682,7 +682,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { } #[derive(Copy, Clone)] -pub struct ImproperCTypes; +pub(crate) struct ImproperCTypes; impl LintPass for ImproperCTypes { fn get_lints(&self) -> LintArray { @@ -710,7 +710,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImproperCTypes { } } -pub struct VariantSizeDifferences; +pub(crate) struct VariantSizeDifferences; impl LintPass for VariantSizeDifferences { fn get_lints(&self) -> LintArray { diff --git a/src/librustc_lint/unused.rs b/src/librustc_lint/unused.rs index 473c0f3ffda86..a013e6276f947 100644 --- a/src/librustc_lint/unused.rs +++ b/src/librustc_lint/unused.rs @@ -29,13 +29,13 @@ use rustc::hir; use rustc::hir::intravisit::FnKind; declare_lint! { - pub UNUSED_MUT, + pub(crate) UNUSED_MUT, Warn, "detect mut variables which don't need to be mutable" } #[derive(Copy, Clone)] -pub struct UnusedMut; +pub(crate) struct UnusedMut; impl UnusedMut { fn check_unused_mut_pat(&self, cx: &LateContext, pats: &[P]) { @@ -109,19 +109,19 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedMut { } declare_lint! { - pub UNUSED_MUST_USE, + pub(crate) UNUSED_MUST_USE, Warn, "unused result of a type flagged as #[must_use]" } declare_lint! { - pub UNUSED_RESULTS, + pub(crate) UNUSED_RESULTS, Allow, "unused result of an expression in a statement" } #[derive(Copy, Clone)] -pub struct UnusedResults; +pub(crate) struct UnusedResults; impl LintPass for UnusedResults { fn get_lints(&self) -> LintArray { @@ -172,13 +172,13 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedResults { } declare_lint! { - pub UNUSED_UNSAFE, + pub(crate) UNUSED_UNSAFE, Warn, "unnecessary use of an `unsafe` block" } #[derive(Copy, Clone)] -pub struct UnusedUnsafe; +pub(crate) struct UnusedUnsafe; impl LintPass for UnusedUnsafe { fn get_lints(&self) -> LintArray { @@ -226,13 +226,13 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedUnsafe { } declare_lint! { - pub PATH_STATEMENTS, + pub(crate) PATH_STATEMENTS, Warn, "path statements with no effect" } #[derive(Copy, Clone)] -pub struct PathStatements; +pub(crate) struct PathStatements; impl LintPass for PathStatements { fn get_lints(&self) -> LintArray { @@ -251,13 +251,13 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PathStatements { } declare_lint! { - pub UNUSED_ATTRIBUTES, + pub(crate) UNUSED_ATTRIBUTES, Warn, "detects attributes that were not used by the compiler" } #[derive(Copy, Clone)] -pub struct UnusedAttributes; +pub(crate) struct UnusedAttributes; impl LintPass for UnusedAttributes { fn get_lints(&self) -> LintArray { @@ -325,7 +325,7 @@ declare_lint! { } #[derive(Copy, Clone)] -pub struct UnusedParens; +pub(crate) struct UnusedParens; impl UnusedParens { fn check_unused_parens_core(&self, @@ -424,7 +424,7 @@ declare_lint! { } #[derive(Copy, Clone)] -pub struct UnusedImportBraces; +pub(crate) struct UnusedImportBraces; impl LintPass for UnusedImportBraces { fn get_lints(&self) -> LintArray { @@ -452,7 +452,7 @@ declare_lint! { } #[derive(Copy, Clone)] -pub struct UnusedAllocation; +pub(crate) struct UnusedAllocation; impl LintPass for UnusedAllocation { fn get_lints(&self) -> LintArray { diff --git a/src/librustc_llvm/archive_ro.rs b/src/librustc_llvm/archive_ro.rs index b3f5f8e536052..f3b89386ab9f4 100644 --- a/src/librustc_llvm/archive_ro.rs +++ b/src/librustc_llvm/archive_ro.rs @@ -63,7 +63,7 @@ impl ArchiveRO { } } - pub fn raw(&self) -> ArchiveRef { + pub(crate) fn raw(&self) -> ArchiveRef { self.ptr } diff --git a/src/librustc_llvm/diagnostic.rs b/src/librustc_llvm/diagnostic.rs index cef6199a74af6..a816fe1c8c8da 100644 --- a/src/librustc_llvm/diagnostic.rs +++ b/src/librustc_llvm/diagnostic.rs @@ -10,7 +10,7 @@ //! LLVM diagnostic reports. -pub use self::OptimizationDiagnosticKind::*; +pub(crate) use self::OptimizationDiagnosticKind::*; pub use self::Diagnostic::*; use libc::c_uint; @@ -46,7 +46,7 @@ impl OptimizationDiagnosticKind { pub struct OptimizationDiagnostic { pub kind: OptimizationDiagnosticKind, pub pass_name: String, - pub function: ValueRef, + pub(crate) function: ValueRef, pub debug_loc: DebugLocRef, pub message: String, } @@ -83,7 +83,7 @@ impl OptimizationDiagnostic { pub struct InlineAsmDiagnostic { pub cookie: c_uint, pub message: TwineRef, - pub instruction: ValueRef, + pub(crate) instruction: ValueRef, } impl InlineAsmDiagnostic { diff --git a/src/librustc_llvm/ffi.rs b/src/librustc_llvm/ffi.rs index 9f0ee95b5a60e..44022052de8a4 100644 --- a/src/librustc_llvm/ffi.rs +++ b/src/librustc_llvm/ffi.rs @@ -86,7 +86,7 @@ pub enum Visibility { /// LLVMDiagnosticSeverity #[derive(Copy, Clone, Debug)] #[repr(C)] -pub enum DiagnosticSeverity { +pub(crate) enum DiagnosticSeverity { Error = 0, Warning = 1, Remark = 2, @@ -310,7 +310,7 @@ pub enum CodeModel { /// LLVMRustDiagnosticKind #[derive(Copy, Clone)] #[repr(C)] -pub enum DiagnosticKind { +pub(crate) enum DiagnosticKind { Other, InlineAsm, StackSize, @@ -360,7 +360,7 @@ pub enum Value_opaque {} pub type ValueRef = *mut Value_opaque; #[allow(missing_copy_implementations)] pub enum Metadata_opaque {} -pub type MetadataRef = *mut Metadata_opaque; +pub(crate) type MetadataRef = *mut Metadata_opaque; #[allow(missing_copy_implementations)] pub enum BasicBlock_opaque {} pub type BasicBlockRef = *mut BasicBlock_opaque; @@ -368,11 +368,11 @@ pub type BasicBlockRef = *mut BasicBlock_opaque; pub enum Builder_opaque {} pub type BuilderRef = *mut Builder_opaque; #[allow(missing_copy_implementations)] -pub enum ExecutionEngine_opaque {} -pub type ExecutionEngineRef = *mut ExecutionEngine_opaque; +pub(crate) enum ExecutionEngine_opaque {} +pub(crate) type ExecutionEngineRef = *mut ExecutionEngine_opaque; #[allow(missing_copy_implementations)] pub enum MemoryBuffer_opaque {} -pub type MemoryBufferRef = *mut MemoryBuffer_opaque; +pub(crate) type MemoryBufferRef = *mut MemoryBuffer_opaque; #[allow(missing_copy_implementations)] pub enum PassManager_opaque {} pub type PassManagerRef = *mut PassManager_opaque; @@ -380,50 +380,50 @@ pub type PassManagerRef = *mut PassManager_opaque; pub enum PassManagerBuilder_opaque {} pub type PassManagerBuilderRef = *mut PassManagerBuilder_opaque; #[allow(missing_copy_implementations)] -pub enum Use_opaque {} -pub type UseRef = *mut Use_opaque; +pub(crate) enum Use_opaque {} +pub(crate) type UseRef = *mut Use_opaque; #[allow(missing_copy_implementations)] pub enum TargetData_opaque {} pub type TargetDataRef = *mut TargetData_opaque; #[allow(missing_copy_implementations)] pub enum ObjectFile_opaque {} -pub type ObjectFileRef = *mut ObjectFile_opaque; +pub(crate) type ObjectFileRef = *mut ObjectFile_opaque; #[allow(missing_copy_implementations)] pub enum SectionIterator_opaque {} -pub type SectionIteratorRef = *mut SectionIterator_opaque; +pub(crate) type SectionIteratorRef = *mut SectionIterator_opaque; #[allow(missing_copy_implementations)] pub enum Pass_opaque {} -pub type PassRef = *mut Pass_opaque; +pub(crate) type PassRef = *mut Pass_opaque; #[allow(missing_copy_implementations)] pub enum TargetMachine_opaque {} pub type TargetMachineRef = *mut TargetMachine_opaque; -pub enum Archive_opaque {} -pub type ArchiveRef = *mut Archive_opaque; -pub enum ArchiveIterator_opaque {} -pub type ArchiveIteratorRef = *mut ArchiveIterator_opaque; +pub(crate) enum Archive_opaque {} +pub(crate) type ArchiveRef = *mut Archive_opaque; +pub(crate) enum ArchiveIterator_opaque {} +pub(crate) type ArchiveIteratorRef = *mut ArchiveIterator_opaque; pub enum ArchiveChild_opaque {} -pub type ArchiveChildRef = *mut ArchiveChild_opaque; +pub(crate) type ArchiveChildRef = *mut ArchiveChild_opaque; #[allow(missing_copy_implementations)] pub enum Twine_opaque {} -pub type TwineRef = *mut Twine_opaque; +pub(crate) type TwineRef = *mut Twine_opaque; #[allow(missing_copy_implementations)] pub enum DiagnosticInfo_opaque {} pub type DiagnosticInfoRef = *mut DiagnosticInfo_opaque; #[allow(missing_copy_implementations)] pub enum DebugLoc_opaque {} -pub type DebugLocRef = *mut DebugLoc_opaque; +pub(crate) type DebugLocRef = *mut DebugLoc_opaque; #[allow(missing_copy_implementations)] pub enum SMDiagnostic_opaque {} pub type SMDiagnosticRef = *mut SMDiagnostic_opaque; #[allow(missing_copy_implementations)] pub enum RustArchiveMember_opaque {} -pub type RustArchiveMemberRef = *mut RustArchiveMember_opaque; +pub(crate) type RustArchiveMemberRef = *mut RustArchiveMember_opaque; #[allow(missing_copy_implementations)] pub enum OperandBundleDef_opaque {} -pub type OperandBundleDefRef = *mut OperandBundleDef_opaque; +pub(crate) type OperandBundleDefRef = *mut OperandBundleDef_opaque; -pub type DiagnosticHandler = unsafe extern "C" fn(DiagnosticInfoRef, *mut c_void); -pub type InlineAsmDiagHandler = unsafe extern "C" fn(SMDiagnosticRef, *const c_void, c_uint); +pub(crate) type DiagnosticHandler = unsafe extern "C" fn(DiagnosticInfoRef, *mut c_void); +pub(crate) type InlineAsmDiagHandler = unsafe extern "C" fn(SMDiagnosticRef, *const c_void, c_uint); pub mod debuginfo { @@ -435,21 +435,21 @@ pub mod debuginfo { pub type DIDescriptor = MetadataRef; pub type DIScope = DIDescriptor; - pub type DILocation = DIDescriptor; + pub(crate) type DILocation = DIDescriptor; pub type DIFile = DIScope; pub type DILexicalBlock = DIScope; pub type DISubprogram = DIScope; - pub type DINameSpace = DIScope; + pub(crate) type DINameSpace = DIScope; pub type DIType = DIDescriptor; - pub type DIBasicType = DIType; - pub type DIDerivedType = DIType; + pub(crate) type DIBasicType = DIType; + pub(crate) type DIDerivedType = DIType; pub type DICompositeType = DIDerivedType; - pub type DIVariable = DIDescriptor; - pub type DIGlobalVariable = DIDescriptor; + pub(crate) type DIVariable = DIDescriptor; + pub(crate) type DIGlobalVariable = DIDescriptor; pub type DIArray = DIDescriptor; - pub type DISubrange = DIDescriptor; - pub type DIEnumerator = DIDescriptor; - pub type DITemplateTypeParameter = DIDescriptor; + pub(crate) type DISubrange = DIDescriptor; + pub(crate) type DIEnumerator = DIDescriptor; + pub(crate) type DITemplateTypeParameter = DIDescriptor; // These values **must** match with LLVMRustDIFlags!! bitflags! { @@ -517,7 +517,7 @@ extern "C" { pub fn LLVMRustGetTypeKind(Ty: TypeRef) -> TypeKind; /// See llvm::Value::getContext - pub fn LLVMRustGetValueContext(V: ValueRef) -> ContextRef; + pub(crate) fn LLVMRustGetValueContext(V: ValueRef) -> ContextRef; // Operations on integer types pub fn LLVMInt1TypeInContext(C: ContextRef) -> TypeRef; @@ -574,12 +574,12 @@ extern "C" { pub fn LLVMSetMetadata(Val: ValueRef, KindID: c_uint, Node: ValueRef); // Operations on Uses - pub fn LLVMGetFirstUse(Val: ValueRef) -> UseRef; - pub fn LLVMGetNextUse(U: UseRef) -> UseRef; - pub fn LLVMGetUser(U: UseRef) -> ValueRef; + pub(crate) fn LLVMGetFirstUse(Val: ValueRef) -> UseRef; + pub(crate) fn LLVMGetNextUse(U: UseRef) -> UseRef; + pub(crate) fn LLVMGetUser(U: UseRef) -> ValueRef; // Operations on Users - pub fn LLVMGetOperand(Val: ValueRef, Index: c_uint) -> ValueRef; + pub(crate) fn LLVMGetOperand(Val: ValueRef, Index: c_uint) -> ValueRef; // Operations on constants of any type pub fn LLVMConstNull(Ty: TypeRef) -> ValueRef; @@ -624,7 +624,7 @@ extern "C" { pub fn LLVMConstVector(ScalarConstantVals: *const ValueRef, Size: c_uint) -> ValueRef; // Constant expressions - pub fn LLVMSizeOf(Ty: TypeRef) -> ValueRef; + pub(crate) fn LLVMSizeOf(Ty: TypeRef) -> ValueRef; pub fn LLVMConstNeg(ConstantVal: ValueRef) -> ValueRef; pub fn LLVMConstFNeg(ConstantVal: ValueRef) -> ValueRef; pub fn LLVMConstNot(ConstantVal: ValueRef) -> ValueRef; @@ -675,7 +675,7 @@ extern "C" { pub fn LLVMIsDeclaration(Global: ValueRef) -> Bool; pub fn LLVMRustGetLinkage(Global: ValueRef) -> Linkage; pub fn LLVMRustSetLinkage(Global: ValueRef, RustLinkage: Linkage); - pub fn LLVMGetSection(Global: ValueRef) -> *const c_char; + pub(crate) fn LLVMGetSection(Global: ValueRef) -> *const c_char; pub fn LLVMSetSection(Global: ValueRef, Section: *const c_char); pub fn LLVMRustGetVisibility(Global: ValueRef) -> Visibility; pub fn LLVMRustSetVisibility(Global: ValueRef, Viz: Visibility); @@ -694,14 +694,15 @@ extern "C" { pub fn LLVMDeleteGlobal(GlobalVar: ValueRef); pub fn LLVMGetInitializer(GlobalVar: ValueRef) -> ValueRef; pub fn LLVMSetInitializer(GlobalVar: ValueRef, ConstantVal: ValueRef); - pub fn LLVMSetThreadLocal(GlobalVar: ValueRef, IsThreadLocal: Bool); + pub(crate) fn LLVMSetThreadLocal(GlobalVar: ValueRef, IsThreadLocal: Bool); pub fn LLVMIsGlobalConstant(GlobalVar: ValueRef) -> Bool; pub fn LLVMSetGlobalConstant(GlobalVar: ValueRef, IsConstant: Bool); pub fn LLVMRustGetNamedValue(M: ModuleRef, Name: *const c_char) -> ValueRef; pub fn LLVMSetTailCall(CallInst: ValueRef, IsTailCall: Bool); // Operations on functions - pub fn LLVMAddFunction(M: ModuleRef, Name: *const c_char, FunctionTy: TypeRef) -> ValueRef; + pub(crate) fn LLVMAddFunction(M: ModuleRef, Name: *const c_char, FunctionTy: TypeRef) + -> ValueRef; pub fn LLVMGetNamedFunction(M: ModuleRef, Name: *const c_char) -> ValueRef; pub fn LLVMGetFirstFunction(M: ModuleRef) -> ValueRef; pub fn LLVMGetNextFunction(Fn: ValueRef) -> ValueRef; @@ -709,21 +710,21 @@ extern "C" { Name: *const c_char, FunctionTy: TypeRef) -> ValueRef; - pub fn LLVMSetFunctionCallConv(Fn: ValueRef, CC: c_uint); + pub(crate) fn LLVMSetFunctionCallConv(Fn: ValueRef, CC: c_uint); pub fn LLVMRustAddDereferenceableAttr(Fn: ValueRef, index: c_uint, bytes: u64); - pub fn LLVMRustAddFunctionAttribute(Fn: ValueRef, index: c_uint, attr: Attribute); - pub fn LLVMRustAddFunctionAttrStringValue(Fn: ValueRef, - index: c_uint, - Name: *const c_char, - Value: *const c_char); - pub fn LLVMRustRemoveFunctionAttributes(Fn: ValueRef, index: c_uint, attr: Attribute); + pub(crate) fn LLVMRustAddFunctionAttribute(Fn: ValueRef, index: c_uint, attr: Attribute); + pub(crate) fn LLVMRustAddFunctionAttrStringValue(Fn: ValueRef, + index: c_uint, + Name: *const c_char, + Value: *const c_char); + pub(crate) fn LLVMRustRemoveFunctionAttributes(Fn: ValueRef, index: c_uint, attr: Attribute); // Operations on parameters - pub fn LLVMCountParams(Fn: ValueRef) -> c_uint; + pub(crate) fn LLVMCountParams(Fn: ValueRef) -> c_uint; pub fn LLVMGetParam(Fn: ValueRef, Index: c_uint) -> ValueRef; // Operations on basic blocks - pub fn LLVMBasicBlockAsValue(BB: BasicBlockRef) -> ValueRef; + pub(crate) fn LLVMBasicBlockAsValue(BB: BasicBlockRef) -> ValueRef; pub fn LLVMGetBasicBlockParent(BB: BasicBlockRef) -> ValueRef; pub fn LLVMAppendBasicBlockInContext(C: ContextRef, Fn: ValueRef, @@ -732,14 +733,14 @@ extern "C" { pub fn LLVMDeleteBasicBlock(BB: BasicBlockRef); // Operations on instructions - pub fn LLVMGetInstructionParent(Inst: ValueRef) -> BasicBlockRef; + pub(crate) fn LLVMGetInstructionParent(Inst: ValueRef) -> BasicBlockRef; pub fn LLVMGetFirstBasicBlock(Fn: ValueRef) -> BasicBlockRef; - pub fn LLVMGetFirstInstruction(BB: BasicBlockRef) -> ValueRef; - pub fn LLVMInstructionEraseFromParent(Inst: ValueRef); + pub(crate) fn LLVMGetFirstInstruction(BB: BasicBlockRef) -> ValueRef; + pub(crate) fn LLVMInstructionEraseFromParent(Inst: ValueRef); // Operations on call sites - pub fn LLVMSetInstructionCallConv(Instr: ValueRef, CC: c_uint); - pub fn LLVMRustAddCallSiteAttribute(Instr: ValueRef, index: c_uint, attr: Attribute); + pub(crate) fn LLVMSetInstructionCallConv(Instr: ValueRef, CC: c_uint); + pub(crate) fn LLVMRustAddCallSiteAttribute(Instr: ValueRef, index: c_uint, attr: Attribute); pub fn LLVMRustAddDereferenceableCallSiteAttr(Instr: ValueRef, index: c_uint, bytes: u64); // Operations on load/store instructions (only) @@ -753,7 +754,7 @@ extern "C" { // Instruction builders pub fn LLVMCreateBuilderInContext(C: ContextRef) -> BuilderRef; - pub fn LLVMPositionBuilder(Builder: BuilderRef, Block: BasicBlockRef, Instr: ValueRef); + pub(crate) fn LLVMPositionBuilder(Builder: BuilderRef, Block: BasicBlockRef, Instr: ValueRef); pub fn LLVMPositionBuilderBefore(Builder: BuilderRef, Instr: ValueRef); pub fn LLVMPositionBuilderAtEnd(Builder: BuilderRef, Block: BasicBlockRef); pub fn LLVMGetInsertBlock(Builder: BuilderRef) -> BasicBlockRef; @@ -1213,14 +1214,14 @@ extern "C" { // Selected entries from the downcasts. - pub fn LLVMIsATerminatorInst(Inst: ValueRef) -> ValueRef; - pub fn LLVMIsAStoreInst(Inst: ValueRef) -> ValueRef; + pub(crate) fn LLVMIsATerminatorInst(Inst: ValueRef) -> ValueRef; + pub(crate) fn LLVMIsAStoreInst(Inst: ValueRef) -> ValueRef; /// Writes a module to the specified path. Returns 0 on success. pub fn LLVMWriteBitcodeToFile(M: ModuleRef, Path: *const c_char) -> c_int; /// Creates target data from a target layout string. - pub fn LLVMCreateTargetData(StringRep: *const c_char) -> TargetDataRef; + pub(crate) fn LLVMCreateTargetData(StringRep: *const c_char) -> TargetDataRef; /// Number of bytes clobbered when doing a Store to *T. pub fn LLVMSizeOfTypeInBits(TD: TargetDataRef, Ty: TypeRef) -> c_ulonglong; @@ -1240,7 +1241,7 @@ extern "C" { -> c_ulonglong; /// Disposes target data. - pub fn LLVMDisposeTargetData(TD: TargetDataRef); + pub(crate) fn LLVMDisposeTargetData(TD: TargetDataRef); /// Creates a pass manager. pub fn LLVMCreatePassManager() -> PassManagerRef; @@ -1275,14 +1276,14 @@ extern "C" { // Stuff that's in rustllvm/ because it's not upstream yet. /// Opens an object file. - pub fn LLVMCreateObjectFile(MemBuf: MemoryBufferRef) -> ObjectFileRef; + pub(crate) fn LLVMCreateObjectFile(MemBuf: MemoryBufferRef) -> ObjectFileRef; /// Closes an object file. - pub fn LLVMDisposeObjectFile(ObjFile: ObjectFileRef); + pub(crate) fn LLVMDisposeObjectFile(ObjFile: ObjectFileRef); /// Enumerates the sections in an object file. - pub fn LLVMGetSections(ObjFile: ObjectFileRef) -> SectionIteratorRef; + pub(crate) fn LLVMGetSections(ObjFile: ObjectFileRef) -> SectionIteratorRef; /// Destroys a section iterator. - pub fn LLVMDisposeSectionIterator(SI: SectionIteratorRef); + pub(crate) fn LLVMDisposeSectionIterator(SI: SectionIteratorRef); /// Returns true if the section iterator is at the end of the section /// list: pub fn LLVMIsSectionIteratorAtEnd(ObjFile: ObjectFileRef, SI: SectionIteratorRef) -> Bool; @@ -1613,37 +1614,39 @@ extern "C" { pub fn LLVMRustRunRestrictionPass(M: ModuleRef, syms: *const *const c_char, len: size_t); pub fn LLVMRustMarkAllFunctionsNounwind(M: ModuleRef); - pub fn LLVMRustOpenArchive(path: *const c_char) -> ArchiveRef; - pub fn LLVMRustArchiveIteratorNew(AR: ArchiveRef) -> ArchiveIteratorRef; - pub fn LLVMRustArchiveIteratorNext(AIR: ArchiveIteratorRef) -> ArchiveChildRef; - pub fn LLVMRustArchiveChildName(ACR: ArchiveChildRef, size: *mut size_t) -> *const c_char; - pub fn LLVMRustArchiveChildData(ACR: ArchiveChildRef, size: *mut size_t) -> *const c_char; - pub fn LLVMRustArchiveChildFree(ACR: ArchiveChildRef); - pub fn LLVMRustArchiveIteratorFree(AIR: ArchiveIteratorRef); - pub fn LLVMRustDestroyArchive(AR: ArchiveRef); + pub(crate) fn LLVMRustOpenArchive(path: *const c_char) -> ArchiveRef; + pub(crate) fn LLVMRustArchiveIteratorNew(AR: ArchiveRef) -> ArchiveIteratorRef; + pub(crate) fn LLVMRustArchiveIteratorNext(AIR: ArchiveIteratorRef) -> ArchiveChildRef; + pub(crate) fn LLVMRustArchiveChildName(ACR: ArchiveChildRef, size: *mut size_t) + -> *const c_char; + pub(crate) fn LLVMRustArchiveChildData(ACR: ArchiveChildRef, size: *mut size_t) + -> *const c_char; + pub(crate) fn LLVMRustArchiveChildFree(ACR: ArchiveChildRef); + pub(crate) fn LLVMRustArchiveIteratorFree(AIR: ArchiveIteratorRef); + pub(crate) fn LLVMRustDestroyArchive(AR: ArchiveRef); pub fn LLVMRustGetSectionName(SI: SectionIteratorRef, data: *mut *const c_char) -> size_t; - pub fn LLVMRustWriteTwineToString(T: TwineRef, s: RustStringRef); + pub(crate) fn LLVMRustWriteTwineToString(T: TwineRef, s: RustStringRef); pub fn LLVMContextSetDiagnosticHandler(C: ContextRef, Handler: DiagnosticHandler, DiagnosticContext: *mut c_void); - pub fn LLVMRustUnpackOptimizationDiagnostic(DI: DiagnosticInfoRef, - pass_name_out: RustStringRef, - function_out: *mut ValueRef, - debugloc_out: *mut DebugLocRef, - message_out: RustStringRef); - pub fn LLVMRustUnpackInlineAsmDiagnostic(DI: DiagnosticInfoRef, - cookie_out: *mut c_uint, - message_out: *mut TwineRef, - instruction_out: *mut ValueRef); + pub(crate) fn LLVMRustUnpackOptimizationDiagnostic(DI: DiagnosticInfoRef, + pass_name_out: RustStringRef, + function_out: *mut ValueRef, + debugloc_out: *mut DebugLocRef, + message_out: RustStringRef); + pub(crate) fn LLVMRustUnpackInlineAsmDiagnostic(DI: DiagnosticInfoRef, + cookie_out: *mut c_uint, + message_out: *mut TwineRef, + instruction_out: *mut ValueRef); - pub fn LLVMRustWriteDiagnosticInfoToString(DI: DiagnosticInfoRef, s: RustStringRef); - pub fn LLVMRustGetDiagInfoKind(DI: DiagnosticInfoRef) -> DiagnosticKind; + pub(crate) fn LLVMRustWriteDiagnosticInfoToString(DI: DiagnosticInfoRef, s: RustStringRef); + pub(crate) fn LLVMRustGetDiagInfoKind(DI: DiagnosticInfoRef) -> DiagnosticKind; - pub fn LLVMRustWriteDebugLocToString(C: ContextRef, DL: DebugLocRef, s: RustStringRef); + pub(crate) fn LLVMRustWriteDebugLocToString(C: ContextRef, DL: DebugLocRef, s: RustStringRef); pub fn LLVMRustSetInlineAsmDiagnosticHandler(C: ContextRef, H: InlineAsmDiagHandler, @@ -1666,15 +1669,15 @@ extern "C" { pub fn LLVMRustSetDataLayoutFromTargetMachine(M: ModuleRef, TM: TargetMachineRef); pub fn LLVMRustGetModuleDataLayout(M: ModuleRef) -> TargetDataRef; - pub fn LLVMRustBuildOperandBundleDef(Name: *const c_char, - Inputs: *const ValueRef, - NumInputs: c_uint) - -> OperandBundleDefRef; - pub fn LLVMRustFreeOperandBundleDef(Bundle: OperandBundleDefRef); + pub(crate) fn LLVMRustBuildOperandBundleDef(Name: *const c_char, + Inputs: *const ValueRef, + NumInputs: c_uint) + -> OperandBundleDefRef; + pub(crate) fn LLVMRustFreeOperandBundleDef(Bundle: OperandBundleDefRef); pub fn LLVMRustPositionBuilderAtStart(B: BuilderRef, BB: BasicBlockRef); - pub fn LLVMRustSetComdat(M: ModuleRef, V: ValueRef, Name: *const c_char); - pub fn LLVMRustUnsetComdat(V: ValueRef); + pub(crate) fn LLVMRustSetComdat(M: ModuleRef, V: ValueRef, Name: *const c_char); + pub(crate) fn LLVMRustUnsetComdat(V: ValueRef); pub fn LLVMRustSetModulePIELevel(M: ModuleRef); } diff --git a/src/librustc_llvm/lib.rs b/src/librustc_llvm/lib.rs index 947e433fdb936..f3b42a048c489 100644 --- a/src/librustc_llvm/lib.rs +++ b/src/librustc_llvm/lib.rs @@ -40,9 +40,7 @@ pub use self::TypeKind::*; pub use self::AtomicRmwBinOp::*; pub use self::MetadataType::*; pub use self::CodeGenOptSize::*; -pub use self::DiagnosticKind::*; pub use self::CallConv::*; -pub use self::DiagnosticSeverity::*; pub use self::Linkage::*; use std::str::FromStr; @@ -53,7 +51,7 @@ use libc::{c_uint, c_char, size_t}; pub mod archive_ro; pub mod diagnostic; -pub mod ffi; +mod ffi; pub use ffi::*; @@ -122,7 +120,7 @@ impl FromStr for ArchiveKind { #[allow(missing_copy_implementations)] pub enum RustString_opaque {} -pub type RustStringRef = *mut RustString_opaque; +type RustStringRef = *mut RustString_opaque; type RustStringRepr = *mut RefCell>; /// Appending to a Rust string -- used by RawRustStringOstream. @@ -201,8 +199,8 @@ impl Attribute { // Memory-managed interface to target data. -pub struct TargetData { - pub lltd: TargetDataRef, +struct TargetData { + lltd: TargetDataRef, } impl Drop for TargetData { @@ -213,7 +211,7 @@ impl Drop for TargetData { } } -pub fn mk_target_data(string_rep: &str) -> TargetData { +fn mk_target_data(string_rep: &str) -> TargetData { let string_rep = CString::new(string_rep).unwrap(); TargetData { lltd: unsafe { LLVMCreateTargetData(string_rep.as_ptr()) } } } @@ -274,7 +272,7 @@ pub fn get_param(llfn: ValueRef, index: c_uint) -> ValueRef { } } -pub fn get_params(llfn: ValueRef) -> Vec { +fn get_params(llfn: ValueRef) -> Vec { unsafe { let num_params = LLVMCountParams(llfn); let mut params = Vec::with_capacity(num_params as usize); diff --git a/src/librustc_metadata/astencode.rs b/src/librustc_metadata/astencode.rs index 6c02ac7eafec3..4116fb795d701 100644 --- a/src/librustc_metadata/astencode.rs +++ b/src/librustc_metadata/astencode.rs @@ -17,11 +17,11 @@ use rustc::hir; use rustc::ty; #[derive(RustcEncodable, RustcDecodable)] -pub struct Ast<'tcx> { - pub body: Lazy, - pub tables: Lazy>, - pub nested_bodies: LazySeq, - pub rvalue_promotable_to_static: bool, +pub(crate) struct Ast<'tcx> { + pub(crate) body: Lazy, + pub(crate) tables: Lazy>, + pub(crate) nested_bodies: LazySeq, + pub(crate) rvalue_promotable_to_static: bool, } impl_stable_hash_for!(struct Ast<'tcx> { @@ -32,7 +32,7 @@ impl_stable_hash_for!(struct Ast<'tcx> { }); impl<'a, 'b, 'tcx> IsolatedEncoder<'a, 'b, 'tcx> { - pub fn encode_body(&mut self, body_id: hir::BodyId) -> Lazy> { + pub(crate) fn encode_body(&mut self, body_id: hir::BodyId) -> Lazy> { let body = self.tcx.hir.body(body_id); let lazy_body = self.lazy(body); diff --git a/src/librustc_metadata/creader.rs b/src/librustc_metadata/creader.rs index d15843b4f318b..5b8d99a0e843c 100644 --- a/src/librustc_metadata/creader.rs +++ b/src/librustc_metadata/creader.rs @@ -45,15 +45,15 @@ use syntax::visit; use syntax_pos::{Span, DUMMY_SP}; use log; -pub struct Library { - pub dylib: Option<(PathBuf, PathKind)>, - pub rlib: Option<(PathBuf, PathKind)>, - pub rmeta: Option<(PathBuf, PathKind)>, - pub metadata: MetadataBlob, +pub(crate) struct Library { + pub(crate) dylib: Option<(PathBuf, PathKind)>, + pub(crate) rlib: Option<(PathBuf, PathKind)>, + pub(crate) rmeta: Option<(PathBuf, PathKind)>, + pub(crate) metadata: MetadataBlob, } pub struct CrateLoader<'a> { - pub sess: &'a Session, + pub(crate) sess: &'a Session, cstore: &'a CStore, next_crate_num: CrateNum, local_crate_name: Symbol, diff --git a/src/librustc_metadata/cstore.rs b/src/librustc_metadata/cstore.rs index fb43f91c46d7f..6d158c7b2ec00 100644 --- a/src/librustc_metadata/cstore.rs +++ b/src/librustc_metadata/cstore.rs @@ -30,9 +30,9 @@ use syntax::ext::base::SyntaxExtension; use syntax::symbol::Symbol; use syntax_pos; -pub use rustc::middle::cstore::{NativeLibrary, NativeLibraryKind, LinkagePreference}; -pub use rustc::middle::cstore::NativeLibraryKind::*; -pub use rustc::middle::cstore::{CrateSource, LinkMeta, LibSource}; +pub(crate) use rustc::middle::cstore::{NativeLibrary, NativeLibraryKind, LinkagePreference}; +pub(crate) use rustc::middle::cstore::NativeLibraryKind::*; +pub(crate) use rustc::middle::cstore::{CrateSource, LibSource}; pub use cstore_impl::{provide, provide_local}; @@ -40,67 +40,67 @@ pub use cstore_impl::{provide, provide_local}; // local crate numbers (as generated during this session). Each external // crate may refer to types in other external crates, and each has their // own crate numbers. -pub type CrateNumMap = IndexVec; +pub(crate) type CrateNumMap = IndexVec; -pub struct MetadataBlob(pub ErasedBoxRef<[u8]>); +pub(crate) struct MetadataBlob(pub(crate) ErasedBoxRef<[u8]>); /// Holds information about a syntax_pos::FileMap imported from another crate. /// See `imported_filemaps()` for more information. -pub struct ImportedFileMap { +pub(crate) struct ImportedFileMap { /// This FileMap's byte-offset within the codemap of its original crate - pub original_start_pos: syntax_pos::BytePos, + pub(crate) original_start_pos: syntax_pos::BytePos, /// The end of this FileMap within the codemap of its original crate - pub original_end_pos: syntax_pos::BytePos, + pub(crate) original_end_pos: syntax_pos::BytePos, /// The imported FileMap's representation within the local codemap - pub translated_filemap: Rc, + pub(crate) translated_filemap: Rc, } -pub struct CrateMetadata { - pub name: Symbol, +pub(crate) struct CrateMetadata { + pub(crate) name: Symbol, /// Information about the extern crate that caused this crate to /// be loaded. If this is `None`, then the crate was injected /// (e.g., by the allocator) - pub extern_crate: Cell>, + pub(crate) extern_crate: Cell>, - pub blob: MetadataBlob, - pub cnum_map: RefCell, - pub cnum: CrateNum, - pub codemap_import_info: RefCell>, - pub attribute_cache: RefCell<[Vec>>; 2]>, + pub(crate) blob: MetadataBlob, + pub(crate) cnum_map: RefCell, + pub(crate) cnum: CrateNum, + pub(crate) codemap_import_info: RefCell>, + pub(crate) attribute_cache: RefCell<[Vec>>; 2]>, - pub root: schema::CrateRoot, + pub(crate) root: schema::CrateRoot, /// For each public item in this crate, we encode a key. When the /// crate is loaded, we read all the keys and put them in this /// hashmap, which gives the reverse mapping. This allows us to /// quickly retrace a `DefPath`, which is needed for incremental /// compilation support. - pub def_path_table: Rc, + pub(crate) def_path_table: Rc, - pub exported_symbols: Tracked>, + pub(crate) exported_symbols: Tracked>, - pub trait_impls: Tracked>>, + pub(crate) trait_impls: Tracked>>, - pub dep_kind: Cell, - pub source: CrateSource, + pub(crate) dep_kind: Cell, + pub(crate) source: CrateSource, - pub proc_macros: Option)>>, + pub(crate) proc_macros: Option)>>, // Foreign items imported from a dylib (Windows only) - pub dllimport_foreign_items: Tracked>, + pub(crate) dllimport_foreign_items: Tracked>, } pub struct CStore { - pub dep_graph: DepGraph, + pub(crate) dep_graph: DepGraph, metas: RefCell>>, /// Map from NodeId's of local extern crate statements to crate numbers extern_mod_crate_map: RefCell>, used_libraries: RefCell>, used_link_args: RefCell>, statically_included_foreign_items: RefCell>, - pub dllimport_foreign_items: RefCell>, - pub visible_parent_map: RefCell>, - pub metadata_loader: Box, + pub(crate) dllimport_foreign_items: RefCell>, + pub(crate) visible_parent_map: RefCell>, + pub(crate) metadata_loader: Box, } impl CStore { @@ -118,23 +118,23 @@ impl CStore { } } - pub fn next_crate_num(&self) -> CrateNum { + pub(crate) fn next_crate_num(&self) -> CrateNum { CrateNum::new(self.metas.borrow().len() + 1) } - pub fn get_crate_data(&self, cnum: CrateNum) -> Rc { + pub(crate) fn get_crate_data(&self, cnum: CrateNum) -> Rc { self.metas.borrow().get(&cnum).unwrap().clone() } - pub fn get_crate_hash(&self, cnum: CrateNum) -> Svh { + pub(crate) fn get_crate_hash(&self, cnum: CrateNum) -> Svh { self.get_crate_data(cnum).hash() } - pub fn set_crate_data(&self, cnum: CrateNum, data: Rc) { + pub(crate) fn set_crate_data(&self, cnum: CrateNum, data: Rc) { self.metas.borrow_mut().insert(cnum, data); } - pub fn iter_crate_data(&self, mut i: I) + pub(crate) fn iter_crate_data(&self, mut i: I) where I: FnMut(CrateNum, &Rc) { for (&k, v) in self.metas.borrow().iter() { @@ -142,22 +142,16 @@ impl CStore { } } - pub fn reset(&self) { - self.metas.borrow_mut().clear(); - self.extern_mod_crate_map.borrow_mut().clear(); - self.used_libraries.borrow_mut().clear(); - self.used_link_args.borrow_mut().clear(); - self.statically_included_foreign_items.borrow_mut().clear(); - } - - pub fn crate_dependencies_in_rpo(&self, krate: CrateNum) -> Vec { + pub(crate) fn crate_dependencies_in_rpo(&self, krate: CrateNum) -> Vec { let mut ordering = Vec::new(); self.push_dependencies_in_postorder(&mut ordering, krate); ordering.reverse(); ordering } - pub fn push_dependencies_in_postorder(&self, ordering: &mut Vec, krate: CrateNum) { + pub(crate) fn push_dependencies_in_postorder(&self, + ordering: &mut Vec, + krate: CrateNum) { if ordering.contains(&krate) { return; } @@ -181,9 +175,9 @@ impl CStore { // In order to get this left-to-right dependency ordering, we perform a // topological sort of all crates putting the leaves at the right-most // positions. - pub fn do_get_used_crates(&self, - prefer: LinkagePreference) - -> Vec<(CrateNum, LibSource)> { + pub(crate) fn do_get_used_crates(&self, + prefer: LinkagePreference) + -> Vec<(CrateNum, LibSource)> { let mut ordering = Vec::new(); for (&num, _) in self.metas.borrow().iter() { self.push_dependencies_in_postorder(&mut ordering, num); @@ -220,43 +214,43 @@ impl CStore { libs } - pub fn add_used_library(&self, lib: NativeLibrary) { + pub(crate) fn add_used_library(&self, lib: NativeLibrary) { assert!(!lib.name.as_str().is_empty()); self.used_libraries.borrow_mut().push(lib); } - pub fn get_used_libraries(&self) -> &RefCell> { + pub(crate) fn get_used_libraries(&self) -> &RefCell> { &self.used_libraries } - pub fn add_used_link_args(&self, args: &str) { + pub(crate) fn add_used_link_args(&self, args: &str) { for s in args.split(' ').filter(|s| !s.is_empty()) { self.used_link_args.borrow_mut().push(s.to_string()); } } - pub fn get_used_link_args<'a>(&'a self) -> &'a RefCell> { + pub(crate) fn get_used_link_args<'a>(&'a self) -> &'a RefCell> { &self.used_link_args } - pub fn add_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId, cnum: CrateNum) { + pub(crate) fn add_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId, cnum: CrateNum) { self.extern_mod_crate_map.borrow_mut().insert(emod_id, cnum); } - pub fn add_statically_included_foreign_item(&self, id: DefIndex) { + pub(crate) fn add_statically_included_foreign_item(&self, id: DefIndex) { self.statically_included_foreign_items.borrow_mut().insert(id); } - pub fn do_is_statically_included_foreign_item(&self, def_id: DefId) -> bool { + pub(crate) fn do_is_statically_included_foreign_item(&self, def_id: DefId) -> bool { assert!(def_id.krate == LOCAL_CRATE); self.statically_included_foreign_items.borrow().contains(&def_id.index) } - pub fn do_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option { + pub(crate) fn do_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option { self.extern_mod_crate_map.borrow().get(&emod_id).cloned() } - pub fn read_dep_node(&self, def_id: DefId) { + pub(crate) fn read_dep_node(&self, def_id: DefId) { use rustc::middle::cstore::CrateStore; let def_path_hash = self.def_path_hash(def_id); let dep_node = def_path_hash.to_dep_node(::rustc::dep_graph::DepKind::MetaData); @@ -265,22 +259,22 @@ impl CStore { } impl CrateMetadata { - pub fn name(&self) -> Symbol { + pub(crate) fn name(&self) -> Symbol { self.root.name } - pub fn hash(&self) -> Svh { + pub(crate) fn hash(&self) -> Svh { self.root.hash } - pub fn disambiguator(&self) -> Symbol { + pub(crate) fn disambiguator(&self) -> Symbol { self.root.disambiguator } - pub fn needs_allocator(&self, dep_graph: &DepGraph) -> bool { + pub(crate) fn needs_allocator(&self, dep_graph: &DepGraph) -> bool { let attrs = self.get_item_attrs(CRATE_DEF_INDEX, dep_graph); attr::contains_name(&attrs, "needs_allocator") } - pub fn has_global_allocator(&self, dep_graph: &DepGraph) -> bool { + pub(crate) fn has_global_allocator(&self, dep_graph: &DepGraph) -> bool { let dep_node = self.metadata_dep_node(GlobalMetaDataKind::Krate); self.root .has_global_allocator @@ -288,7 +282,7 @@ impl CrateMetadata { .clone() } - pub fn has_default_lib_allocator(&self, dep_graph: &DepGraph) -> bool { + pub(crate) fn has_default_lib_allocator(&self, dep_graph: &DepGraph) -> bool { let dep_node = self.metadata_dep_node(GlobalMetaDataKind::Krate); self.root .has_default_lib_allocator @@ -296,37 +290,37 @@ impl CrateMetadata { .clone() } - pub fn is_panic_runtime(&self, dep_graph: &DepGraph) -> bool { + pub(crate) fn is_panic_runtime(&self, dep_graph: &DepGraph) -> bool { let attrs = self.get_item_attrs(CRATE_DEF_INDEX, dep_graph); attr::contains_name(&attrs, "panic_runtime") } - pub fn needs_panic_runtime(&self, dep_graph: &DepGraph) -> bool { + pub(crate) fn needs_panic_runtime(&self, dep_graph: &DepGraph) -> bool { let attrs = self.get_item_attrs(CRATE_DEF_INDEX, dep_graph); attr::contains_name(&attrs, "needs_panic_runtime") } - pub fn is_compiler_builtins(&self, dep_graph: &DepGraph) -> bool { + pub(crate) fn is_compiler_builtins(&self, dep_graph: &DepGraph) -> bool { let attrs = self.get_item_attrs(CRATE_DEF_INDEX, dep_graph); attr::contains_name(&attrs, "compiler_builtins") } - pub fn is_sanitizer_runtime(&self, dep_graph: &DepGraph) -> bool { + pub(crate) fn is_sanitizer_runtime(&self, dep_graph: &DepGraph) -> bool { let attrs = self.get_item_attrs(CRATE_DEF_INDEX, dep_graph); attr::contains_name(&attrs, "sanitizer_runtime") } - pub fn is_profiler_runtime(&self, dep_graph: &DepGraph) -> bool { + pub(crate) fn is_profiler_runtime(&self, dep_graph: &DepGraph) -> bool { let attrs = self.get_item_attrs(CRATE_DEF_INDEX, dep_graph); attr::contains_name(&attrs, "profiler_runtime") } - pub fn is_no_builtins(&self, dep_graph: &DepGraph) -> bool { + pub(crate) fn is_no_builtins(&self, dep_graph: &DepGraph) -> bool { let attrs = self.get_item_attrs(CRATE_DEF_INDEX, dep_graph); attr::contains_name(&attrs, "no_builtins") } - pub fn panic_strategy(&self, dep_graph: &DepGraph) -> PanicStrategy { + pub(crate) fn panic_strategy(&self, dep_graph: &DepGraph) -> PanicStrategy { let dep_node = self.metadata_dep_node(GlobalMetaDataKind::Krate); self.root .panic_strategy diff --git a/src/librustc_metadata/decoder.rs b/src/librustc_metadata/decoder.rs index ad3a9dd9fefaf..11be2b5cb24bf 100644 --- a/src/librustc_metadata/decoder.rs +++ b/src/librustc_metadata/decoder.rs @@ -44,7 +44,7 @@ use syntax::codemap; use syntax::ext::base::MacroKind; use syntax_pos::{self, Span, BytePos, Pos, DUMMY_SP, NO_EXPANSION}; -pub struct DecodeContext<'a, 'tcx: 'a> { +pub(crate) struct DecodeContext<'a, 'tcx: 'a> { opaque: opaque::Decoder<'a>, cdata: Option<&'a CrateMetadata>, sess: Option<&'a Session>, @@ -57,7 +57,7 @@ pub struct DecodeContext<'a, 'tcx: 'a> { } /// Abstract over the various ways one can create metadata decoders. -pub trait Metadata<'a, 'tcx>: Copy { +pub(crate) trait Metadata<'a, 'tcx>: Copy { fn raw_bytes(self) -> &'a [u8]; fn cdata(self) -> Option<&'a CrateMetadata> { None } fn sess(self) -> Option<&'a Session> { None } @@ -116,7 +116,7 @@ impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, TyCtxt<'a, 'tcx, 'tcx> } impl<'a, 'tcx: 'a, T: Decodable> Lazy { - pub fn decode>(self, meta: M) -> T { + pub(crate) fn decode>(self, meta: M) -> T { let mut dcx = meta.decoder(self.position); dcx.lazy_state = LazyState::NodeStart(self.position); T::decode(&mut dcx).unwrap() @@ -124,7 +124,7 @@ impl<'a, 'tcx: 'a, T: Decodable> Lazy { } impl<'a, 'tcx: 'a, T: Decodable> LazySeq { - pub fn decode>(self, meta: M) -> impl Iterator + 'a { + pub(crate) fn decode>(self, meta: M) -> impl Iterator + 'a { let mut dcx = meta.decoder(self.position); dcx.lazy_state = LazyState::NodeStart(self.position); (0..self.len).map(move |_| T::decode(&mut dcx).unwrap()) @@ -132,11 +132,11 @@ impl<'a, 'tcx: 'a, T: Decodable> LazySeq { } impl<'a, 'tcx> DecodeContext<'a, 'tcx> { - pub fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { + pub(crate) fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { self.tcx.expect("missing TyCtxt in DecodeContext") } - pub fn cdata(&self) -> &'a CrateMetadata { + pub(crate) fn cdata(&self) -> &'a CrateMetadata { self.cdata.expect("missing CrateMetadata in DecodeContext") } @@ -379,15 +379,15 @@ impl<'a, 'tcx> SpecializedDecoder<&'tcx ty::Slice } impl<'a, 'tcx> MetadataBlob { - pub fn is_compatible(&self) -> bool { + pub(crate) fn is_compatible(&self) -> bool { self.raw_bytes().starts_with(METADATA_HEADER) } - pub fn get_rustc_version(&self) -> String { + pub(crate) fn get_rustc_version(&self) -> String { Lazy::with_position(METADATA_HEADER.len() + 4).decode(self) } - pub fn get_root(&self) -> CrateRoot { + pub(crate) fn get_root(&self) -> CrateRoot { let slice = self.raw_bytes(); let offset = METADATA_HEADER.len(); let pos = (((slice[offset + 0] as u32) << 24) | ((slice[offset + 1] as u32) << 16) | @@ -396,8 +396,7 @@ impl<'a, 'tcx> MetadataBlob { Lazy::with_position(pos).decode(self) } - pub fn list_crate_metadata(&self, - out: &mut io::Write) -> io::Result<()> { + pub(crate) fn list_crate_metadata(&self, out: &mut io::Write) -> io::Result<()> { write!(out, "=External Dependencies=\n")?; let root = self.get_root(); for (i, dep) in root.crate_deps @@ -472,7 +471,7 @@ impl<'a, 'tcx> CrateMetadata { } } - pub fn item_name(&self, item_index: DefIndex) -> ast::Name { + pub(crate) fn item_name(&self, item_index: DefIndex) -> ast::Name { self.def_key(item_index) .disambiguated_data .data @@ -480,7 +479,7 @@ impl<'a, 'tcx> CrateMetadata { .expect("no name in item_name") } - pub fn get_def(&self, index: DefIndex) -> Option { + pub(crate) fn get_def(&self, index: DefIndex) -> Option { if !self.is_proc_macro(index) { self.entry(index).kind.to_def(self.local_def_id(index)) } else { @@ -489,14 +488,14 @@ impl<'a, 'tcx> CrateMetadata { } } - pub fn get_span(&self, index: DefIndex, sess: &Session) -> Span { + pub(crate) fn get_span(&self, index: DefIndex, sess: &Session) -> Span { match self.is_proc_macro(index) { true => DUMMY_SP, false => self.entry(index).span.decode((self, sess)), } } - pub fn get_trait_def(&self, item_id: DefIndex) -> ty::TraitDef { + pub(crate) fn get_trait_def(&self, item_id: DefIndex) -> ty::TraitDef { let data = match self.entry(item_id).kind { EntryKind::Trait(data) => data.decode(self), _ => bug!(), @@ -533,10 +532,10 @@ impl<'a, 'tcx> CrateMetadata { } } - pub fn get_adt_def(&self, - item_id: DefIndex, - tcx: TyCtxt<'a, 'tcx, 'tcx>) - -> &'tcx ty::AdtDef { + pub(crate) fn get_adt_def(&self, + item_id: DefIndex, + tcx: TyCtxt<'a, 'tcx, 'tcx>) + -> &'tcx ty::AdtDef { let item = self.entry(item_id); let did = self.local_def_id(item_id); let kind = match item.kind { @@ -565,46 +564,46 @@ impl<'a, 'tcx> CrateMetadata { tcx.alloc_adt_def(did, kind, variants, repr) } - pub fn get_predicates(&self, - item_id: DefIndex, - tcx: TyCtxt<'a, 'tcx, 'tcx>) - -> ty::GenericPredicates<'tcx> { + pub(crate) fn get_predicates(&self, + item_id: DefIndex, + tcx: TyCtxt<'a, 'tcx, 'tcx>) + -> ty::GenericPredicates<'tcx> { self.entry(item_id).predicates.unwrap().decode((self, tcx)) } - pub fn get_super_predicates(&self, - item_id: DefIndex, - tcx: TyCtxt<'a, 'tcx, 'tcx>) - -> ty::GenericPredicates<'tcx> { + pub(crate) fn get_super_predicates(&self, + item_id: DefIndex, + tcx: TyCtxt<'a, 'tcx, 'tcx>) + -> ty::GenericPredicates<'tcx> { match self.entry(item_id).kind { EntryKind::Trait(data) => data.decode(self).super_predicates.decode((self, tcx)), _ => bug!(), } } - pub fn get_generics(&self, item_id: DefIndex) -> ty::Generics { + pub(crate) fn get_generics(&self, item_id: DefIndex) -> ty::Generics { self.entry(item_id).generics.unwrap().decode(self) } - pub fn get_type(&self, id: DefIndex, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> { + pub(crate) fn get_type(&self, id: DefIndex, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> { self.entry(id).ty.unwrap().decode((self, tcx)) } - pub fn get_stability(&self, id: DefIndex) -> Option { + pub(crate) fn get_stability(&self, id: DefIndex) -> Option { match self.is_proc_macro(id) { true => None, false => self.entry(id).stability.map(|stab| stab.decode(self)), } } - pub fn get_deprecation(&self, id: DefIndex) -> Option { + pub(crate) fn get_deprecation(&self, id: DefIndex) -> Option { match self.is_proc_macro(id) { true => None, false => self.entry(id).deprecation.map(|depr| depr.decode(self)), } } - pub fn get_visibility(&self, id: DefIndex) -> ty::Visibility { + pub(crate) fn get_visibility(&self, id: DefIndex) -> ty::Visibility { match self.is_proc_macro(id) { true => ty::Visibility::Public, false => self.entry(id).visibility.decode(self), @@ -618,33 +617,33 @@ impl<'a, 'tcx> CrateMetadata { } } - pub fn get_parent_impl(&self, id: DefIndex) -> Option { + pub(crate) fn get_parent_impl(&self, id: DefIndex) -> Option { self.get_impl_data(id).parent_impl } - pub fn get_impl_polarity(&self, id: DefIndex) -> hir::ImplPolarity { + pub(crate) fn get_impl_polarity(&self, id: DefIndex) -> hir::ImplPolarity { self.get_impl_data(id).polarity } - pub fn get_impl_defaultness(&self, id: DefIndex) -> hir::Defaultness { + pub(crate) fn get_impl_defaultness(&self, id: DefIndex) -> hir::Defaultness { self.get_impl_data(id).defaultness } - pub fn get_coerce_unsized_info(&self, - id: DefIndex) - -> Option { + pub(crate) fn get_coerce_unsized_info(&self, + id: DefIndex) + -> Option { self.get_impl_data(id).coerce_unsized_info } - pub fn get_impl_trait(&self, - id: DefIndex, - tcx: TyCtxt<'a, 'tcx, 'tcx>) - -> Option> { + pub(crate) fn get_impl_trait(&self, + id: DefIndex, + tcx: TyCtxt<'a, 'tcx, 'tcx>) + -> Option> { self.get_impl_data(id).trait_ref.map(|tr| tr.decode((self, tcx))) } /// Iterates over the language items in the given crate. - pub fn get_lang_items(&self, dep_graph: &DepGraph) -> Vec<(DefIndex, usize)> { + pub(crate) fn get_lang_items(&self, dep_graph: &DepGraph) -> Vec<(DefIndex, usize)> { let dep_node = self.metadata_dep_node(GlobalMetaDataKind::LangItems); self.root .lang_items @@ -654,7 +653,7 @@ impl<'a, 'tcx> CrateMetadata { } /// Iterates over each child of the given item. - pub fn each_child_of_item(&self, id: DefIndex, mut callback: F, sess: &Session) + pub(crate) fn each_child_of_item(&self, id: DefIndex, mut callback: F, sess: &Session) where F: FnMut(def::Export) { if let Some(ref proc_macros) = self.proc_macros { @@ -758,10 +757,10 @@ impl<'a, 'tcx> CrateMetadata { } } - pub fn item_body(&self, - tcx: TyCtxt<'a, 'tcx, 'tcx>, - id: DefIndex) - -> &'tcx hir::Body { + pub(crate) fn item_body(&self, + tcx: TyCtxt<'a, 'tcx, 'tcx>, + id: DefIndex) + -> &'tcx hir::Body { assert!(!self.is_proc_macro(id)); let ast = self.entry(id).ast.unwrap(); let def_id = self.local_def_id(id); @@ -769,41 +768,41 @@ impl<'a, 'tcx> CrateMetadata { tcx.hir.intern_inlined_body(def_id, body) } - pub fn item_body_tables(&self, - id: DefIndex, - tcx: TyCtxt<'a, 'tcx, 'tcx>) - -> &'tcx ty::TypeckTables<'tcx> { + pub(crate) fn item_body_tables(&self, + id: DefIndex, + tcx: TyCtxt<'a, 'tcx, 'tcx>) + -> &'tcx ty::TypeckTables<'tcx> { let ast = self.entry(id).ast.unwrap().decode(self); tcx.alloc_tables(ast.tables.decode((self, tcx))) } - pub fn item_body_nested_bodies(&self, id: DefIndex) -> BTreeMap { + pub(crate) fn item_body_nested_bodies(&self, id: DefIndex) -> BTreeMap { self.entry(id).ast.into_iter().flat_map(|ast| { ast.decode(self).nested_bodies.decode(self).map(|body| (body.id(), body)) }).collect() } - pub fn const_is_rvalue_promotable_to_static(&self, id: DefIndex) -> bool { + pub(crate) fn const_is_rvalue_promotable_to_static(&self, id: DefIndex) -> bool { self.entry(id).ast.expect("const item missing `ast`") .decode(self).rvalue_promotable_to_static } - pub fn is_item_mir_available(&self, id: DefIndex) -> bool { + pub(crate) fn is_item_mir_available(&self, id: DefIndex) -> bool { !self.is_proc_macro(id) && self.maybe_entry(id).and_then(|item| item.decode(self).mir).is_some() } - pub fn maybe_get_optimized_mir(&self, - tcx: TyCtxt<'a, 'tcx, 'tcx>, - id: DefIndex) - -> Option> { + pub(crate) fn maybe_get_optimized_mir(&self, + tcx: TyCtxt<'a, 'tcx, 'tcx>, + id: DefIndex) + -> Option> { match self.is_proc_macro(id) { true => None, false => self.entry(id).mir.map(|mir| mir.decode((self, tcx))), } } - pub fn mir_const_qualif(&self, id: DefIndex) -> u8 { + pub(crate) fn mir_const_qualif(&self, id: DefIndex) -> u8 { match self.entry(id).kind { EntryKind::Const(qualif) | EntryKind::AssociatedConst(AssociatedContainer::ImplDefault, qualif) | @@ -814,7 +813,7 @@ impl<'a, 'tcx> CrateMetadata { } } - pub fn get_associated_item(&self, id: DefIndex) -> ty::AssociatedItem { + pub(crate) fn get_associated_item(&self, id: DefIndex) -> ty::AssociatedItem { let item = self.entry(id); let def_key = self.def_key(id); let parent = self.local_def_id(def_key.parent.unwrap()); @@ -845,11 +844,11 @@ impl<'a, 'tcx> CrateMetadata { } } - pub fn get_item_variances(&self, id: DefIndex) -> Vec { + pub(crate) fn get_item_variances(&self, id: DefIndex) -> Vec { self.entry(id).variances.decode(self).collect() } - pub fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind { + pub(crate) fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind { match self.entry(node_id).kind { EntryKind::Struct(data, _) | EntryKind::Union(data, _) | @@ -858,7 +857,7 @@ impl<'a, 'tcx> CrateMetadata { } } - pub fn get_struct_ctor_def_id(&self, node_id: DefIndex) -> Option { + pub(crate) fn get_struct_ctor_def_id(&self, node_id: DefIndex) -> Option { match self.entry(node_id).kind { EntryKind::Struct(data, _) => { data.decode(self).struct_ctor.map(|index| self.local_def_id(index)) @@ -867,9 +866,9 @@ impl<'a, 'tcx> CrateMetadata { } } - pub fn get_item_attrs(&self, - node_id: DefIndex, - dep_graph: &DepGraph) -> Rc<[ast::Attribute]> { + pub(crate) fn get_item_attrs(&self, + node_id: DefIndex, + dep_graph: &DepGraph) -> Rc<[ast::Attribute]> { let (node_as, node_index) = (node_id.address_space().index(), node_id.as_array_index()); if self.is_proc_macro(node_id) { @@ -901,7 +900,7 @@ impl<'a, 'tcx> CrateMetadata { result } - pub fn get_struct_field_names(&self, id: DefIndex) -> Vec { + pub(crate) fn get_struct_field_names(&self, id: DefIndex) -> Vec { self.entry(id) .children .decode(self) @@ -935,7 +934,7 @@ impl<'a, 'tcx> CrateMetadata { None } - pub fn get_inherent_implementations_for_type(&self, id: DefIndex) -> Vec { + pub(crate) fn get_inherent_implementations_for_type(&self, id: DefIndex) -> Vec { self.entry(id) .inherent_impls .decode(self) @@ -943,10 +942,10 @@ impl<'a, 'tcx> CrateMetadata { .collect() } - pub fn get_implementations_for_trait(&self, - filter: Option, - dep_graph: &DepGraph, - result: &mut Vec) { + pub(crate) fn get_implementations_for_trait(&self, + filter: Option, + dep_graph: &DepGraph, + result: &mut Vec) { // Do a reverse lookup beforehand to avoid touching the crate_num // hash map in the loop below. let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) { @@ -971,7 +970,7 @@ impl<'a, 'tcx> CrateMetadata { } } - pub fn get_trait_of_item(&self, id: DefIndex) -> Option { + pub(crate) fn get_trait_of_item(&self, id: DefIndex) -> Option { self.def_key(id).parent.and_then(|parent_index| { match self.entry(parent_index).kind { EntryKind::Trait(_) => Some(self.local_def_id(parent_index)), @@ -981,9 +980,7 @@ impl<'a, 'tcx> CrateMetadata { } - pub fn get_native_libraries(&self, - dep_graph: &DepGraph) - -> Vec { + pub(crate) fn get_native_libraries(&self, dep_graph: &DepGraph) -> Vec { let dep_node = self.metadata_dep_node(GlobalMetaDataKind::NativeLibraries); self.root .native_libraries @@ -992,9 +989,9 @@ impl<'a, 'tcx> CrateMetadata { .collect() } - pub fn get_dylib_dependency_formats(&self, - dep_graph: &DepGraph) - -> Vec<(CrateNum, LinkagePreference)> { + pub(crate) fn get_dylib_dependency_formats(&self, + dep_graph: &DepGraph) + -> Vec<(CrateNum, LinkagePreference)> { let dep_node = self.metadata_dep_node(GlobalMetaDataKind::DylibDependencyFormats); self.root @@ -1009,7 +1006,7 @@ impl<'a, 'tcx> CrateMetadata { .collect() } - pub fn get_missing_lang_items(&self, dep_graph: &DepGraph) -> Vec { + pub(crate) fn get_missing_lang_items(&self, dep_graph: &DepGraph) -> Vec { let dep_node = self.metadata_dep_node(GlobalMetaDataKind::LangItemsMissing); self.root .lang_items_missing @@ -1018,7 +1015,7 @@ impl<'a, 'tcx> CrateMetadata { .collect() } - pub fn get_fn_arg_names(&self, id: DefIndex) -> Vec { + pub(crate) fn get_fn_arg_names(&self, id: DefIndex) -> Vec { let arg_names = match self.entry(id).kind { EntryKind::Fn(data) | EntryKind::ForeignFn(data) => data.decode(self).arg_names, @@ -1028,7 +1025,7 @@ impl<'a, 'tcx> CrateMetadata { arg_names.decode(self).collect() } - pub fn get_exported_symbols(&self, dep_graph: &DepGraph) -> Vec { + pub(crate) fn get_exported_symbols(&self, dep_graph: &DepGraph) -> Vec { let dep_node = self.metadata_dep_node(GlobalMetaDataKind::ExportedSymbols); self.exported_symbols .get(dep_graph, dep_node) @@ -1037,7 +1034,7 @@ impl<'a, 'tcx> CrateMetadata { .collect() } - pub fn get_macro(&self, id: DefIndex) -> (ast::Name, MacroDef) { + pub(crate) fn get_macro(&self, id: DefIndex) -> (ast::Name, MacroDef) { let entry = self.entry(id); match entry.kind { EntryKind::MacroDef(macro_def) => (self.item_name(id), macro_def.decode(self)), @@ -1045,7 +1042,7 @@ impl<'a, 'tcx> CrateMetadata { } } - pub fn is_const_fn(&self, id: DefIndex) -> bool { + pub(crate) fn is_const_fn(&self, id: DefIndex) -> bool { let constness = match self.entry(id).kind { EntryKind::Method(data) => data.decode(self).fn_data.constness, EntryKind::Fn(data) => data.decode(self).constness, @@ -1054,7 +1051,7 @@ impl<'a, 'tcx> CrateMetadata { constness == hir::Constness::Const } - pub fn is_foreign_item(&self, id: DefIndex) -> bool { + pub(crate) fn is_foreign_item(&self, id: DefIndex) -> bool { match self.entry(id).kind { EntryKind::ForeignImmStatic | EntryKind::ForeignMutStatic | @@ -1063,31 +1060,31 @@ impl<'a, 'tcx> CrateMetadata { } } - pub fn is_dllimport_foreign_item(&self, id: DefIndex, dep_graph: &DepGraph) -> bool { + pub(crate) fn is_dllimport_foreign_item(&self, id: DefIndex, dep_graph: &DepGraph) -> bool { let dep_node = self.metadata_dep_node(GlobalMetaDataKind::NativeLibraries); self.dllimport_foreign_items .get(dep_graph, dep_node) .contains(&id) } - pub fn is_default_impl(&self, impl_id: DefIndex) -> bool { + pub(crate) fn is_default_impl(&self, impl_id: DefIndex) -> bool { match self.entry(impl_id).kind { EntryKind::DefaultImpl(_) => true, _ => false, } } - pub fn closure_kind(&self, closure_id: DefIndex) -> ty::ClosureKind { + pub(crate) fn closure_kind(&self, closure_id: DefIndex) -> ty::ClosureKind { match self.entry(closure_id).kind { EntryKind::Closure(data) => data.decode(self).kind, _ => bug!(), } } - pub fn fn_sig(&self, - id: DefIndex, - tcx: TyCtxt<'a, 'tcx, 'tcx>) - -> ty::PolyFnSig<'tcx> { + pub(crate) fn fn_sig(&self, + id: DefIndex, + tcx: TyCtxt<'a, 'tcx, 'tcx>) + -> ty::PolyFnSig<'tcx> { let sig = match self.entry(id).kind { EntryKind::Fn(data) | EntryKind::ForeignFn(data) => data.decode(self).sig, @@ -1101,18 +1098,18 @@ impl<'a, 'tcx> CrateMetadata { } #[inline] - pub fn def_key(&self, index: DefIndex) -> DefKey { + pub(crate) fn def_key(&self, index: DefIndex) -> DefKey { self.def_path_table.def_key(index) } // Returns the path leading to the thing with this `id`. - pub fn def_path(&self, id: DefIndex) -> DefPath { + pub(crate) fn def_path(&self, id: DefIndex) -> DefPath { debug!("def_path(id={:?})", id); DefPath::make(self.cnum, id, |parent| self.def_path_table.def_key(parent)) } #[inline] - pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash { + pub(crate) fn def_path_hash(&self, index: DefIndex) -> DefPathHash { self.def_path_table.def_path_hash(index) } @@ -1138,9 +1135,9 @@ impl<'a, 'tcx> CrateMetadata { /// file they represent, just information about length, line breaks, and /// multibyte characters. This information is enough to generate valid debuginfo /// for items inlined from other crates. - pub fn imported_filemaps(&'a self, - local_codemap: &codemap::CodeMap) - -> Ref<'a, Vec> { + pub(crate) fn imported_filemaps(&'a self, + local_codemap: &codemap::CodeMap) + -> Ref<'a, Vec> { { let filemaps = self.codemap_import_info.borrow(); if !filemaps.is_empty() { @@ -1203,7 +1200,7 @@ impl<'a, 'tcx> CrateMetadata { self.codemap_import_info.borrow() } - pub fn metadata_dep_node(&self, kind: GlobalMetaDataKind) -> DepNode { + pub(crate) fn metadata_dep_node(&self, kind: GlobalMetaDataKind) -> DepNode { let def_index = kind.def_index(&self.def_path_table); let def_path_hash = self.def_path_table.def_path_hash(def_index); def_path_hash.to_dep_node(DepKind::MetaData) diff --git a/src/librustc_metadata/encoder.rs b/src/librustc_metadata/encoder.rs index 5d73abc3ee8b8..0bf1138199621 100644 --- a/src/librustc_metadata/encoder.rs +++ b/src/librustc_metadata/encoder.rs @@ -49,9 +49,9 @@ use rustc::hir::itemlikevisit::ItemLikeVisitor; use rustc::hir::intravisit::{Visitor, NestedVisitorMap}; use rustc::hir::intravisit; -pub struct EncodeContext<'a, 'tcx: 'a> { +pub(crate) struct EncodeContext<'a, 'tcx: 'a> { opaque: opaque::Encoder<'a>, - pub tcx: TyCtxt<'a, 'tcx, 'tcx>, + pub(crate) tcx: TyCtxt<'a, 'tcx, 'tcx>, link_meta: &'a LinkMeta, exported_symbols: &'a NodeSet, @@ -59,8 +59,8 @@ pub struct EncodeContext<'a, 'tcx: 'a> { type_shorthands: FxHashMap, usize>, predicate_shorthands: FxHashMap, usize>, - pub metadata_hashes: EncodedMetadataHashes, - pub compute_ich: bool, + pub(crate) metadata_hashes: EncodedMetadataHashes, + pub(crate) compute_ich: bool, } macro_rules! encoder_methods { @@ -138,7 +138,7 @@ impl<'a, 'tcx> SpecializedEncoder> for EncodeContext impl<'a, 'tcx> EncodeContext<'a, 'tcx> { - pub fn position(&self) -> usize { + pub(crate) fn position(&self) -> usize { self.opaque.position() } @@ -171,7 +171,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { self.emit_usize(distance) } - pub fn lazy(&mut self, value: &T) -> Lazy { + pub(crate) fn lazy(&mut self, value: &T) -> Lazy { self.emit_node(|ecx, pos| { value.encode(ecx).unwrap(); @@ -180,7 +180,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { }) } - pub fn lazy_seq(&mut self, iter: I) -> LazySeq + pub(crate) fn lazy_seq(&mut self, iter: I) -> LazySeq where I: IntoIterator, T: Encodable { @@ -192,7 +192,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { }) } - pub fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq + pub(crate) fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq where I: IntoIterator, T: 'b + Encodable { @@ -244,11 +244,11 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { // Encodes something that corresponds to a single DepNode::GlobalMetaData // and registers the Fingerprint in the `metadata_hashes` map. - pub fn tracked<'x, DATA, R>(&'x mut self, - def_index: DefIndex, - op: fn(&mut IsolatedEncoder<'x, 'a, 'tcx>, DATA) -> R, - data: DATA) - -> Tracked { + pub(crate) fn tracked<'x, DATA, R>(&'x mut self, + def_index: DefIndex, + op: fn(&mut IsolatedEncoder<'x, 'a, 'tcx>, DATA) -> R, + data: DATA) + -> Tracked { let mut entry_builder = IsolatedEncoder::new(self); let ret = op(&mut entry_builder, data); let (fingerprint, this) = entry_builder.finish(); @@ -1635,10 +1635,10 @@ impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> { // will allow us to slice the metadata to the precise length that we just // generated regardless of trailing bytes that end up in it. -pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - link_meta: &LinkMeta, - exported_symbols: &NodeSet) - -> EncodedMetadata +pub(crate) fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, + link_meta: &LinkMeta, + exported_symbols: &NodeSet) + -> EncodedMetadata { let mut cursor = Cursor::new(vec![]); cursor.write_all(METADATA_HEADER).unwrap(); @@ -1687,7 +1687,8 @@ pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } } -pub fn get_repr_options<'a, 'tcx, 'gcx>(tcx: &TyCtxt<'a, 'tcx, 'gcx>, did: DefId) -> ReprOptions { +pub(crate) fn get_repr_options<'a, 'tcx, 'gcx>(tcx: &TyCtxt<'a, 'tcx, 'gcx>, did: DefId) + -> ReprOptions { let ty = tcx.type_of(did); match ty.sty { ty::TyAdt(ref def, _) => return def.repr, diff --git a/src/librustc_metadata/index.rs b/src/librustc_metadata/index.rs index ebf9910e9c99c..baa7e78879d89 100644 --- a/src/librustc_metadata/index.rs +++ b/src/librustc_metadata/index.rs @@ -22,24 +22,24 @@ use std::u32; /// `u32::MAX`. Whenever an index is visited, we fill in the /// appropriate spot by calling `record_position`. We should never /// visit the same index twice. -pub struct Index { +pub(crate) struct Index { positions: [Vec; 2] } impl Index { - pub fn new((max_index_lo, max_index_hi): (usize, usize)) -> Index { + pub(crate) fn new((max_index_lo, max_index_hi): (usize, usize)) -> Index { Index { positions: [vec![u32::MAX; max_index_lo], vec![u32::MAX; max_index_hi]], } } - pub fn record(&mut self, def_id: DefId, entry: Lazy) { + pub(crate) fn record(&mut self, def_id: DefId, entry: Lazy) { assert!(def_id.is_local()); self.record_index(def_id.index, entry); } - pub fn record_index(&mut self, item: DefIndex, entry: Lazy) { + pub(crate) fn record_index(&mut self, item: DefIndex, entry: Lazy) { assert!(entry.position < (u32::MAX as usize)); let position = entry.position as u32; let space_index = item.address_space().index(); @@ -54,7 +54,7 @@ impl Index { self.positions[space_index][array_index] = position.to_le(); } - pub fn write_index(&self, buf: &mut Cursor>) -> LazySeq { + pub(crate) fn write_index(&self, buf: &mut Cursor>) -> LazySeq { let pos = buf.position(); // First we write the length of the lower range ... @@ -72,7 +72,7 @@ impl<'tcx> LazySeq { /// Given the metadata, extract out the offset of a particular /// DefIndex (if any). #[inline(never)] - pub fn lookup(&self, bytes: &[u8], def_index: DefIndex) -> Option>> { + pub(crate) fn lookup(&self, bytes: &[u8], def_index: DefIndex) -> Option>> { let words = &bytes_to_words(&bytes[self.position..])[..self.len]; let index = def_index.as_usize(); @@ -100,32 +100,6 @@ impl<'tcx> LazySeq { Some(Lazy::with_position(position as usize)) } } - - pub fn iter_enumerated<'a>(&self, - bytes: &'a [u8]) - -> impl Iterator>)> + 'a { - let words = &bytes_to_words(&bytes[self.position..])[..self.len]; - let lo_count = u32::from_le(words[0].get()) as usize; - let lo = &words[1 .. lo_count + 1]; - let hi = &words[1 + lo_count ..]; - - lo.iter().map(|word| word.get()).enumerate().filter_map(|(index, pos)| { - if pos == u32::MAX { - None - } else { - let pos = u32::from_le(pos) as usize; - Some((DefIndex::new(index), Lazy::with_position(pos))) - } - }).chain(hi.iter().map(|word| word.get()).enumerate().filter_map(|(index, pos)| { - if pos == u32::MAX { - None - } else { - let pos = u32::from_le(pos) as usize; - Some((DefIndex::new(index + DefIndexAddressSpace::High.start()), - Lazy::with_position(pos))) - } - })) - } } #[repr(packed)] diff --git a/src/librustc_metadata/index_builder.rs b/src/librustc_metadata/index_builder.rs index 2db9c6a4ff811..0c4bd69a28b28 100644 --- a/src/librustc_metadata/index_builder.rs +++ b/src/librustc_metadata/index_builder.rs @@ -70,9 +70,9 @@ use std::ops::{Deref, DerefMut}; /// Builder that can encode new items, adding them into the index. /// Item encoding cannot be nested. -pub struct IndexBuilder<'a, 'b: 'a, 'tcx: 'b> { +pub(crate) struct IndexBuilder<'a, 'b: 'a, 'tcx: 'b> { items: Index, - pub ecx: &'a mut EncodeContext<'b, 'tcx>, + pub(crate) ecx: &'a mut EncodeContext<'b, 'tcx>, } impl<'a, 'b, 'tcx> Deref for IndexBuilder<'a, 'b, 'tcx> { @@ -89,7 +89,7 @@ impl<'a, 'b, 'tcx> DerefMut for IndexBuilder<'a, 'b, 'tcx> { } impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> { - pub fn new(ecx: &'a mut EncodeContext<'b, 'tcx>) -> Self { + pub(crate) fn new(ecx: &'a mut EncodeContext<'b, 'tcx>) -> Self { IndexBuilder { items: Index::new(ecx.tcx.hir.definitions().def_index_counts_lo_hi()), ecx: ecx, @@ -113,10 +113,10 @@ impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> { /// holds, and that it is therefore not gaining "secret" access to /// bits of HIR or other state that would not be trackd by the /// content system. - pub fn record<'x, DATA>(&'x mut self, - id: DefId, - op: fn(&mut IsolatedEncoder<'x, 'b, 'tcx>, DATA) -> Entry<'tcx>, - data: DATA) + pub(crate) fn record<'x, DATA>(&'x mut self, + id: DefId, + op: fn(&mut IsolatedEncoder<'x, 'b, 'tcx>, DATA) -> Entry<'tcx>, + data: DATA) where DATA: DepGraphRead { assert!(id.is_local()); @@ -144,7 +144,7 @@ impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> { self.items.record(id, entry); } - pub fn into_items(self) -> Index { + pub(crate) fn into_items(self) -> Index { self.items } } @@ -153,7 +153,7 @@ impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> { /// task. The data must either be of some safe type, such as a /// `DefId` index, or implement the `read` method so that it can add /// a read of whatever dep-graph nodes are appropriate. -pub trait DepGraphRead { +pub(crate) trait DepGraphRead { fn read(&self, tcx: TyCtxt); } @@ -226,7 +226,7 @@ read_hir!(hir::MacroDef); /// /// A good idea is to add to each use of `Untracked` an explanation of /// why this value is ok. -pub struct Untracked(pub T); +pub(crate) struct Untracked(pub(crate) T); impl DepGraphRead for Untracked { fn read(&self, _tcx: TyCtxt) {} @@ -236,7 +236,7 @@ impl DepGraphRead for Untracked { /// HIR node that doesn't carry its own id. This will allow an /// arbitrary `T` to be passed in, but register a read on the given /// node-id. -pub struct FromId(pub ast::NodeId, pub T); +pub(crate) struct FromId(pub(crate) ast::NodeId, pub(crate) T); impl DepGraphRead for FromId { fn read(&self, tcx: TyCtxt) { diff --git a/src/librustc_metadata/isolated_encoder.rs b/src/librustc_metadata/isolated_encoder.rs index c4116489357af..9706895016955 100644 --- a/src/librustc_metadata/isolated_encoder.rs +++ b/src/librustc_metadata/isolated_encoder.rs @@ -20,15 +20,15 @@ use rustc_serialize::Encodable; /// The IsolatedEncoder provides facilities to write to crate metadata while /// making sure that anything going through it is also feed into an ICH hasher. -pub struct IsolatedEncoder<'a, 'b: 'a, 'tcx: 'b> { - pub tcx: TyCtxt<'b, 'tcx, 'tcx>, +pub(crate) struct IsolatedEncoder<'a, 'b: 'a, 'tcx: 'b> { + pub(crate) tcx: TyCtxt<'b, 'tcx, 'tcx>, ecx: &'a mut EncodeContext<'b, 'tcx>, hcx: Option<(StableHashingContext<'b, 'tcx, 'tcx>, StableHasher)>, } impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> { - pub fn new(ecx: &'a mut EncodeContext<'b, 'tcx>) -> Self { + pub(crate) fn new(ecx: &'a mut EncodeContext<'b, 'tcx>) -> Self { let tcx = ecx.tcx; let compute_ich = ecx.compute_ich; IsolatedEncoder { @@ -52,7 +52,7 @@ impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> { } } - pub fn finish(self) -> (Option, &'a mut EncodeContext<'b, 'tcx>) { + pub(crate) fn finish(self) -> (Option, &'a mut EncodeContext<'b, 'tcx>) { if let Some((_, hasher)) = self.hcx { (Some(hasher.finish()), self.ecx) } else { @@ -60,7 +60,7 @@ impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> { } } - pub fn lazy(&mut self, value: &T) -> Lazy + pub(crate) fn lazy(&mut self, value: &T) -> Lazy where T: Encodable + HashStable> { if let Some((ref mut hcx, ref mut hasher)) = self.hcx { @@ -70,7 +70,7 @@ impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> { self.ecx.lazy(value) } - pub fn lazy_seq(&mut self, iter: I) -> LazySeq + pub(crate) fn lazy_seq(&mut self, iter: I) -> LazySeq where I: IntoIterator, T: Encodable + HashStable> { @@ -109,7 +109,7 @@ impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> { } } - pub fn lazy_seq_ref<'x, I, T>(&mut self, iter: I) -> LazySeq + pub(crate) fn lazy_seq_ref<'x, I, T>(&mut self, iter: I) -> LazySeq where I: IntoIterator, T: 'x + Encodable + HashStable> { @@ -148,7 +148,7 @@ impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> { } } - pub fn lazy_seq_from_slice(&mut self, slice: &[T]) -> LazySeq + pub(crate) fn lazy_seq_from_slice(&mut self, slice: &[T]) -> LazySeq where T: Encodable + HashStable> { if let Some((ref mut hcx, ref mut hasher)) = self.hcx { @@ -158,7 +158,7 @@ impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> { self.ecx.lazy_seq_ref(slice.iter()) } - pub fn lazy_seq_ref_from_slice(&mut self, slice: &[&T]) -> LazySeq + pub(crate) fn lazy_seq_ref_from_slice(&mut self, slice: &[&T]) -> LazySeq where T: Encodable + HashStable> { if let Some((ref mut hcx, ref mut hasher)) = self.hcx { diff --git a/src/librustc_metadata/lib.rs b/src/librustc_metadata/lib.rs index 99b718ea07b1e..8fd87ae88a884 100644 --- a/src/librustc_metadata/lib.rs +++ b/src/librustc_metadata/lib.rs @@ -47,8 +47,6 @@ extern crate rustc_data_structures; mod diagnostics; -pub use rustc::middle; - mod astencode; mod index_builder; mod index; diff --git a/src/librustc_metadata/locator.rs b/src/librustc_metadata/locator.rs index 9bcf590eb8bb3..33152fd5e88b2 100644 --- a/src/librustc_metadata/locator.rs +++ b/src/librustc_metadata/locator.rs @@ -245,37 +245,37 @@ use std::time::Instant; use flate2::read::DeflateDecoder; use owning_ref::{ErasedBoxRef, OwningRef}; -pub struct CrateMismatch { +pub(crate) struct CrateMismatch { path: PathBuf, got: String, } -pub struct Context<'a> { - pub sess: &'a Session, - pub span: Span, - pub ident: Symbol, - pub crate_name: Symbol, - pub hash: Option<&'a Svh>, +pub(crate) struct Context<'a> { + pub(crate) sess: &'a Session, + pub(crate) span: Span, + pub(crate) ident: Symbol, + pub(crate) crate_name: Symbol, + pub(crate) hash: Option<&'a Svh>, // points to either self.sess.target.target or self.sess.host, must match triple - pub target: &'a Target, - pub triple: &'a str, - pub filesearch: FileSearch<'a>, - pub root: &'a Option, - pub rejected_via_hash: Vec, - pub rejected_via_triple: Vec, - pub rejected_via_kind: Vec, - pub rejected_via_version: Vec, - pub rejected_via_filename: Vec, - pub should_match_name: bool, - pub is_proc_macro: Option, - pub metadata_loader: &'a MetadataLoader, + pub(crate) target: &'a Target, + pub(crate) triple: &'a str, + pub(crate) filesearch: FileSearch<'a>, + pub(crate) root: &'a Option, + pub(crate) rejected_via_hash: Vec, + pub(crate) rejected_via_triple: Vec, + pub(crate) rejected_via_kind: Vec, + pub(crate) rejected_via_version: Vec, + pub(crate) rejected_via_filename: Vec, + pub(crate) should_match_name: bool, + pub(crate) is_proc_macro: Option, + pub(crate) metadata_loader: &'a MetadataLoader, } -pub struct CratePaths { - pub ident: String, - pub dylib: Option, - pub rlib: Option, - pub rmeta: Option, +pub(crate) struct CratePaths { + pub(crate) ident: String, + pub(crate) dylib: Option, + pub(crate) rlib: Option, + pub(crate) rmeta: Option, } #[derive(Copy, Clone, PartialEq)] @@ -302,15 +302,11 @@ impl CratePaths { } impl<'a> Context<'a> { - pub fn maybe_load_library_crate(&mut self) -> Option { + pub(crate) fn maybe_load_library_crate(&mut self) -> Option { self.find_library_crate() } - pub fn load_library_crate(&mut self) -> Library { - self.find_library_crate().unwrap_or_else(|| self.report_errs()) - } - - pub fn report_errs(&mut self) -> ! { + pub(crate) fn report_errs(&mut self) -> ! { let add = match self.root { &None => String::new(), &Some(ref r) => format!(" which `{}` depends on", r.ident), @@ -819,7 +815,7 @@ impl<'a> Context<'a> { } } -pub fn note_crate_name(err: &mut DiagnosticBuilder, name: &str) { +pub(crate) fn note_crate_name(err: &mut DiagnosticBuilder, name: &str) { err.note(&format!("crate name: {}", name)); } diff --git a/src/librustc_metadata/schema.rs b/src/librustc_metadata/schema.rs index 0b670121ba23b..fd4001114f645 100644 --- a/src/librustc_metadata/schema.rs +++ b/src/librustc_metadata/schema.rs @@ -34,7 +34,7 @@ use rustc_data_structures::stable_hasher::{StableHasher, HashStable, use rustc::dep_graph::{DepGraph, DepNode}; -pub fn rustc_version() -> String { +pub(crate) fn rustc_version() -> String { format!("rustc {}", option_env!("CFG_VERSION").unwrap_or("unknown version")) } @@ -42,7 +42,7 @@ pub fn rustc_version() -> String { /// Metadata encoding version. /// NB: increment this if you change the format of metadata such that /// the rustc version can't be found to compare with `rustc_version()`. -pub const METADATA_VERSION: u8 = 4; +pub(crate) const METADATA_VERSION: u8 = 4; /// Metadata header which includes `METADATA_VERSION`. /// To get older versions of rustc to ignore this metadata, @@ -52,13 +52,13 @@ pub const METADATA_VERSION: u8 = 4; /// This header is followed by the position of the `CrateRoot`, /// which is encoded as a 32-bit big-endian unsigned integer, /// and further followed by the rustc version string. -pub const METADATA_HEADER: &'static [u8; 12] = +pub(crate) const METADATA_HEADER: &'static [u8; 12] = &[0, 0, 0, 0, b'r', b'u', b's', b't', 0, 0, 0, METADATA_VERSION]; /// The shorthand encoding uses an enum's variant index `usize` /// and is offset by this value so it never matches a real variant. /// This offset is also chosen so that the first byte is never < 0x80. -pub const SHORTHAND_OFFSET: usize = 0x80; +pub(crate) const SHORTHAND_OFFSET: usize = 0x80; /// A value of type T referred to by its absolute position /// in the metadata, and which can be decoded lazily. @@ -76,13 +76,13 @@ pub const SHORTHAND_OFFSET: usize = 0x80; /// Also invalid are nodes being referred in a different /// order than they were encoded in. #[must_use] -pub struct Lazy { - pub position: usize, +pub(crate) struct Lazy { + pub(crate) position: usize, _marker: PhantomData, } impl Lazy { - pub fn with_position(position: usize) -> Lazy { + pub(crate) fn with_position(position: usize) -> Lazy { Lazy { position: position, _marker: PhantomData, @@ -91,7 +91,7 @@ impl Lazy { /// Returns the minimum encoded size of a value of type `T`. // FIXME(eddyb) Give better estimates for certain types. - pub fn min_size() -> usize { + pub(crate) fn min_size() -> usize { 1 } } @@ -128,18 +128,18 @@ impl HashStable for Lazy { /// the minimal distance the length of the sequence, i.e. /// it's assumed there's no 0-byte element in the sequence. #[must_use] -pub struct LazySeq { - pub len: usize, - pub position: usize, +pub(crate) struct LazySeq { + pub(crate) len: usize, + pub(crate) position: usize, _marker: PhantomData, } impl LazySeq { - pub fn empty() -> LazySeq { + pub(crate) fn empty() -> LazySeq { LazySeq::with_position_and_length(0, 0) } - pub fn with_position_and_length(position: usize, len: usize) -> LazySeq { + pub(crate) fn with_position_and_length(position: usize, len: usize) -> LazySeq { LazySeq { len: len, position: position, @@ -148,7 +148,7 @@ impl LazySeq { } /// Returns the minimum encoded size of `length` values of type `T`. - pub fn min_size(length: usize) -> usize { + pub(crate) fn min_size(length: usize) -> usize { length } } @@ -174,7 +174,7 @@ impl HashStable for LazySeq { /// Encoding / decoding state for `Lazy` and `LazySeq`. #[derive(Copy, Clone, PartialEq, Eq, Debug)] -pub enum LazyState { +pub(crate) enum LazyState { /// Outside of a metadata node. NoNode, @@ -192,27 +192,27 @@ pub enum LazyState { /// the `DepNode` for that value. This makes it harder to forget registering /// reads. #[derive(RustcEncodable, RustcDecodable)] -pub struct Tracked { +pub(crate) struct Tracked { state: T, } impl Tracked { - pub fn new(state: T) -> Tracked { + pub(crate) fn new(state: T) -> Tracked { Tracked { state: state, } } - pub fn get(&self, dep_graph: &DepGraph, dep_node: DepNode) -> &T { + pub(crate) fn get(&self, dep_graph: &DepGraph, dep_node: DepNode) -> &T { dep_graph.read(dep_node); &self.state } - pub fn get_untracked(&self) -> &T { + pub(crate) fn get_untracked(&self) -> &T { &self.state } - pub fn map(&self, f: F) -> Tracked + pub(crate) fn map(&self, f: F) -> Tracked where F: FnOnce(&T) -> R { Tracked { @@ -237,34 +237,34 @@ impl<'a, 'gcx, 'tcx, T> HashStable> for Tra #[derive(RustcEncodable, RustcDecodable)] -pub struct CrateRoot { - pub name: Symbol, - pub triple: String, - pub hash: hir::svh::Svh, - pub disambiguator: Symbol, - pub panic_strategy: Tracked, - pub has_global_allocator: Tracked, - pub has_default_lib_allocator: Tracked, - pub plugin_registrar_fn: Option, - pub macro_derive_registrar: Option, - - pub crate_deps: Tracked>, - pub dylib_dependency_formats: Tracked>>, - pub lang_items: Tracked>, - pub lang_items_missing: Tracked>, - pub native_libraries: Tracked>, - pub codemap: LazySeq, - pub def_path_table: Lazy, - pub impls: Tracked>, - pub exported_symbols: Tracked>, - pub index: LazySeq, +pub(crate) struct CrateRoot { + pub(crate) name: Symbol, + pub(crate) triple: String, + pub(crate) hash: hir::svh::Svh, + pub(crate) disambiguator: Symbol, + pub(crate) panic_strategy: Tracked, + pub(crate) has_global_allocator: Tracked, + pub(crate) has_default_lib_allocator: Tracked, + pub(crate) plugin_registrar_fn: Option, + pub(crate) macro_derive_registrar: Option, + + pub(crate) crate_deps: Tracked>, + pub(crate) dylib_dependency_formats: Tracked>>, + pub(crate) lang_items: Tracked>, + pub(crate) lang_items_missing: Tracked>, + pub(crate) native_libraries: Tracked>, + pub(crate) codemap: LazySeq, + pub(crate) def_path_table: Lazy, + pub(crate) impls: Tracked>, + pub(crate) exported_symbols: Tracked>, + pub(crate) index: LazySeq, } #[derive(RustcEncodable, RustcDecodable)] -pub struct CrateDep { - pub name: ast::Name, - pub hash: hir::svh::Svh, - pub kind: DepKind, +pub(crate) struct CrateDep { + pub(crate) name: ast::Name, + pub(crate) hash: hir::svh::Svh, + pub(crate) kind: DepKind, } impl_stable_hash_for!(struct CrateDep { @@ -274,9 +274,9 @@ impl_stable_hash_for!(struct CrateDep { }); #[derive(RustcEncodable, RustcDecodable)] -pub struct TraitImpls { - pub trait_id: (u32, DefIndex), - pub impls: LazySeq, +pub(crate) struct TraitImpls { + pub(crate) trait_id: (u32, DefIndex), + pub(crate) impls: LazySeq, } impl<'a, 'gcx, 'tcx> HashStable> for TraitImpls { @@ -297,23 +297,23 @@ impl<'a, 'gcx, 'tcx> HashStable> for TraitI } #[derive(RustcEncodable, RustcDecodable)] -pub struct Entry<'tcx> { - pub kind: EntryKind<'tcx>, - pub visibility: Lazy, - pub span: Lazy, - pub attributes: LazySeq, - pub children: LazySeq, - pub stability: Option>, - pub deprecation: Option>, - - pub ty: Option>>, - pub inherent_impls: LazySeq, - pub variances: LazySeq, - pub generics: Option>, - pub predicates: Option>>, - - pub ast: Option>>, - pub mir: Option>>, +pub(crate) struct Entry<'tcx> { + pub(crate) kind: EntryKind<'tcx>, + pub(crate) visibility: Lazy, + pub(crate) span: Lazy, + pub(crate) attributes: LazySeq, + pub(crate) children: LazySeq, + pub(crate) stability: Option>, + pub(crate) deprecation: Option>, + + pub(crate) ty: Option>>, + pub(crate) inherent_impls: LazySeq, + pub(crate) variances: LazySeq, + pub(crate) generics: Option>, + pub(crate) predicates: Option>>, + + pub(crate) ast: Option>>, + pub(crate) mir: Option>>, } impl_stable_hash_for!(struct Entry<'tcx> { @@ -334,7 +334,7 @@ impl_stable_hash_for!(struct Entry<'tcx> { }); #[derive(Copy, Clone, RustcEncodable, RustcDecodable)] -pub enum EntryKind<'tcx> { +pub(crate) enum EntryKind<'tcx> { Const(u8), ImmStatic, MutStatic, @@ -426,41 +426,41 @@ impl<'a, 'gcx, 'tcx> HashStable> for EntryK } #[derive(RustcEncodable, RustcDecodable)] -pub struct ModData { - pub reexports: LazySeq, +pub(crate) struct ModData { + pub(crate) reexports: LazySeq, } impl_stable_hash_for!(struct ModData { reexports }); #[derive(RustcEncodable, RustcDecodable)] -pub struct MacroDef { - pub body: String, - pub legacy: bool, +pub(crate) struct MacroDef { + pub(crate) body: String, + pub(crate) legacy: bool, } impl_stable_hash_for!(struct MacroDef { body, legacy }); #[derive(RustcEncodable, RustcDecodable)] -pub struct FnData<'tcx> { - pub constness: hir::Constness, - pub arg_names: LazySeq, - pub sig: Lazy>, +pub(crate) struct FnData<'tcx> { + pub(crate) constness: hir::Constness, + pub(crate) arg_names: LazySeq, + pub(crate) sig: Lazy>, } impl_stable_hash_for!(struct FnData<'tcx> { constness, arg_names, sig }); #[derive(RustcEncodable, RustcDecodable)] -pub struct VariantData<'tcx> { - pub ctor_kind: CtorKind, - pub discr: ty::VariantDiscr, +pub(crate) struct VariantData<'tcx> { + pub(crate) ctor_kind: CtorKind, + pub(crate) discr: ty::VariantDiscr, /// If this is a struct's only variant, this /// is the index of the "struct ctor" item. - pub struct_ctor: Option, + pub(crate) struct_ctor: Option, /// If this is a tuple struct or variant /// ctor, this is its "function" signature. - pub ctor_sig: Option>>, + pub(crate) ctor_sig: Option>>, } impl_stable_hash_for!(struct VariantData<'tcx> { @@ -471,11 +471,11 @@ impl_stable_hash_for!(struct VariantData<'tcx> { }); #[derive(RustcEncodable, RustcDecodable)] -pub struct TraitData<'tcx> { - pub unsafety: hir::Unsafety, - pub paren_sugar: bool, - pub has_default_impl: bool, - pub super_predicates: Lazy>, +pub(crate) struct TraitData<'tcx> { + pub(crate) unsafety: hir::Unsafety, + pub(crate) paren_sugar: bool, + pub(crate) has_default_impl: bool, + pub(crate) super_predicates: Lazy>, } impl_stable_hash_for!(struct TraitData<'tcx> { @@ -486,14 +486,14 @@ impl_stable_hash_for!(struct TraitData<'tcx> { }); #[derive(RustcEncodable, RustcDecodable)] -pub struct ImplData<'tcx> { - pub polarity: hir::ImplPolarity, - pub defaultness: hir::Defaultness, - pub parent_impl: Option, +pub(crate) struct ImplData<'tcx> { + pub(crate) polarity: hir::ImplPolarity, + pub(crate) defaultness: hir::Defaultness, + pub(crate) parent_impl: Option, /// This is `Some` only for impls of `CoerceUnsized`. - pub coerce_unsized_info: Option, - pub trait_ref: Option>>, + pub(crate) coerce_unsized_info: Option, + pub(crate) trait_ref: Option>>, } impl_stable_hash_for!(struct ImplData<'tcx> { @@ -509,7 +509,7 @@ impl_stable_hash_for!(struct ImplData<'tcx> { /// is a trait or an impl and whether, in a trait, it has /// a default, or an in impl, whether it's marked "default". #[derive(Copy, Clone, RustcEncodable, RustcDecodable)] -pub enum AssociatedContainer { +pub(crate) enum AssociatedContainer { TraitRequired, TraitWithDefault, ImplDefault, @@ -524,7 +524,7 @@ impl_stable_hash_for!(enum ::schema::AssociatedContainer { }); impl AssociatedContainer { - pub fn with_def_id(&self, def_id: DefId) -> ty::AssociatedItemContainer { + pub(crate) fn with_def_id(&self, def_id: DefId) -> ty::AssociatedItemContainer { match *self { AssociatedContainer::TraitRequired | AssociatedContainer::TraitWithDefault => ty::TraitContainer(def_id), @@ -534,7 +534,7 @@ impl AssociatedContainer { } } - pub fn defaultness(&self) -> hir::Defaultness { + pub(crate) fn defaultness(&self) -> hir::Defaultness { match *self { AssociatedContainer::TraitRequired => hir::Defaultness::Default { has_value: false, @@ -551,16 +551,16 @@ impl AssociatedContainer { } #[derive(RustcEncodable, RustcDecodable)] -pub struct MethodData<'tcx> { - pub fn_data: FnData<'tcx>, - pub container: AssociatedContainer, - pub has_self: bool, +pub(crate) struct MethodData<'tcx> { + pub(crate) fn_data: FnData<'tcx>, + pub(crate) container: AssociatedContainer, + pub(crate) has_self: bool, } impl_stable_hash_for!(struct MethodData<'tcx> { fn_data, container, has_self }); #[derive(RustcEncodable, RustcDecodable)] -pub struct ClosureData<'tcx> { - pub kind: ty::ClosureKind, - pub sig: Lazy>, +pub(crate) struct ClosureData<'tcx> { + pub(crate) kind: ty::ClosureKind, + pub(crate) sig: Lazy>, } impl_stable_hash_for!(struct ClosureData<'tcx> { kind, sig }); diff --git a/src/librustc_mir/build/block.rs b/src/librustc_mir/build/block.rs index 865174aa272ec..67a9fd5b28db7 100644 --- a/src/librustc_mir/build/block.rs +++ b/src/librustc_mir/build/block.rs @@ -15,12 +15,12 @@ use rustc::hir; use syntax_pos::Span; impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { - pub fn ast_block(&mut self, - destination: &Lvalue<'tcx>, - block: BasicBlock, - ast_block: &'tcx hir::Block, - source_info: SourceInfo) - -> BlockAnd<()> { + pub(crate) fn ast_block(&mut self, + destination: &Lvalue<'tcx>, + block: BasicBlock, + ast_block: &'tcx hir::Block, + source_info: SourceInfo) + -> BlockAnd<()> { let Block { extent, opt_destruction_extent, span, stmts, expr, targeted_by_break } = self.hir.mirror(ast_block); self.in_opt_scope(opt_destruction_extent.map(|de|(de, source_info)), block, move |this| { diff --git a/src/librustc_mir/build/cfg.rs b/src/librustc_mir/build/cfg.rs index c20f8bde78386..37a91319ea409 100644 --- a/src/librustc_mir/build/cfg.rs +++ b/src/librustc_mir/build/cfg.rs @@ -18,75 +18,75 @@ use rustc::middle::region::CodeExtent; use rustc::mir::*; impl<'tcx> CFG<'tcx> { - pub fn block_data(&self, blk: BasicBlock) -> &BasicBlockData<'tcx> { + pub(crate) fn block_data(&self, blk: BasicBlock) -> &BasicBlockData<'tcx> { &self.basic_blocks[blk] } - pub fn block_data_mut(&mut self, blk: BasicBlock) -> &mut BasicBlockData<'tcx> { + pub(crate) fn block_data_mut(&mut self, blk: BasicBlock) -> &mut BasicBlockData<'tcx> { &mut self.basic_blocks[blk] } // llvm.org/PR32488 makes this function use an excess of stack space. Mark // it as #[inline(never)] to keep rustc's stack use in check. #[inline(never)] - pub fn start_new_block(&mut self) -> BasicBlock { + pub(crate) fn start_new_block(&mut self) -> BasicBlock { self.basic_blocks.push(BasicBlockData::new(None)) } - pub fn start_new_cleanup_block(&mut self) -> BasicBlock { + pub(crate) fn start_new_cleanup_block(&mut self) -> BasicBlock { let bb = self.start_new_block(); self.block_data_mut(bb).is_cleanup = true; bb } - pub fn push(&mut self, block: BasicBlock, statement: Statement<'tcx>) { + pub(crate) fn push(&mut self, block: BasicBlock, statement: Statement<'tcx>) { debug!("push({:?}, {:?})", block, statement); self.block_data_mut(block).statements.push(statement); } - pub fn push_end_region(&mut self, - block: BasicBlock, - source_info: SourceInfo, - extent: CodeExtent) { + pub(crate) fn push_end_region(&mut self, + block: BasicBlock, + source_info: SourceInfo, + extent: CodeExtent) { self.push(block, Statement { source_info: source_info, kind: StatementKind::EndRegion(extent), }); } - pub fn push_assign(&mut self, - block: BasicBlock, - source_info: SourceInfo, - lvalue: &Lvalue<'tcx>, - rvalue: Rvalue<'tcx>) { + pub(crate) fn push_assign(&mut self, + block: BasicBlock, + source_info: SourceInfo, + lvalue: &Lvalue<'tcx>, + rvalue: Rvalue<'tcx>) { self.push(block, Statement { source_info: source_info, kind: StatementKind::Assign(lvalue.clone(), rvalue) }); } - pub fn push_assign_constant(&mut self, - block: BasicBlock, - source_info: SourceInfo, - temp: &Lvalue<'tcx>, - constant: Constant<'tcx>) { + pub(crate) fn push_assign_constant(&mut self, + block: BasicBlock, + source_info: SourceInfo, + temp: &Lvalue<'tcx>, + constant: Constant<'tcx>) { self.push_assign(block, source_info, temp, Rvalue::Use(Operand::Constant(box constant))); } - pub fn push_assign_unit(&mut self, - block: BasicBlock, - source_info: SourceInfo, - lvalue: &Lvalue<'tcx>) { + pub(crate) fn push_assign_unit(&mut self, + block: BasicBlock, + source_info: SourceInfo, + lvalue: &Lvalue<'tcx>) { self.push_assign(block, source_info, lvalue, Rvalue::Aggregate( box AggregateKind::Tuple, vec![] )); } - pub fn terminate(&mut self, - block: BasicBlock, - source_info: SourceInfo, - kind: TerminatorKind<'tcx>) { + pub(crate) fn terminate(&mut self, + block: BasicBlock, + source_info: SourceInfo, + kind: TerminatorKind<'tcx>) { debug!("terminating block {:?} <- {:?}", block, kind); debug_assert!(self.block_data(block).terminator.is_none(), "terminate: block {:?}={:?} already has a terminator set", diff --git a/src/librustc_mir/build/expr/as_constant.rs b/src/librustc_mir/build/expr/as_constant.rs index 6d15f0a2e5d7f..e4094bd3e7469 100644 --- a/src/librustc_mir/build/expr/as_constant.rs +++ b/src/librustc_mir/build/expr/as_constant.rs @@ -17,7 +17,7 @@ use rustc::mir::*; impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// Compile `expr`, yielding a compile-time constant. Assumes that /// `expr` is a valid compile-time constant! - pub fn as_constant(&mut self, expr: M) -> Constant<'tcx> + pub(crate) fn as_constant(&mut self, expr: M) -> Constant<'tcx> where M: Mirror<'tcx, Output=Expr<'tcx>> { let expr = self.hir.mirror(expr); diff --git a/src/librustc_mir/build/expr/as_lvalue.rs b/src/librustc_mir/build/expr/as_lvalue.rs index 04c23215463dd..b338ae2c3369e 100644 --- a/src/librustc_mir/build/expr/as_lvalue.rs +++ b/src/librustc_mir/build/expr/as_lvalue.rs @@ -19,10 +19,10 @@ use rustc_data_structures::indexed_vec::Idx; impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// Compile `expr`, yielding an lvalue that we can move from etc. - pub fn as_lvalue(&mut self, - block: BasicBlock, - expr: M) - -> BlockAnd> + pub(crate) fn as_lvalue(&mut self, + block: BasicBlock, + expr: M) + -> BlockAnd> where M: Mirror<'tcx, Output=Expr<'tcx>> { let expr = self.hir.mirror(expr); diff --git a/src/librustc_mir/build/expr/as_operand.rs b/src/librustc_mir/build/expr/as_operand.rs index 4679e0bb0a5c3..f6819ee1dbc9a 100644 --- a/src/librustc_mir/build/expr/as_operand.rs +++ b/src/librustc_mir/build/expr/as_operand.rs @@ -23,8 +23,8 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// The operand returned from this function will *not be valid* after /// an ExprKind::Scope is passed, so please do *not* return it from /// functions to avoid bad miscompiles. - pub fn as_local_operand(&mut self, block: BasicBlock, expr: M) - -> BlockAnd> + pub(crate) fn as_local_operand(&mut self, block: BasicBlock, expr: M) + -> BlockAnd> where M: Mirror<'tcx, Output = Expr<'tcx>> { let local_scope = self.local_scope(); @@ -37,10 +37,10 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// this time. /// /// The operand is known to be live until the end of `scope`. - pub fn as_operand(&mut self, - block: BasicBlock, - scope: Option, - expr: M) -> BlockAnd> + pub(crate) fn as_operand(&mut self, + block: BasicBlock, + scope: Option, + expr: M) -> BlockAnd> where M: Mirror<'tcx, Output = Expr<'tcx>> { let expr = self.hir.mirror(expr); diff --git a/src/librustc_mir/build/expr/as_rvalue.rs b/src/librustc_mir/build/expr/as_rvalue.rs index 2512291f1a44f..efa360439d83b 100644 --- a/src/librustc_mir/build/expr/as_rvalue.rs +++ b/src/librustc_mir/build/expr/as_rvalue.rs @@ -29,8 +29,8 @@ use syntax_pos::Span; impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// See comment on `as_local_operand` - pub fn as_local_rvalue(&mut self, block: BasicBlock, expr: M) - -> BlockAnd> + pub(crate) fn as_local_rvalue(&mut self, block: BasicBlock, expr: M) + -> BlockAnd> where M: Mirror<'tcx, Output = Expr<'tcx>> { let local_scope = self.local_scope(); @@ -38,8 +38,8 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { } /// Compile `expr`, yielding an rvalue. - pub fn as_rvalue(&mut self, block: BasicBlock, scope: Option, expr: M) - -> BlockAnd> + pub(crate) fn as_rvalue(&mut self, block: BasicBlock, scope: Option, expr: M) + -> BlockAnd> where M: Mirror<'tcx, Output = Expr<'tcx>> { let expr = self.hir.mirror(expr); @@ -256,9 +256,10 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { } } - pub fn build_binary_op(&mut self, mut block: BasicBlock, - op: BinOp, span: Span, ty: ty::Ty<'tcx>, - lhs: Operand<'tcx>, rhs: Operand<'tcx>) -> BlockAnd> { + pub(crate) fn build_binary_op(&mut self, mut block: BasicBlock, + op: BinOp, span: Span, ty: ty::Ty<'tcx>, + lhs: Operand<'tcx>, rhs: Operand<'tcx>) + -> BlockAnd> { let source_info = self.source_info(span); let bool_ty = self.hir.bool_ty(); if self.hir.check_overflow() && op.is_checkable() && ty.is_integral() { diff --git a/src/librustc_mir/build/expr/as_temp.rs b/src/librustc_mir/build/expr/as_temp.rs index 9be306d2848b3..da2f21eee6e11 100644 --- a/src/librustc_mir/build/expr/as_temp.rs +++ b/src/librustc_mir/build/expr/as_temp.rs @@ -19,11 +19,11 @@ use rustc::mir::*; impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// Compile `expr` into a fresh temporary. This is used when building /// up rvalues so as to freeze the value that will be consumed. - pub fn as_temp(&mut self, - block: BasicBlock, - temp_lifetime: Option, - expr: M) - -> BlockAnd> + pub(crate) fn as_temp(&mut self, + block: BasicBlock, + temp_lifetime: Option, + expr: M) + -> BlockAnd> where M: Mirror<'tcx, Output = Expr<'tcx>> { let expr = self.hir.mirror(expr); diff --git a/src/librustc_mir/build/expr/category.rs b/src/librustc_mir/build/expr/category.rs index 35173bb598c7c..e7d440ac42f7b 100644 --- a/src/librustc_mir/build/expr/category.rs +++ b/src/librustc_mir/build/expr/category.rs @@ -11,7 +11,7 @@ use hair::*; #[derive(Debug, PartialEq)] -pub enum Category { +pub(crate) enum Category { // An assignable memory location like `x`, `x.f`, `foo()[3]`, that // sort of thing. Something that could appear on the LHS of an `=` // sign. @@ -29,7 +29,7 @@ pub enum Category { // Rvalues fall into different "styles" that will determine which fn // is best suited to generate them. #[derive(Debug, PartialEq)] -pub enum RvalueFunc { +pub(crate) enum RvalueFunc { // Best generated by `into`. This is generally exprs that // cause branching, like `match`, but also includes calls. Into, @@ -41,7 +41,7 @@ pub enum RvalueFunc { /// Determines the category for a given expression. Note that scope /// and paren expressions have no category. impl Category { - pub fn of<'tcx>(ek: &ExprKind<'tcx>) -> Option { + pub(crate) fn of<'tcx>(ek: &ExprKind<'tcx>) -> Option { match *ek { ExprKind::Scope { .. } => None, diff --git a/src/librustc_mir/build/expr/into.rs b/src/librustc_mir/build/expr/into.rs index 326c1df69ebeb..580331a7499b0 100644 --- a/src/librustc_mir/build/expr/into.rs +++ b/src/librustc_mir/build/expr/into.rs @@ -21,11 +21,11 @@ use syntax::abi::Abi; impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// Compile `expr`, storing the result into `destination`, which /// is assumed to be uninitialized. - pub fn into_expr(&mut self, - destination: &Lvalue<'tcx>, - mut block: BasicBlock, - expr: Expr<'tcx>) - -> BlockAnd<()> + pub(crate) fn into_expr(&mut self, + destination: &Lvalue<'tcx>, + mut block: BasicBlock, + expr: Expr<'tcx>) + -> BlockAnd<()> { debug!("into_expr(destination={:?}, block={:?}, expr={:?})", destination, block, expr); diff --git a/src/librustc_mir/build/expr/stmt.rs b/src/librustc_mir/build/expr/stmt.rs index 3120ac2190824..53a496161f496 100644 --- a/src/librustc_mir/build/expr/stmt.rs +++ b/src/librustc_mir/build/expr/stmt.rs @@ -15,7 +15,7 @@ use rustc::mir::*; impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { - pub fn stmt_expr(&mut self, mut block: BasicBlock, expr: Expr<'tcx>) -> BlockAnd<()> { + pub(crate) fn stmt_expr(&mut self, mut block: BasicBlock, expr: Expr<'tcx>) -> BlockAnd<()> { let this = self; let expr_span = expr.span; let source_info = this.source_info(expr.span); diff --git a/src/librustc_mir/build/into.rs b/src/librustc_mir/build/into.rs index 0d912513c6c76..f1ad2aa10cdc0 100644 --- a/src/librustc_mir/build/into.rs +++ b/src/librustc_mir/build/into.rs @@ -27,11 +27,11 @@ pub(in build) trait EvalInto<'tcx> { } impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { - pub fn into(&mut self, - destination: &Lvalue<'tcx>, - block: BasicBlock, - expr: E) - -> BlockAnd<()> + pub(crate) fn into(&mut self, + destination: &Lvalue<'tcx>, + block: BasicBlock, + expr: E) + -> BlockAnd<()> where E: EvalInto<'tcx> { expr.eval_into(self, destination, block) diff --git a/src/librustc_mir/build/matches/mod.rs b/src/librustc_mir/build/matches/mod.rs index 54f285480ab53..cd02d3cb1fc1a 100644 --- a/src/librustc_mir/build/matches/mod.rs +++ b/src/librustc_mir/build/matches/mod.rs @@ -30,13 +30,13 @@ mod test; mod util; impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { - pub fn match_expr(&mut self, - destination: &Lvalue<'tcx>, - span: Span, - mut block: BasicBlock, - discriminant: ExprRef<'tcx>, - arms: Vec>) - -> BlockAnd<()> { + pub(crate) fn match_expr(&mut self, + destination: &Lvalue<'tcx>, + span: Span, + mut block: BasicBlock, + discriminant: ExprRef<'tcx>, + arms: Vec>) + -> BlockAnd<()> { let discriminant_lvalue = unpack!(block = self.as_lvalue(block, discriminant)); let mut arm_blocks = ArmBlocks { @@ -113,11 +113,11 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { end_block.unit() } - pub fn expr_into_pattern(&mut self, - mut block: BasicBlock, - irrefutable_pat: Pattern<'tcx>, - initializer: ExprRef<'tcx>) - -> BlockAnd<()> { + pub(crate) fn expr_into_pattern(&mut self, + mut block: BasicBlock, + irrefutable_pat: Pattern<'tcx>, + initializer: ExprRef<'tcx>) + -> BlockAnd<()> { // optimize the case of `let x = ...` match *irrefutable_pat.kind { PatternKind::Binding { mode: BindingMode::ByValue, @@ -135,11 +135,11 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { } } - pub fn lvalue_into_pattern(&mut self, - mut block: BasicBlock, - irrefutable_pat: Pattern<'tcx>, - initializer: &Lvalue<'tcx>) - -> BlockAnd<()> { + pub(crate) fn lvalue_into_pattern(&mut self, + mut block: BasicBlock, + irrefutable_pat: Pattern<'tcx>, + initializer: &Lvalue<'tcx>) + -> BlockAnd<()> { // create a dummy candidate let mut candidate = Candidate { span: irrefutable_pat.span, @@ -169,11 +169,11 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// Declares the bindings of the given pattern and returns the visibility scope /// for the bindings in this patterns, if such a scope had to be created. /// NOTE: Declaring the bindings should always be done in their drop scope. - pub fn declare_bindings(&mut self, - mut var_scope: Option, - scope_span: Span, - pattern: &Pattern<'tcx>) - -> Option { + pub(crate) fn declare_bindings(&mut self, + mut var_scope: Option, + scope_span: Span, + pattern: &Pattern<'tcx>) + -> Option { self.visit_bindings(pattern, &mut |this, mutability, name, var, span, ty| { if var_scope.is_none() { var_scope = Some(this.new_visibility_scope(scope_span)); @@ -187,8 +187,8 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { var_scope } - pub fn storage_live_binding(&mut self, block: BasicBlock, var: NodeId, span: Span) - -> Lvalue<'tcx> + pub(crate) fn storage_live_binding(&mut self, block: BasicBlock, var: NodeId, span: Span) + -> Lvalue<'tcx> { let local_id = self.var_indices[&var]; let source_info = self.source_info(span); @@ -199,14 +199,14 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { Lvalue::Local(local_id) } - pub fn schedule_drop_for_binding(&mut self, var: NodeId, span: Span) { + pub(crate) fn schedule_drop_for_binding(&mut self, var: NodeId, span: Span) { let local_id = self.var_indices[&var]; let var_ty = self.local_decls[local_id].ty; let extent = self.hir.region_maps.var_scope(var); self.schedule_drop(span, extent, &Lvalue::Local(local_id), var_ty); } - pub fn visit_bindings(&mut self, pattern: &Pattern<'tcx>, mut f: &mut F) + pub(crate) fn visit_bindings(&mut self, pattern: &Pattern<'tcx>, mut f: &mut F) where F: FnMut(&mut Self, Mutability, Name, NodeId, Span, Ty<'tcx>) { match *pattern.kind { @@ -245,7 +245,7 @@ struct ArmBlocks { } #[derive(Clone, Debug)] -pub struct Candidate<'pat, 'tcx:'pat> { +pub(crate) struct Candidate<'pat, 'tcx:'pat> { // span of the original pattern that gave rise to this candidate span: Span, @@ -274,7 +274,7 @@ struct Binding<'tcx> { } #[derive(Clone, Debug)] -pub struct MatchPair<'pat, 'tcx:'pat> { +pub(crate) struct MatchPair<'pat, 'tcx:'pat> { // this lvalue... lvalue: Lvalue<'tcx>, @@ -326,7 +326,7 @@ enum TestKind<'tcx> { } #[derive(Debug)] -pub struct Test<'tcx> { +pub(crate) struct Test<'tcx> { span: Span, kind: TestKind<'tcx>, } diff --git a/src/librustc_mir/build/matches/simplify.rs b/src/librustc_mir/build/matches/simplify.rs index efddee2c933f4..bea5e8cf4f2a3 100644 --- a/src/librustc_mir/build/matches/simplify.rs +++ b/src/librustc_mir/build/matches/simplify.rs @@ -31,10 +31,10 @@ use rustc_data_structures::fx::FxHashMap; use std::mem; impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { - pub fn simplify_candidate<'pat>(&mut self, - block: BasicBlock, - candidate: &mut Candidate<'pat, 'tcx>) - -> BlockAnd<()> { + pub(crate) fn simplify_candidate<'pat>(&mut self, + block: BasicBlock, + candidate: &mut Candidate<'pat, 'tcx>) + -> BlockAnd<()> { // repeatedly simplify match pairs until fixed point is reached loop { let match_pairs = mem::replace(&mut candidate.match_pairs, vec![]); diff --git a/src/librustc_mir/build/matches/test.rs b/src/librustc_mir/build/matches/test.rs index f4d43e041ae87..f5f6a39ea8552 100644 --- a/src/librustc_mir/build/matches/test.rs +++ b/src/librustc_mir/build/matches/test.rs @@ -32,7 +32,7 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// Identifies what test is needed to decide if `match_pair` is applicable. /// /// It is a bug to call this with a simplifyable pattern. - pub fn test<'pat>(&mut self, match_pair: &MatchPair<'pat, 'tcx>) -> Test<'tcx> { + pub(crate) fn test<'pat>(&mut self, match_pair: &MatchPair<'pat, 'tcx>) -> Test<'tcx> { match *match_pair.pattern.kind { PatternKind::Variant { ref adt_def, substs: _, variant_index: _, subpatterns: _ } => { Test { @@ -108,13 +108,13 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { } } - pub fn add_cases_to_switch<'pat>(&mut self, - test_lvalue: &Lvalue<'tcx>, - candidate: &Candidate<'pat, 'tcx>, - switch_ty: Ty<'tcx>, - options: &mut Vec>, - indices: &mut FxHashMap, usize>) - -> bool + pub(crate) fn add_cases_to_switch<'pat>(&mut self, + test_lvalue: &Lvalue<'tcx>, + candidate: &Candidate<'pat, 'tcx>, + switch_ty: Ty<'tcx>, + options: &mut Vec>, + indices: &mut FxHashMap, usize>) + -> bool { let match_pair = match candidate.match_pairs.iter().find(|mp| mp.lvalue == *test_lvalue) { Some(match_pair) => match_pair, @@ -149,11 +149,11 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { } } - pub fn add_variants_to_switch<'pat>(&mut self, - test_lvalue: &Lvalue<'tcx>, - candidate: &Candidate<'pat, 'tcx>, - variants: &mut BitVector) - -> bool + pub(crate) fn add_variants_to_switch<'pat>(&mut self, + test_lvalue: &Lvalue<'tcx>, + candidate: &Candidate<'pat, 'tcx>, + variants: &mut BitVector) + -> bool { let match_pair = match candidate.match_pairs.iter().find(|mp| mp.lvalue == *test_lvalue) { Some(match_pair) => match_pair, @@ -175,11 +175,11 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { } /// Generates the code to perform a test. - pub fn perform_test(&mut self, - block: BasicBlock, - lvalue: &Lvalue<'tcx>, - test: &Test<'tcx>) - -> Vec { + pub(crate) fn perform_test(&mut self, + block: BasicBlock, + lvalue: &Lvalue<'tcx>, + test: &Test<'tcx>) + -> Vec { let source_info = self.source_info(test.span); match test.kind { TestKind::Switch { adt_def, ref variants } => { @@ -429,12 +429,12 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// apply. For now, we return false, indicate that the test does /// not apply to this candidate, but it might be we can get /// tighter match code if we do something a bit different. - pub fn sort_candidate<'pat>(&mut self, - test_lvalue: &Lvalue<'tcx>, - test: &Test<'tcx>, - candidate: &Candidate<'pat, 'tcx>, - resulting_candidates: &mut [Vec>]) - -> bool { + pub(crate) fn sort_candidate<'pat>(&mut self, + test_lvalue: &Lvalue<'tcx>, + test: &Test<'tcx>, + candidate: &Candidate<'pat, 'tcx>, + resulting_candidates: &mut [Vec>]) + -> bool { // Find the match_pair for this lvalue (if any). At present, // afaik, there can be at most one. (In the future, if we // adopted a more general `@` operator, there might be more diff --git a/src/librustc_mir/build/matches/util.rs b/src/librustc_mir/build/matches/util.rs index a013875b3110b..93033e5add5fc 100644 --- a/src/librustc_mir/build/matches/util.rs +++ b/src/librustc_mir/build/matches/util.rs @@ -15,10 +15,10 @@ use rustc::mir::*; use std::u32; impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { - pub fn field_match_pairs<'pat>(&mut self, - lvalue: Lvalue<'tcx>, - subpatterns: &'pat [FieldPattern<'tcx>]) - -> Vec> { + pub(crate) fn field_match_pairs<'pat>(&mut self, + lvalue: Lvalue<'tcx>, + subpatterns: &'pat [FieldPattern<'tcx>]) + -> Vec> { subpatterns.iter() .map(|fieldpat| { let lvalue = lvalue.clone().field(fieldpat.field, @@ -28,12 +28,12 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { .collect() } - pub fn prefix_slice_suffix<'pat>(&mut self, - match_pairs: &mut Vec>, - lvalue: &Lvalue<'tcx>, - prefix: &'pat [Pattern<'tcx>], - opt_slice: Option<&'pat Pattern<'tcx>>, - suffix: &'pat [Pattern<'tcx>]) { + pub(crate) fn prefix_slice_suffix<'pat>(&mut self, + match_pairs: &mut Vec>, + lvalue: &Lvalue<'tcx>, + prefix: &'pat [Pattern<'tcx>], + opt_slice: Option<&'pat Pattern<'tcx>>, + suffix: &'pat [Pattern<'tcx>]) { let min_length = prefix.len() + suffix.len(); assert!(min_length < u32::MAX as usize); let min_length = min_length as u32; @@ -78,7 +78,7 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { } impl<'pat, 'tcx> MatchPair<'pat, 'tcx> { - pub fn new(lvalue: Lvalue<'tcx>, pattern: &'pat Pattern<'tcx>) -> MatchPair<'pat, 'tcx> { + pub(crate) fn new(lvalue: Lvalue<'tcx>, pattern: &'pat Pattern<'tcx>) -> MatchPair<'pat, 'tcx> { MatchPair { lvalue: lvalue, pattern: pattern, diff --git a/src/librustc_mir/build/misc.rs b/src/librustc_mir/build/misc.rs index 6c93e073de6b1..fc091f10df873 100644 --- a/src/librustc_mir/build/misc.rs +++ b/src/librustc_mir/build/misc.rs @@ -27,7 +27,7 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// /// NB: **No cleanup is scheduled for this temporary.** You should /// call `schedule_drop` once the temporary is initialized. - pub fn temp(&mut self, ty: Ty<'tcx>, span: Span) -> Lvalue<'tcx> { + pub(crate) fn temp(&mut self, ty: Ty<'tcx>, span: Span) -> Lvalue<'tcx> { let temp = self.local_decls.push(LocalDecl::new_temp(ty, span)); let lvalue = Lvalue::Local(temp); debug!("temp: created temp {:?} with type {:?}", @@ -35,11 +35,11 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { lvalue } - pub fn literal_operand(&mut self, - span: Span, - ty: Ty<'tcx>, - literal: Literal<'tcx>) - -> Operand<'tcx> { + pub(crate) fn literal_operand(&mut self, + span: Span, + ty: Ty<'tcx>, + literal: Literal<'tcx>) + -> Operand<'tcx> { let constant = box Constant { span: span, ty: ty, @@ -48,13 +48,13 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { Operand::Constant(constant) } - pub fn unit_rvalue(&mut self) -> Rvalue<'tcx> { + pub(crate) fn unit_rvalue(&mut self) -> Rvalue<'tcx> { Rvalue::Aggregate(box AggregateKind::Tuple, vec![]) } // Returns a zero literal operand for the appropriate type, works for // bool, char and integers. - pub fn zero_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> { + pub(crate) fn zero_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> { let literal = match ty.sty { ty::TyBool => { self.hir.false_literal() @@ -100,11 +100,11 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { self.literal_operand(span, ty, literal) } - pub fn push_usize(&mut self, - block: BasicBlock, - source_info: SourceInfo, - value: u64) - -> Lvalue<'tcx> { + pub(crate) fn push_usize(&mut self, + block: BasicBlock, + source_info: SourceInfo, + value: u64) + -> Lvalue<'tcx> { let usize_ty = self.hir.usize_ty(); let temp = self.temp(usize_ty, source_info.span); self.cfg.push_assign_constant( diff --git a/src/librustc_mir/build/mod.rs b/src/librustc_mir/build/mod.rs index eb1414d42e179..26499c9b27fb5 100644 --- a/src/librustc_mir/build/mod.rs +++ b/src/librustc_mir/build/mod.rs @@ -32,7 +32,7 @@ use syntax_pos::Span; use util as mir_util; /// Construct the MIR for a given def-id. -pub fn mir_build<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Mir<'tcx> { +pub(crate) fn mir_build<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Mir<'tcx> { let id = tcx.hir.as_local_node_id(def_id).unwrap(); let unsupported = || { span_bug!(tcx.hir.span(id), "can't build MIR for {:?}", def_id); @@ -262,7 +262,7 @@ struct CFG<'tcx> { } #[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub struct ScopeId(u32); +pub(crate) struct ScopeId(u32); impl Idx for ScopeId { fn new(index: usize) -> ScopeId { diff --git a/src/librustc_mir/build/scope.rs b/src/librustc_mir/build/scope.rs index 2244ffde3c9d0..de9b4f0880067 100644 --- a/src/librustc_mir/build/scope.rs +++ b/src/librustc_mir/build/scope.rs @@ -100,7 +100,7 @@ use rustc_data_structures::indexed_vec::Idx; use rustc_data_structures::fx::FxHashMap; #[derive(Debug)] -pub struct Scope<'tcx> { +pub(crate) struct Scope<'tcx> { /// The visibility scope this scope was created in. visibility_scope: VisibilityScope, @@ -184,17 +184,17 @@ struct FreeData<'tcx> { } #[derive(Clone, Debug)] -pub struct BreakableScope<'tcx> { +pub(crate) struct BreakableScope<'tcx> { /// Extent of the loop - pub extent: CodeExtent, + pub(crate) extent: CodeExtent, /// Where the body of the loop begins. `None` if block - pub continue_block: Option, + pub(crate) continue_block: Option, /// Block to branch into when the loop or block terminates (either by being `break`-en out /// from, or by having its condition to become false) - pub break_block: BasicBlock, + pub(crate) break_block: BasicBlock, /// The destination of the loop/block expression itself (i.e. where to put the result of a /// `break` expression) - pub break_destination: Lvalue<'tcx>, + pub(crate) break_destination: Lvalue<'tcx>, } impl<'tcx> Scope<'tcx> { @@ -253,11 +253,11 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// should branch to. See module comment for more details. /// /// Returns the might_break attribute of the BreakableScope used. - pub fn in_breakable_scope(&mut self, - loop_block: Option, - break_block: BasicBlock, - break_destination: Lvalue<'tcx>, - f: F) -> R + pub(crate) fn in_breakable_scope(&mut self, + loop_block: Option, + break_block: BasicBlock, + break_destination: Lvalue<'tcx>, + f: F) -> R where F: FnOnce(&mut Builder<'a, 'gcx, 'tcx>) -> R { let extent = self.topmost_scope(); @@ -274,11 +274,11 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { res } - pub fn in_opt_scope(&mut self, - opt_extent: Option<(CodeExtent, SourceInfo)>, - mut block: BasicBlock, - f: F) - -> BlockAnd + pub(crate) fn in_opt_scope(&mut self, + opt_extent: Option<(CodeExtent, SourceInfo)>, + mut block: BasicBlock, + f: F) + -> BlockAnd where F: FnOnce(&mut Builder<'a, 'gcx, 'tcx>) -> BlockAnd { debug!("in_opt_scope(opt_extent={:?}, block={:?})", opt_extent, block); @@ -293,11 +293,11 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// Convenience wrapper that pushes a scope and then executes `f` /// to build its contents, popping the scope afterwards. - pub fn in_scope(&mut self, - extent: (CodeExtent, SourceInfo), - mut block: BasicBlock, - f: F) - -> BlockAnd + pub(crate) fn in_scope(&mut self, + extent: (CodeExtent, SourceInfo), + mut block: BasicBlock, + f: F) + -> BlockAnd where F: FnOnce(&mut Builder<'a, 'gcx, 'tcx>) -> BlockAnd { debug!("in_scope(extent={:?}, block={:?})", extent, block); @@ -312,7 +312,7 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// scope and call `pop_scope` afterwards. Note that these two /// calls must be paired; using `in_scope` as a convenience /// wrapper maybe preferable. - pub fn push_scope(&mut self, extent: CodeExtent) { + pub(crate) fn push_scope(&mut self, extent: CodeExtent) { debug!("push_scope({:?})", extent); let vis_scope = self.visibility_scope; self.scopes.push(Scope { @@ -328,10 +328,10 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// Pops a scope, which should have extent `extent`, adding any /// drops onto the end of `block` that are needed. This must /// match 1-to-1 with `push_scope`. - pub fn pop_scope(&mut self, - extent: (CodeExtent, SourceInfo), - mut block: BasicBlock) - -> BlockAnd<()> { + pub(crate) fn pop_scope(&mut self, + extent: (CodeExtent, SourceInfo), + mut block: BasicBlock) + -> BlockAnd<()> { debug!("pop_scope({:?}, {:?})", extent, block); // We need to have `cached_block`s available for all the drops, so we call diverge_cleanup // to make sure all the `cached_block`s are filled in. @@ -353,11 +353,11 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// and including `extent`. This will insert whatever drops are /// needed, as well as tracking this exit for the SEME region. See /// module comment for details. - pub fn exit_scope(&mut self, - span: Span, - extent: (CodeExtent, SourceInfo), - mut block: BasicBlock, - target: BasicBlock) { + pub(crate) fn exit_scope(&mut self, + span: Span, + extent: (CodeExtent, SourceInfo), + mut block: BasicBlock, + target: BasicBlock) { debug!("exit_scope(extent={:?}, block={:?}, target={:?})", extent, block, target); let scope_count = 1 + self.scopes.iter().rev().position(|scope| scope.extent == extent.0) .unwrap_or_else(||{ @@ -404,7 +404,7 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { } /// Creates a new visibility scope, nested in the current one. - pub fn new_visibility_scope(&mut self, span: Span) -> VisibilityScope { + pub(crate) fn new_visibility_scope(&mut self, span: Span) -> VisibilityScope { let parent = self.visibility_scope; let scope = VisibilityScope::new(self.visibility_scopes.len()); self.visibility_scopes.push(VisibilityScopeData { @@ -418,10 +418,10 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { // ============== /// Finds the breakable scope for a given label. This is used for /// resolving `break` and `continue`. - pub fn find_breakable_scope(&mut self, - span: Span, - label: CodeExtent) - -> &mut BreakableScope<'tcx> { + pub(crate) fn find_breakable_scope(&mut self, + span: Span, + label: CodeExtent) + -> &mut BreakableScope<'tcx> { // find the loop-scope with the correct id self.breakable_scopes.iter_mut() .rev() @@ -431,7 +431,7 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { } /// Given a span and the current visibility scope, make a SourceInfo. - pub fn source_info(&self, span: Span) -> SourceInfo { + pub(crate) fn source_info(&self, span: Span) -> SourceInfo { SourceInfo { span: span, scope: self.visibility_scope @@ -440,7 +440,7 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// Returns the extent of the scope which should be exited by a /// return. - pub fn extent_of_return_scope(&self) -> CodeExtent { + pub(crate) fn extent_of_return_scope(&self) -> CodeExtent { // The outermost scope (`scopes[0]`) will be the `CallSiteScope`. // We want `scopes[1]`, which is the `ParameterScope`. assert!(self.scopes.len() >= 2); @@ -453,7 +453,7 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// Returns the topmost active scope, which is known to be alive until /// the next scope expression. - pub fn topmost_scope(&self) -> CodeExtent { + pub(crate) fn topmost_scope(&self) -> CodeExtent { self.scopes.last().expect("topmost_scope: no scopes present").extent } @@ -479,7 +479,7 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// /// When building statics/constants, returns `None` since /// intermediate values do not have to be dropped in that case. - pub fn local_scope(&self) -> Option { + pub(crate) fn local_scope(&self) -> Option { match self.hir.src { MirSource::Const(_) | MirSource::Static(..) => @@ -496,11 +496,11 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { // ================ /// Indicates that `lvalue` should be dropped on exit from /// `extent`. - pub fn schedule_drop(&mut self, - span: Span, - extent: CodeExtent, - lvalue: &Lvalue<'tcx>, - lvalue_ty: Ty<'tcx>) { + pub(crate) fn schedule_drop(&mut self, + span: Span, + extent: CodeExtent, + lvalue: &Lvalue<'tcx>, + lvalue_ty: Ty<'tcx>) { let needs_drop = self.hir.needs_drop(lvalue_ty); let drop_kind = if needs_drop { DropKind::Value { cached_block: None } @@ -586,11 +586,11 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// This cleanup will only be translated into unwind branch. /// The extent should be for the `EXPR` inside `box EXPR`. /// There may only be one “free” scheduled in any given scope. - pub fn schedule_box_free(&mut self, - span: Span, - extent: CodeExtent, - value: &Lvalue<'tcx>, - item_ty: Ty<'tcx>) { + pub(crate) fn schedule_box_free(&mut self, + span: Span, + extent: CodeExtent, + value: &Lvalue<'tcx>, + item_ty: Ty<'tcx>) { for scope in self.scopes.iter_mut().rev() { // See the comment in schedule_drop above. The primary difference is that we invalidate // the unwind blocks unconditionally. That’s because the box free may be considered @@ -618,7 +618,7 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// This path terminates in Resume. Returns the start of the path. /// See module comment for more details. None indicates there’s no /// cleanup to do at this point. - pub fn diverge_cleanup(&mut self, span: Span) -> Option { + pub(crate) fn diverge_cleanup(&mut self, span: Span) -> Option { if !self.scopes.iter().any(|scope| scope.needs_cleanup) { return None; } @@ -658,11 +658,11 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { } /// Utility function for *non*-scope code to build their own drops - pub fn build_drop(&mut self, - block: BasicBlock, - span: Span, - location: Lvalue<'tcx>, - ty: Ty<'tcx>) -> BlockAnd<()> { + pub(crate) fn build_drop(&mut self, + block: BasicBlock, + span: Span, + location: Lvalue<'tcx>, + ty: Ty<'tcx>) -> BlockAnd<()> { if !self.hir.needs_drop(ty) { return block.unit(); } @@ -679,11 +679,11 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { } /// Utility function for *non*-scope code to build their own drops - pub fn build_drop_and_replace(&mut self, - block: BasicBlock, - span: Span, - location: Lvalue<'tcx>, - value: Operand<'tcx>) -> BlockAnd<()> { + pub(crate) fn build_drop_and_replace(&mut self, + block: BasicBlock, + span: Span, + location: Lvalue<'tcx>, + value: Operand<'tcx>) -> BlockAnd<()> { let source_info = self.source_info(span); let next_target = self.cfg.start_new_block(); let diverge_target = self.diverge_cleanup(span); @@ -700,12 +700,12 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// Create an Assert terminator and return the success block. /// If the boolean condition operand is not the expected value, /// a runtime panic will be caused with the given message. - pub fn assert(&mut self, block: BasicBlock, - cond: Operand<'tcx>, - expected: bool, - msg: AssertMessage<'tcx>, - span: Span) - -> BasicBlock { + pub(crate) fn assert(&mut self, block: BasicBlock, + cond: Operand<'tcx>, + expected: bool, + msg: AssertMessage<'tcx>, + span: Span) + -> BasicBlock { let source_info = self.source_info(span); let success_block = self.cfg.start_new_block(); diff --git a/src/librustc_mir/dataflow/drop_flag_effects.rs b/src/librustc_mir/dataflow/drop_flag_effects.rs index daafbecc5dfa3..123f4de0b79b5 100644 --- a/src/librustc_mir/dataflow/drop_flag_effects.rs +++ b/src/librustc_mir/dataflow/drop_flag_effects.rs @@ -40,19 +40,19 @@ pub(crate) fn has_rustc_mir_with(attrs: &[ast::Attribute], name: &str) -> Option return None; } -pub struct MoveDataParamEnv<'tcx> { +pub(crate) struct MoveDataParamEnv<'tcx> { pub(crate) move_data: MoveData<'tcx>, pub(crate) param_env: ty::ParamEnv<'tcx>, } pub(crate) fn do_dataflow<'a, 'tcx, BD, P>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - mir: &Mir<'tcx>, - node_id: ast::NodeId, - attributes: &[ast::Attribute], - dead_unwinds: &IdxSet, - bd: BD, - p: P) - -> DataflowResults + mir: &Mir<'tcx>, + node_id: ast::NodeId, + attributes: &[ast::Attribute], + dead_unwinds: &IdxSet, + bd: BD, + p: P) + -> DataflowResults where BD: BitDenotation + DataflowOperator, P: Fn(&BD, BD::Idx) -> &fmt::Debug { @@ -86,10 +86,10 @@ pub(crate) fn do_dataflow<'a, 'tcx, BD, P>(tcx: TyCtxt<'a, 'tcx, 'tcx>, mbcx.flow_state.results() } -pub fn move_path_children_matching<'tcx, F>(move_data: &MoveData<'tcx>, - path: MovePathIndex, - mut cond: F) - -> Option +pub(crate) fn move_path_children_matching<'tcx, F>(move_data: &MoveData<'tcx>, + path: MovePathIndex, + mut cond: F) + -> Option where F: FnMut(&mir::LvalueProjection<'tcx>) -> bool { let mut next_child = move_data.move_paths[path].first_child; diff --git a/src/librustc_mir/dataflow/graphviz.rs b/src/librustc_mir/dataflow/graphviz.rs index e6d77aa2686af..134a2843d02b7 100644 --- a/src/librustc_mir/dataflow/graphviz.rs +++ b/src/librustc_mir/dataflow/graphviz.rs @@ -65,11 +65,11 @@ impl DataflowState { } } - pub fn interpret_set<'c, P>(&self, - o: &'c O, - words: &IdxSet, - render_idx: &P) - -> Vec<&'c Debug> + pub(crate) fn interpret_set<'c, P>(&self, + o: &'c O, + words: &IdxSet, + render_idx: &P) + -> Vec<&'c Debug> where P: Fn(&O, O::Idx) -> &Debug { let mut v = Vec::new(); @@ -80,7 +80,7 @@ impl DataflowState { } } -pub trait MirWithFlowState<'tcx> { +pub(crate) trait MirWithFlowState<'tcx> { type BD: BitDenotation; fn node_id(&self) -> NodeId; fn mir(&self) -> &Mir<'tcx>; @@ -120,10 +120,10 @@ pub(crate) fn print_borrowck_graph_to<'a, 'tcx, BD, P>( File::create(path).and_then(|mut f| f.write_all(&v)) } -pub type Node = BasicBlock; +pub(crate) type Node = BasicBlock; #[derive(Copy, Clone, PartialEq, Eq, Debug)] -pub struct Edge { source: BasicBlock, index: usize } +pub(crate) struct Edge { source: BasicBlock, index: usize } fn outgoing(mir: &Mir, bb: BasicBlock) -> Vec { let succ_len = mir[bb].terminator().successors().len(); diff --git a/src/librustc_mir/dataflow/impls/mod.rs b/src/librustc_mir/dataflow/impls/mod.rs index 97c996dea68f6..98a6ff28291a1 100644 --- a/src/librustc_mir/dataflow/impls/mod.rs +++ b/src/librustc_mir/dataflow/impls/mod.rs @@ -14,15 +14,13 @@ use rustc::ty::TyCtxt; use rustc::mir::{self, Mir, Location}; -use rustc_data_structures::bitslice::BitSlice; // adds set_bit/get_bit to &[usize] bitvector rep. use rustc_data_structures::bitslice::{BitwiseOperator}; use rustc_data_structures::indexed_set::{IdxSet}; -use rustc_data_structures::indexed_vec::Idx; use super::MoveDataParamEnv; use util::elaborate_drops::DropFlagState; -use super::move_paths::{HasMoveData, MoveData, MoveOutIndex, MovePathIndex}; +use super::move_paths::{HasMoveData, MoveData, MovePathIndex}; use super::{BitDenotation, BlockSets, DataflowOperator}; use super::drop_flag_effects_for_function_entry; @@ -64,17 +62,17 @@ use super::on_lookup_result_bits; /// Similarly, at a given `drop` statement, the set-intersection /// between this data and `MaybeUninitializedLvals` yields the set of /// l-values that would require a dynamic drop-flag at that statement. -pub struct MaybeInitializedLvals<'a, 'tcx: 'a> { +pub(crate) struct MaybeInitializedLvals<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx>, mir: &'a Mir<'tcx>, mdpe: &'a MoveDataParamEnv<'tcx>, } impl<'a, 'tcx: 'a> MaybeInitializedLvals<'a, 'tcx> { - pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, - mir: &'a Mir<'tcx>, - mdpe: &'a MoveDataParamEnv<'tcx>) - -> Self + pub(crate) fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, + mir: &'a Mir<'tcx>, + mdpe: &'a MoveDataParamEnv<'tcx>) + -> Self { MaybeInitializedLvals { tcx: tcx, mir: mir, mdpe: mdpe } } @@ -119,17 +117,17 @@ impl<'a, 'tcx: 'a> HasMoveData<'tcx> for MaybeInitializedLvals<'a, 'tcx> { /// Similarly, at a given `drop` statement, the set-intersection /// between this data and `MaybeInitializedLvals` yields the set of /// l-values that would require a dynamic drop-flag at that statement. -pub struct MaybeUninitializedLvals<'a, 'tcx: 'a> { +pub(crate) struct MaybeUninitializedLvals<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx>, mir: &'a Mir<'tcx>, mdpe: &'a MoveDataParamEnv<'tcx>, } impl<'a, 'tcx: 'a> MaybeUninitializedLvals<'a, 'tcx> { - pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, - mir: &'a Mir<'tcx>, - mdpe: &'a MoveDataParamEnv<'tcx>) - -> Self + pub(crate) fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, + mir: &'a Mir<'tcx>, + mdpe: &'a MoveDataParamEnv<'tcx>) + -> Self { MaybeUninitializedLvals { tcx: tcx, mir: mir, mdpe: mdpe } } @@ -180,17 +178,17 @@ impl<'a, 'tcx: 'a> HasMoveData<'tcx> for MaybeUninitializedLvals<'a, 'tcx> { /// Similarly, at a given `drop` statement, the set-difference between /// this data and `MaybeInitializedLvals` yields the set of l-values /// that would require a dynamic drop-flag at that statement. -pub struct DefinitelyInitializedLvals<'a, 'tcx: 'a> { +pub(crate) struct DefinitelyInitializedLvals<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx>, mir: &'a Mir<'tcx>, mdpe: &'a MoveDataParamEnv<'tcx>, } impl<'a, 'tcx: 'a> DefinitelyInitializedLvals<'a, 'tcx> { - pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, - mir: &'a Mir<'tcx>, - mdpe: &'a MoveDataParamEnv<'tcx>) - -> Self + pub(crate) fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, + mir: &'a Mir<'tcx>, + mdpe: &'a MoveDataParamEnv<'tcx>) + -> Self { DefinitelyInitializedLvals { tcx: tcx, mir: mir, mdpe: mdpe } } @@ -200,40 +198,6 @@ impl<'a, 'tcx: 'a> HasMoveData<'tcx> for DefinitelyInitializedLvals<'a, 'tcx> { fn move_data(&self) -> &MoveData<'tcx> { &self.mdpe.move_data } } -/// `MovingOutStatements` tracks the statements that perform moves out -/// of particular l-values. More precisely, it tracks whether the -/// *effect* of such moves (namely, the uninitialization of the -/// l-value in question) can reach some point in the control-flow of -/// the function, or if that effect is "killed" by some intervening -/// operation reinitializing that l-value. -/// -/// The resulting dataflow is a more enriched version of -/// `MaybeUninitializedLvals`. Both structures on their own only tell -/// you if an l-value *might* be uninitialized at a given point in the -/// control flow. But `MovingOutStatements` also includes the added -/// data of *which* particular statement causing the deinitialization -/// that the borrow checker's error meessage may need to report. -#[allow(dead_code)] -pub struct MovingOutStatements<'a, 'tcx: 'a> { - tcx: TyCtxt<'a, 'tcx, 'tcx>, - mir: &'a Mir<'tcx>, - mdpe: &'a MoveDataParamEnv<'tcx>, -} - -impl<'a, 'tcx: 'a> MovingOutStatements<'a, 'tcx> { - pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, - mir: &'a Mir<'tcx>, - mdpe: &'a MoveDataParamEnv<'tcx>) - -> Self - { - MovingOutStatements { tcx: tcx, mir: mir, mdpe: mdpe } - } -} - -impl<'a, 'tcx> HasMoveData<'tcx> for MovingOutStatements<'a, 'tcx> { - fn move_data(&self) -> &MoveData<'tcx> { &self.mdpe.move_data } -} - impl<'a, 'tcx> MaybeInitializedLvals<'a, 'tcx> { fn update_bits(sets: &mut BlockSets, path: MovePathIndex, state: DropFlagState) @@ -434,112 +398,6 @@ impl<'a, 'tcx> BitDenotation for DefinitelyInitializedLvals<'a, 'tcx> { } } -impl<'a, 'tcx> BitDenotation for MovingOutStatements<'a, 'tcx> { - type Idx = MoveOutIndex; - fn name() -> &'static str { "moving_out" } - fn bits_per_block(&self) -> usize { - self.move_data().moves.len() - } - - fn start_block_effect(&self, _sets: &mut BlockSets) { - // no move-statements have been executed prior to function - // execution, so this method has no effect on `_sets`. - } - fn statement_effect(&self, - sets: &mut BlockSets, - bb: mir::BasicBlock, - idx: usize) { - let (tcx, mir, move_data) = (self.tcx, self.mir, self.move_data()); - let stmt = &mir[bb].statements[idx]; - let loc_map = &move_data.loc_map; - let path_map = &move_data.path_map; - let rev_lookup = &move_data.rev_lookup; - - let loc = Location { block: bb, statement_index: idx }; - debug!("stmt {:?} at loc {:?} moves out of move_indexes {:?}", - stmt, loc, &loc_map[loc]); - for move_index in &loc_map[loc] { - // Every path deinitialized by a *particular move* - // has corresponding bit, "gen'ed" (i.e. set) - // here, in dataflow vector - zero_to_one(sets.gen_set.words_mut(), *move_index); - } - let bits_per_block = self.bits_per_block(); - match stmt.kind { - mir::StatementKind::SetDiscriminant { .. } => { - span_bug!(stmt.source_info.span, "SetDiscriminant should not exist in borrowck"); - } - mir::StatementKind::Assign(ref lvalue, _) => { - // assigning into this `lvalue` kills all - // MoveOuts from it, and *also* all MoveOuts - // for children and associated fragment sets. - on_lookup_result_bits(tcx, - mir, - move_data, - rev_lookup.find(lvalue), - |mpi| for moi in &path_map[mpi] { - assert!(moi.index() < bits_per_block); - sets.kill_set.add(&moi); - }); - } - mir::StatementKind::StorageLive(_) | - mir::StatementKind::StorageDead(_) | - mir::StatementKind::InlineAsm { .. } | - mir::StatementKind::EndRegion(_) | - mir::StatementKind::Nop => {} - } - } - - fn terminator_effect(&self, - sets: &mut BlockSets, - bb: mir::BasicBlock, - statements_len: usize) - { - let (mir, move_data) = (self.mir, self.move_data()); - let term = mir[bb].terminator(); - let loc_map = &move_data.loc_map; - let loc = Location { block: bb, statement_index: statements_len }; - debug!("terminator {:?} at loc {:?} moves out of move_indexes {:?}", - term, loc, &loc_map[loc]); - let bits_per_block = self.bits_per_block(); - for move_index in &loc_map[loc] { - assert!(move_index.index() < bits_per_block); - zero_to_one(sets.gen_set.words_mut(), *move_index); - } - } - - fn propagate_call_return(&self, - in_out: &mut IdxSet, - _call_bb: mir::BasicBlock, - _dest_bb: mir::BasicBlock, - dest_lval: &mir::Lvalue) { - let move_data = self.move_data(); - let bits_per_block = self.bits_per_block(); - - let path_map = &move_data.path_map; - on_lookup_result_bits(self.tcx, - self.mir, - move_data, - move_data.rev_lookup.find(dest_lval), - |mpi| for moi in &path_map[mpi] { - assert!(moi.index() < bits_per_block); - in_out.remove(&moi); - }); - } -} - -fn zero_to_one(bitvec: &mut [usize], move_index: MoveOutIndex) { - let retval = bitvec.set_bit(move_index.index()); - assert!(retval); -} - -impl<'a, 'tcx> BitwiseOperator for MovingOutStatements<'a, 'tcx> { - #[inline] - fn join(&self, pred1: usize, pred2: usize) -> usize { - pred1 | pred2 // moves from both preds are in scope - } -} - impl<'a, 'tcx> BitwiseOperator for MaybeInitializedLvals<'a, 'tcx> { #[inline] fn join(&self, pred1: usize, pred2: usize) -> usize { @@ -571,13 +429,6 @@ impl<'a, 'tcx> BitwiseOperator for DefinitelyInitializedLvals<'a, 'tcx> { // propagating, or you start at all-ones and then use Intersect as // your merge when propagating. -impl<'a, 'tcx> DataflowOperator for MovingOutStatements<'a, 'tcx> { - #[inline] - fn bottom_value() -> bool { - false // bottom = no loans in scope by default - } -} - impl<'a, 'tcx> DataflowOperator for MaybeInitializedLvals<'a, 'tcx> { #[inline] fn bottom_value() -> bool { diff --git a/src/librustc_mir/dataflow/mod.rs b/src/librustc_mir/dataflow/mod.rs index d7ad9f9c09aef..c76e89804a6ff 100644 --- a/src/librustc_mir/dataflow/mod.rs +++ b/src/librustc_mir/dataflow/mod.rs @@ -23,15 +23,15 @@ use std::mem; use std::path::PathBuf; use std::usize; -pub use self::impls::{MaybeInitializedLvals, MaybeUninitializedLvals}; -pub use self::impls::{DefinitelyInitializedLvals, MovingOutStatements}; +pub(crate) use self::impls::{MaybeInitializedLvals, MaybeUninitializedLvals}; +pub(crate) use self::impls::{DefinitelyInitializedLvals}; pub(crate) use self::drop_flag_effects::*; mod drop_flag_effects; mod graphviz; mod impls; -pub mod move_paths; +pub(crate) mod move_paths; pub(crate) use self::move_paths::indexes; @@ -43,7 +43,7 @@ pub(crate) struct DataflowBuilder<'a, 'tcx: 'a, BD> where BD: BitDenotation print_postflow_to: Option, } -pub trait Dataflow { +pub(crate) trait Dataflow { fn dataflow

(&mut self, p: P) where P: Fn(&BD, BD::Idx) -> &Debug; } @@ -189,7 +189,7 @@ impl Bits { } } -pub struct DataflowAnalysis<'a, 'tcx: 'a, O> +pub(crate) struct DataflowAnalysis<'a, 'tcx: 'a, O> where O: BitDenotation { flow_state: DataflowState, @@ -200,36 +200,36 @@ pub struct DataflowAnalysis<'a, 'tcx: 'a, O> impl<'a, 'tcx: 'a, O> DataflowAnalysis<'a, 'tcx, O> where O: BitDenotation { - pub fn results(self) -> DataflowResults { + pub(crate) fn results(self) -> DataflowResults { DataflowResults(self.flow_state) } - pub fn mir(&self) -> &'a Mir<'tcx> { self.mir } + pub(crate) fn mir(&self) -> &'a Mir<'tcx> { self.mir } } -pub struct DataflowResults(pub(crate) DataflowState) where O: BitDenotation; +pub(crate) struct DataflowResults(pub(crate) DataflowState) where O: BitDenotation; impl DataflowResults { - pub fn sets(&self) -> &AllSets { + pub(crate) fn sets(&self) -> &AllSets { &self.0.sets } } // FIXME: This type shouldn't be public, but the graphviz::MirWithFlowState trait // references it in a method signature. Look into using `pub(crate)` to address this. -pub struct DataflowState +pub(crate) struct DataflowState { /// All the sets for the analysis. (Factored into its /// own structure so that we can borrow it mutably /// on its own separate from other fields.) - pub sets: AllSets, + pub(crate) sets: AllSets, /// operator used to initialize, combine, and interpret bits. pub(crate) operator: O, } #[derive(Debug)] -pub struct AllSets { +pub(crate) struct AllSets { /// Analysis bitwidth for each block. bits_per_block: usize, @@ -251,7 +251,7 @@ pub struct AllSets { on_entry_sets: Bits, } -pub struct BlockSets<'a, E: Idx> { +pub(crate) struct BlockSets<'a, E: Idx> { pub(crate) on_entry: &'a mut IdxSet, pub(crate) gen_set: &'a mut IdxSet, pub(crate) kill_set: &'a mut IdxSet, @@ -269,8 +269,8 @@ impl<'a, E:Idx> BlockSets<'a, E> { } impl AllSets { - pub fn bits_per_block(&self) -> usize { self.bits_per_block } - pub fn for_block(&mut self, block_idx: usize) -> BlockSets { + pub(crate) fn bits_per_block(&self) -> usize { self.bits_per_block } + pub(crate) fn for_block(&mut self, block_idx: usize) -> BlockSets { let offset = self.words_per_block * block_idx; let range = E::new(offset)..E::new(offset + self.words_per_block); BlockSets { @@ -285,24 +285,24 @@ impl AllSets { let range = E::new(offset)..E::new(offset + self.words_per_block); sets.bits.range(&range) } - pub fn gen_set_for(&self, block_idx: usize) -> &IdxSet { + pub(crate) fn gen_set_for(&self, block_idx: usize) -> &IdxSet { self.lookup_set_for(&self.gen_sets, block_idx) } - pub fn kill_set_for(&self, block_idx: usize) -> &IdxSet { + pub(crate) fn kill_set_for(&self, block_idx: usize) -> &IdxSet { self.lookup_set_for(&self.kill_sets, block_idx) } - pub fn on_entry_set_for(&self, block_idx: usize) -> &IdxSet { + pub(crate) fn on_entry_set_for(&self, block_idx: usize) -> &IdxSet { self.lookup_set_for(&self.on_entry_sets, block_idx) } } /// Parameterization for the precise form of data flow that is used. -pub trait DataflowOperator: BitwiseOperator { +pub(crate) trait DataflowOperator: BitwiseOperator { /// Specifies the initial value for each bit in the `on_entry` set fn bottom_value() -> bool; } -pub trait BitDenotation { +pub(crate) trait BitDenotation { /// Specifies what index type is used to access the bitvector. type Idx: Idx; @@ -388,10 +388,10 @@ pub trait BitDenotation { impl<'a, 'tcx: 'a, D> DataflowAnalysis<'a, 'tcx, D> where D: BitDenotation + DataflowOperator { - pub fn new(_tcx: TyCtxt<'a, 'tcx, 'tcx>, - mir: &'a Mir<'tcx>, - dead_unwinds: &'a IdxSet, - denotation: D) -> Self { + pub(crate) fn new(_tcx: TyCtxt<'a, 'tcx, 'tcx>, + mir: &'a Mir<'tcx>, + dead_unwinds: &'a IdxSet, + denotation: D) -> Self { let bits_per_block = denotation.bits_per_block(); let usize_bits = mem::size_of::() * 8; let words_per_block = (bits_per_block + usize_bits - 1) / usize_bits; diff --git a/src/librustc_mir/dataflow/move_paths/abs_domain.rs b/src/librustc_mir/dataflow/move_paths/abs_domain.rs index 5e61c2ec7a292..76867fcb46cba 100644 --- a/src/librustc_mir/dataflow/move_paths/abs_domain.rs +++ b/src/librustc_mir/dataflow/move_paths/abs_domain.rs @@ -25,11 +25,11 @@ use rustc::mir::LvalueElem; use rustc::mir::{Operand, ProjectionElem}; #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] -pub struct AbstractOperand; -pub type AbstractElem<'tcx> = +pub(crate) struct AbstractOperand; +pub(crate) type AbstractElem<'tcx> = ProjectionElem<'tcx, AbstractOperand>; -pub trait Lift { +pub(crate) trait Lift { type Abstract; fn lift(&self) -> Self::Abstract; } diff --git a/src/librustc_mir/dataflow/move_paths/mod.rs b/src/librustc_mir/dataflow/move_paths/mod.rs index d7ed0938e886a..e3d02d0e0509a 100644 --- a/src/librustc_mir/dataflow/move_paths/mod.rs +++ b/src/librustc_mir/dataflow/move_paths/mod.rs @@ -38,7 +38,7 @@ pub(crate) mod indexes { macro_rules! new_index { ($Index:ident, $debug_name:expr) => { #[derive(Copy, Clone, PartialEq, Eq, Hash)] - pub struct $Index(NonZero); + pub(crate) struct $Index(NonZero); impl Idx for $Index { fn new(idx: usize) -> Self { @@ -64,11 +64,11 @@ pub(crate) mod indexes { new_index!(MoveOutIndex, "mo"); } -pub use self::indexes::MovePathIndex; -pub use self::indexes::MoveOutIndex; +pub(crate) use self::indexes::MovePathIndex; +pub(crate) use self::indexes::MoveOutIndex; impl MoveOutIndex { - pub fn move_path_index(&self, move_data: &MoveData) -> MovePathIndex { + pub(crate) fn move_path_index(&self, move_data: &MoveData) -> MovePathIndex { move_data.moves[*self].path } } @@ -86,11 +86,11 @@ impl MoveOutIndex { /// and the other will have no entry in its `next_sibling` field), and /// they both have the MovePath representing `x` as their parent. #[derive(Clone)] -pub struct MovePath<'tcx> { - pub next_sibling: Option, - pub first_child: Option, - pub parent: Option, - pub lvalue: Lvalue<'tcx>, +pub(crate) struct MovePath<'tcx> { + pub(crate) next_sibling: Option, + pub(crate) first_child: Option, + pub(crate) parent: Option, + pub(crate) lvalue: Lvalue<'tcx>, } impl<'tcx> fmt::Debug for MovePath<'tcx> { @@ -110,24 +110,24 @@ impl<'tcx> fmt::Debug for MovePath<'tcx> { } #[derive(Debug)] -pub struct MoveData<'tcx> { - pub move_paths: IndexVec>, - pub moves: IndexVec, +pub(crate) struct MoveData<'tcx> { + pub(crate) move_paths: IndexVec>, + pub(crate) moves: IndexVec, /// Each Location `l` is mapped to the MoveOut's that are effects /// of executing the code at `l`. (There can be multiple MoveOut's /// for a given `l` because each MoveOut is associated with one /// particular path being moved.) - pub loc_map: LocationMap>, - pub path_map: IndexVec>, - pub rev_lookup: MovePathLookup<'tcx>, + pub(crate) loc_map: LocationMap>, + pub(crate) path_map: IndexVec>, + pub(crate) rev_lookup: MovePathLookup<'tcx>, } -pub trait HasMoveData<'tcx> { +pub(crate) trait HasMoveData<'tcx> { fn move_data(&self) -> &MoveData<'tcx>; } #[derive(Debug)] -pub struct LocationMap { +pub(crate) struct LocationMap { /// Location-indexed (BasicBlock for outer index, index within BB /// for inner index) map. pub(crate) map: IndexVec>, @@ -163,11 +163,11 @@ impl LocationMap where T: Default + Clone { /// - Generated by moves and declaration of uninitialized variables. /// - Killed by assignments to the memory. #[derive(Copy, Clone)] -pub struct MoveOut { +pub(crate) struct MoveOut { /// path being moved - pub path: MovePathIndex, + pub(crate) path: MovePathIndex, /// location of move - pub source: Location, + pub(crate) source: Location, } impl fmt::Debug for MoveOut { @@ -178,7 +178,7 @@ impl fmt::Debug for MoveOut { /// Tables mapping from an l-value to its MovePathIndex. #[derive(Debug)] -pub struct MovePathLookup<'tcx> { +pub(crate) struct MovePathLookup<'tcx> { locals: IndexVec, /// projections are made from a base-lvalue and a projection @@ -197,7 +197,7 @@ pub(super) struct MoveDataBuilder<'a, 'tcx: 'a> { data: MoveData<'tcx>, } -pub enum MovePathError { +pub(crate) enum MovePathError { IllegalMove, UnionMove { path: MovePathIndex }, } @@ -340,7 +340,7 @@ impl<'a, 'tcx> MoveDataBuilder<'a, 'tcx> { } #[derive(Copy, Clone, Debug)] -pub enum LookupResult { +pub(crate) enum LookupResult { Exact(MovePathIndex), Parent(Option) } @@ -350,7 +350,7 @@ impl<'tcx> MovePathLookup<'tcx> { // alternative will *not* create a MovePath on the fly for an // unknown l-value, but will rather return the nearest available // parent. - pub fn find(&self, lval: &Lvalue<'tcx>) -> LookupResult { + pub(crate) fn find(&self, lval: &Lvalue<'tcx>) -> LookupResult { match *lval { Lvalue::Local(local) => LookupResult::Exact(self.locals[local]), Lvalue::Static(..) => LookupResult::Parent(None), @@ -370,10 +370,10 @@ impl<'tcx> MovePathLookup<'tcx> { } impl<'a, 'tcx> MoveData<'tcx> { - pub fn gather_moves(mir: &Mir<'tcx>, - tcx: TyCtxt<'a, 'tcx, 'tcx>, - param_env: ty::ParamEnv<'tcx>) - -> Self { + pub(crate) fn gather_moves(mir: &Mir<'tcx>, + tcx: TyCtxt<'a, 'tcx, 'tcx>, + param_env: ty::ParamEnv<'tcx>) + -> Self { gather_moves(mir, tcx, param_env) } } diff --git a/src/librustc_mir/hair/cx/block.rs b/src/librustc_mir/hair/cx/block.rs index fad070ca8d8f9..850c10d392a38 100644 --- a/src/librustc_mir/hair/cx/block.rs +++ b/src/librustc_mir/hair/cx/block.rs @@ -89,9 +89,9 @@ fn mirror_stmts<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>, return result; } -pub fn to_expr_ref<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>, - block: &'tcx hir::Block) - -> ExprRef<'tcx> { +pub(crate) fn to_expr_ref<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>, + block: &'tcx hir::Block) + -> ExprRef<'tcx> { let block_ty = cx.tables().node_id_to_type(block.id); let temp_lifetime = cx.region_maps.temporary_scope(block.id); let expr = Expr { diff --git a/src/librustc_mir/hair/cx/mod.rs b/src/librustc_mir/hair/cx/mod.rs index 2bb6b39966a82..ef696b6c03218 100644 --- a/src/librustc_mir/hair/cx/mod.rs +++ b/src/librustc_mir/hair/cx/mod.rs @@ -32,26 +32,26 @@ use rustc_const_math::{ConstInt, ConstUsize}; use std::rc::Rc; #[derive(Clone)] -pub struct Cx<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> { +pub(crate) struct Cx<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> { tcx: TyCtxt<'a, 'gcx, 'tcx>, infcx: &'a InferCtxt<'a, 'gcx, 'tcx>, - pub param_env: ty::ParamEnv<'tcx>, - pub region_maps: Rc, - pub tables: &'a ty::TypeckTables<'gcx>, + pub(crate) param_env: ty::ParamEnv<'tcx>, + pub(crate) region_maps: Rc, + pub(crate) tables: &'a ty::TypeckTables<'gcx>, /// This is `Constness::Const` if we are compiling a `static`, /// `const`, or the body of a `const fn`. constness: hir::Constness, /// What are we compiling? - pub src: MirSource, + pub(crate) src: MirSource, /// True if this constant/function needs overflow checks. check_overflow: bool, } impl<'a, 'gcx, 'tcx> Cx<'a, 'gcx, 'tcx> { - pub fn new(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>, src: MirSource) -> Cx<'a, 'gcx, 'tcx> { + pub(crate) fn new(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>, src: MirSource) -> Cx<'a, 'gcx, 'tcx> { let constness = match src { MirSource::Const(_) | MirSource::Static(..) => hir::Constness::Const, @@ -90,38 +90,38 @@ impl<'a, 'gcx, 'tcx> Cx<'a, 'gcx, 'tcx> { impl<'a, 'gcx, 'tcx> Cx<'a, 'gcx, 'tcx> { /// Normalizes `ast` into the appropriate `mirror` type. - pub fn mirror>(&mut self, ast: M) -> M::Output { + pub(crate) fn mirror>(&mut self, ast: M) -> M::Output { ast.make_mirror(self) } - pub fn usize_ty(&mut self) -> Ty<'tcx> { + pub(crate) fn usize_ty(&mut self) -> Ty<'tcx> { self.tcx.types.usize } - pub fn usize_literal(&mut self, value: u64) -> Literal<'tcx> { + pub(crate) fn usize_literal(&mut self, value: u64) -> Literal<'tcx> { match ConstUsize::new(value, self.tcx.sess.target.uint_type) { Ok(val) => Literal::Value { value: ConstVal::Integral(ConstInt::Usize(val)) }, Err(_) => bug!("usize literal out of range for target"), } } - pub fn bool_ty(&mut self) -> Ty<'tcx> { + pub(crate) fn bool_ty(&mut self) -> Ty<'tcx> { self.tcx.types.bool } - pub fn unit_ty(&mut self) -> Ty<'tcx> { + pub(crate) fn unit_ty(&mut self) -> Ty<'tcx> { self.tcx.mk_nil() } - pub fn true_literal(&mut self) -> Literal<'tcx> { + pub(crate) fn true_literal(&mut self) -> Literal<'tcx> { Literal::Value { value: ConstVal::Bool(true) } } - pub fn false_literal(&mut self) -> Literal<'tcx> { + pub(crate) fn false_literal(&mut self) -> Literal<'tcx> { Literal::Value { value: ConstVal::Bool(false) } } - pub fn const_eval_literal(&mut self, e: &hir::Expr) -> Literal<'tcx> { + pub(crate) fn const_eval_literal(&mut self, e: &hir::Expr) -> Literal<'tcx> { let tcx = self.tcx.global_tcx(); match ConstContext::with_tables(tcx, self.tables()).eval(e) { Ok(value) => Literal::Value { value: value }, @@ -129,7 +129,7 @@ impl<'a, 'gcx, 'tcx> Cx<'a, 'gcx, 'tcx> { } } - pub fn fatal_const_eval_err(&self, + pub(crate) fn fatal_const_eval_err(&self, err: &ConstEvalErr<'tcx>, primary_span: Span, primary_kind: &str) @@ -140,12 +140,12 @@ impl<'a, 'gcx, 'tcx> Cx<'a, 'gcx, 'tcx> { unreachable!() } - pub fn trait_method(&mut self, - trait_def_id: DefId, - method_name: &str, - self_ty: Ty<'tcx>, - params: &[Ty<'tcx>]) - -> (Ty<'tcx>, Literal<'tcx>) { + pub(crate) fn trait_method(&mut self, + trait_def_id: DefId, + method_name: &str, + self_ty: Ty<'tcx>, + params: &[Ty<'tcx>]) + -> (Ty<'tcx>, Literal<'tcx>) { let method_name = Symbol::intern(method_name); let substs = self.tcx.mk_substs_trait(self_ty, params); for item in self.tcx.associated_items(trait_def_id) { @@ -162,17 +162,17 @@ impl<'a, 'gcx, 'tcx> Cx<'a, 'gcx, 'tcx> { bug!("found no method `{}` in `{:?}`", method_name, trait_def_id); } - pub fn num_variants(&mut self, adt_def: &ty::AdtDef) -> usize { + pub(crate) fn num_variants(&mut self, adt_def: &ty::AdtDef) -> usize { adt_def.variants.len() } - pub fn all_fields(&mut self, adt_def: &ty::AdtDef, variant_index: usize) -> Vec { + pub(crate) fn all_fields(&mut self, adt_def: &ty::AdtDef, variant_index: usize) -> Vec { (0..adt_def.variants[variant_index].fields.len()) .map(Field::new) .collect() } - pub fn needs_drop(&mut self, ty: Ty<'tcx>) -> bool { + pub(crate) fn needs_drop(&mut self, ty: Ty<'tcx>) -> bool { let (ty, param_env) = self.tcx.lift_to_global(&(ty, self.param_env)).unwrap_or_else(|| { bug!("MIR: Cx::needs_drop({:?}, {:?}) got \ type with inference types/regions", @@ -181,15 +181,15 @@ impl<'a, 'gcx, 'tcx> Cx<'a, 'gcx, 'tcx> { ty.needs_drop(self.tcx.global_tcx(), param_env) } - pub fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> { + pub(crate) fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> { self.tcx } - pub fn tables(&self) -> &'a ty::TypeckTables<'gcx> { + pub(crate) fn tables(&self) -> &'a ty::TypeckTables<'gcx> { self.tables } - pub fn check_overflow(&self) -> bool { + pub(crate) fn check_overflow(&self) -> bool { self.check_overflow } } diff --git a/src/librustc_mir/hair/cx/to_ref.rs b/src/librustc_mir/hair/cx/to_ref.rs index 6930a959d6515..f7a9a6bd74bca 100644 --- a/src/librustc_mir/hair/cx/to_ref.rs +++ b/src/librustc_mir/hair/cx/to_ref.rs @@ -13,7 +13,7 @@ use hair::*; use rustc::hir; use syntax::ptr::P; -pub trait ToRef { +pub(crate) trait ToRef { type Output; fn to_ref(self) -> Self::Output; } diff --git a/src/librustc_mir/hair/mod.rs b/src/librustc_mir/hair/mod.rs index bb11cce748751..3ae6c98c6dac9 100644 --- a/src/librustc_mir/hair/mod.rs +++ b/src/librustc_mir/hair/mod.rs @@ -25,34 +25,34 @@ use syntax::ast; use syntax_pos::Span; use self::cx::Cx; -pub mod cx; +pub(crate) mod cx; -pub use rustc_const_eval::pattern::{BindingMode, Pattern, PatternKind, FieldPattern}; +pub(crate) use rustc_const_eval::pattern::{BindingMode, Pattern, PatternKind, FieldPattern}; #[derive(Clone, Debug)] -pub struct Block<'tcx> { - pub targeted_by_break: bool, - pub extent: CodeExtent, - pub opt_destruction_extent: Option, - pub span: Span, - pub stmts: Vec>, - pub expr: Option>, +pub(crate) struct Block<'tcx> { + pub(crate) targeted_by_break: bool, + pub(crate) extent: CodeExtent, + pub(crate) opt_destruction_extent: Option, + pub(crate) span: Span, + pub(crate) stmts: Vec>, + pub(crate) expr: Option>, } #[derive(Clone, Debug)] -pub enum StmtRef<'tcx> { +pub(crate) enum StmtRef<'tcx> { Mirror(Box>), } #[derive(Clone, Debug)] -pub struct Stmt<'tcx> { - pub span: Span, - pub kind: StmtKind<'tcx>, - pub opt_destruction_extent: Option, +pub(crate) struct Stmt<'tcx> { + pub(crate) span: Span, + pub(crate) kind: StmtKind<'tcx>, + pub(crate) opt_destruction_extent: Option, } #[derive(Clone, Debug)] -pub enum StmtKind<'tcx> { +pub(crate) enum StmtKind<'tcx> { Expr { /// scope for this statement; may be used as lifetime of temporaries scope: CodeExtent, @@ -93,23 +93,23 @@ pub enum StmtKind<'tcx> { /// example, method calls and overloaded operators are absent: they are /// expected to be converted into `Expr::Call` instances. #[derive(Clone, Debug)] -pub struct Expr<'tcx> { +pub(crate) struct Expr<'tcx> { /// type of this expression - pub ty: Ty<'tcx>, + pub(crate) ty: Ty<'tcx>, /// lifetime of this expression if it should be spilled into a /// temporary; should be None only if in a constant context - pub temp_lifetime: Option, + pub(crate) temp_lifetime: Option, /// span of the expression in the source - pub span: Span, + pub(crate) span: Span, /// kind of expression - pub kind: ExprKind<'tcx>, + pub(crate) kind: ExprKind<'tcx>, } #[derive(Clone, Debug)] -pub enum ExprKind<'tcx> { +pub(crate) enum ExprKind<'tcx> { Scope { extent: CodeExtent, value: ExprRef<'tcx>, @@ -251,32 +251,32 @@ pub enum ExprKind<'tcx> { } #[derive(Clone, Debug)] -pub enum ExprRef<'tcx> { +pub(crate) enum ExprRef<'tcx> { Hair(&'tcx hir::Expr), Mirror(Box>), } #[derive(Clone, Debug)] -pub struct FieldExprRef<'tcx> { - pub name: Field, - pub expr: ExprRef<'tcx>, +pub(crate) struct FieldExprRef<'tcx> { + pub(crate) name: Field, + pub(crate) expr: ExprRef<'tcx>, } #[derive(Clone, Debug)] -pub struct FruInfo<'tcx> { - pub base: ExprRef<'tcx>, - pub field_types: Vec> +pub(crate) struct FruInfo<'tcx> { + pub(crate) base: ExprRef<'tcx>, + pub(crate) field_types: Vec> } #[derive(Clone, Debug)] -pub struct Arm<'tcx> { - pub patterns: Vec>, - pub guard: Option>, - pub body: ExprRef<'tcx>, +pub(crate) struct Arm<'tcx> { + pub(crate) patterns: Vec>, + pub(crate) guard: Option>, + pub(crate) body: ExprRef<'tcx>, } #[derive(Copy, Clone, Debug)] -pub enum LogicalOp { +pub(crate) enum LogicalOp { And, Or, } @@ -296,7 +296,7 @@ pub enum LogicalOp { /// mirrored. This allows a single AST node from the compiler to /// expand into one or more Hair nodes, which lets the Hair nodes be /// simpler. -pub trait Mirror<'tcx> { +pub(crate) trait Mirror<'tcx> { type Output; fn make_mirror<'a, 'gcx>(self, cx: &mut Cx<'a, 'gcx, 'tcx>) -> Self::Output; diff --git a/src/librustc_mir/lib.rs b/src/librustc_mir/lib.rs index bb1767773327c..2f143cf964639 100644 --- a/src/librustc_mir/lib.rs +++ b/src/librustc_mir/lib.rs @@ -44,10 +44,10 @@ extern crate rustc_const_math; extern crate rustc_const_eval; extern crate core; // for NonZero -pub mod diagnostics; +mod diagnostics; mod build; -pub mod dataflow; +mod dataflow; mod hair; mod shim; pub mod transform; diff --git a/src/librustc_mir/shim.rs b/src/librustc_mir/shim.rs index 11ad5d1509d29..2890a59cc1cca 100644 --- a/src/librustc_mir/shim.rs +++ b/src/librustc_mir/shim.rs @@ -31,7 +31,7 @@ use transform::{add_call_guards, no_landing_pads, simplify}; use util::elaborate_drops::{self, DropElaborator, DropStyle, DropFlagMode}; use util::patch::MirPatch; -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { providers.mir_shims = make_shim; } @@ -212,7 +212,7 @@ fn build_drop_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>, mir } -pub struct DropShimElaborator<'a, 'tcx: 'a> { +pub(crate) struct DropShimElaborator<'a, 'tcx: 'a> { mir: &'a Mir<'tcx>, patch: MirPatch<'tcx>, tcx: ty::TyCtxt<'a, 'tcx, 'tcx>, @@ -401,11 +401,11 @@ fn build_call_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>, mir } -pub fn build_adt_ctor<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>, - ctor_id: ast::NodeId, - fields: &[hir::StructField], - span: Span) - -> (Mir<'tcx>, MirSource) +pub(crate) fn build_adt_ctor<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>, + ctor_id: ast::NodeId, + fields: &[hir::StructField], + span: Span) + -> (Mir<'tcx>, MirSource) { let tcx = infcx.tcx; let def_id = tcx.hir.local_def_id(ctor_id); diff --git a/src/librustc_mir/transform/add_call_guards.rs b/src/librustc_mir/transform/add_call_guards.rs index b7c7a1774dd35..9151702fd0728 100644 --- a/src/librustc_mir/transform/add_call_guards.rs +++ b/src/librustc_mir/transform/add_call_guards.rs @@ -44,7 +44,7 @@ impl MirPass for AddCallGuards { } } -pub fn add_call_guards(mir: &mut Mir) { +pub(crate) fn add_call_guards(mir: &mut Mir) { let pred_count: IndexVec<_, _> = mir.predecessors().iter().map(|ps| ps.len()).collect(); diff --git a/src/librustc_mir/transform/dump_mir.rs b/src/librustc_mir/transform/dump_mir.rs index 67a3281dba48b..255d17c511d63 100644 --- a/src/librustc_mir/transform/dump_mir.rs +++ b/src/librustc_mir/transform/dump_mir.rs @@ -36,7 +36,7 @@ impl MirPass for Marker { } } -pub struct Disambiguator { +pub(crate) struct Disambiguator { is_after: bool } diff --git a/src/librustc_mir/transform/erase_regions.rs b/src/librustc_mir/transform/erase_regions.rs index eb283df869f12..ad135b61fa2c5 100644 --- a/src/librustc_mir/transform/erase_regions.rs +++ b/src/librustc_mir/transform/erase_regions.rs @@ -23,7 +23,7 @@ struct EraseRegionsVisitor<'a, 'tcx: 'a> { } impl<'a, 'tcx> EraseRegionsVisitor<'a, 'tcx> { - pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Self { + pub(crate) fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Self { EraseRegionsVisitor { tcx: tcx } diff --git a/src/librustc_mir/transform/instcombine.rs b/src/librustc_mir/transform/instcombine.rs index 88a368077d4f5..5cf3422cb7d77 100644 --- a/src/librustc_mir/transform/instcombine.rs +++ b/src/librustc_mir/transform/instcombine.rs @@ -44,7 +44,7 @@ impl MirPass for InstCombine { } } -pub struct InstCombineVisitor { +pub(crate) struct InstCombineVisitor { optimizations: OptimizationList, } diff --git a/src/librustc_mir/transform/mod.rs b/src/librustc_mir/transform/mod.rs index c9c8ad0e0eb63..a30ff6d70cc31 100644 --- a/src/librustc_mir/transform/mod.rs +++ b/src/librustc_mir/transform/mod.rs @@ -33,7 +33,7 @@ pub mod type_check; pub mod rustc_peek; pub mod elaborate_drops; pub mod add_call_guards; -pub mod promote_consts; +pub(crate) mod promote_consts; pub mod qualify_consts; pub mod dump_mir; pub mod deaggregator; diff --git a/src/librustc_mir/transform/no_landing_pads.rs b/src/librustc_mir/transform/no_landing_pads.rs index 8595663ba18c4..eea4f05eaa515 100644 --- a/src/librustc_mir/transform/no_landing_pads.rs +++ b/src/librustc_mir/transform/no_landing_pads.rs @@ -27,7 +27,7 @@ impl MirPass for NoLandingPads { } } -pub fn no_landing_pads<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, mir: &mut Mir<'tcx>) { +pub(crate) fn no_landing_pads<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, mir: &mut Mir<'tcx>) { if tcx.sess.no_landing_pads() { NoLandingPads.visit_mir(mir); } diff --git a/src/librustc_mir/transform/promote_consts.rs b/src/librustc_mir/transform/promote_consts.rs index e1c4602b045eb..5e7af01e1bd46 100644 --- a/src/librustc_mir/transform/promote_consts.rs +++ b/src/librustc_mir/transform/promote_consts.rs @@ -36,7 +36,7 @@ use std::usize; /// State of a temporary during collection and promotion. #[derive(Copy, Clone, PartialEq, Eq, Debug)] -pub enum TempState { +pub(crate) enum TempState { /// No references to this temp. Undefined, /// One direct assignment and any number of direct uses. @@ -54,7 +54,7 @@ pub enum TempState { } impl TempState { - pub fn is_promotable(&self) -> bool { + pub(crate) fn is_promotable(&self) -> bool { if let TempState::Defined { uses, .. } = *self { uses > 0 } else { @@ -67,7 +67,7 @@ impl TempState { /// returned value in a promoted MIR, unless it's a subset /// of a larger candidate. #[derive(Debug)] -pub enum Candidate { +pub(crate) enum Candidate { /// Borrow of a constant temporary. Ref(Location), @@ -136,7 +136,7 @@ impl<'tcx> Visitor<'tcx> for TempCollector<'tcx> { } } -pub fn collect_temps(mir: &Mir, rpo: &mut ReversePostorder) -> IndexVec { +pub(crate) fn collect_temps(mir: &Mir, rpo: &mut ReversePostorder) -> IndexVec { let mut collector = TempCollector { temps: IndexVec::from_elem(TempState::Undefined, &mir.local_decls), span: mir.span, @@ -339,10 +339,10 @@ impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> { } } -pub fn promote_candidates<'a, 'tcx>(mir: &mut Mir<'tcx>, - tcx: TyCtxt<'a, 'tcx, 'tcx>, - mut temps: IndexVec, - candidates: Vec) { +pub(crate) fn promote_candidates<'a, 'tcx>(mir: &mut Mir<'tcx>, + tcx: TyCtxt<'a, 'tcx, 'tcx>, + mut temps: IndexVec, + candidates: Vec) { // Visit candidates in reverse, in case they're nested. debug!("promote_candidates({:?})", candidates); for candidate in candidates.into_iter().rev() { diff --git a/src/librustc_mir/transform/qualify_consts.rs b/src/librustc_mir/transform/qualify_consts.rs index 9bb0f07aa68ac..e11ba6085ee75 100644 --- a/src/librustc_mir/transform/qualify_consts.rs +++ b/src/librustc_mir/transform/qualify_consts.rs @@ -921,7 +921,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Qualifier<'a, 'tcx, 'tcx> { } } -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { *providers = Providers { mir_const_qualif, ..*providers diff --git a/src/librustc_mir/transform/rustc_peek.rs b/src/librustc_mir/transform/rustc_peek.rs index 5918de0c68811..04a7b1b142085 100644 --- a/src/librustc_mir/transform/rustc_peek.rs +++ b/src/librustc_mir/transform/rustc_peek.rs @@ -92,11 +92,11 @@ impl MirPass for SanityCheck { /// (If there are any calls to `rustc_peek` that do not match the /// expression form above, then that emits an error as well, but those /// errors are not intended to be used for unit tests.) -pub fn sanity_check_via_rustc_peek<'a, 'tcx, O>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - mir: &Mir<'tcx>, - id: ast::NodeId, - _attributes: &[ast::Attribute], - results: &DataflowResults) +pub(crate) fn sanity_check_via_rustc_peek<'a, 'tcx, O>(tcx: TyCtxt<'a, 'tcx, 'tcx>, + mir: &Mir<'tcx>, + id: ast::NodeId, + _attributes: &[ast::Attribute], + results: &DataflowResults) where O: BitDenotation + HasMoveData<'tcx> { debug!("sanity_check_via_rustc_peek id: {:?}", id); diff --git a/src/librustc_mir/transform/simplify.rs b/src/librustc_mir/transform/simplify.rs index d5b79c0d1c382..0cd4bf3d08a5c 100644 --- a/src/librustc_mir/transform/simplify.rs +++ b/src/librustc_mir/transform/simplify.rs @@ -53,7 +53,7 @@ impl SimplifyCfg { } } -pub fn simplify_cfg(mir: &mut Mir) { +pub(crate) fn simplify_cfg(mir: &mut Mir) { CfgSimplifier::new(mir).simplify(); remove_dead_blocks(mir); @@ -75,13 +75,13 @@ impl MirPass for SimplifyCfg { } } -pub struct CfgSimplifier<'a, 'tcx: 'a> { +pub(crate) struct CfgSimplifier<'a, 'tcx: 'a> { basic_blocks: &'a mut IndexVec>, pred_count: IndexVec } impl<'a, 'tcx: 'a> CfgSimplifier<'a, 'tcx> { - pub fn new(mir: &'a mut Mir<'tcx>) -> Self { + pub(crate) fn new(mir: &'a mut Mir<'tcx>) -> Self { let mut pred_count = IndexVec::from_elem(0u32, mir.basic_blocks()); // we can't use mir.predecessors() here because that counts @@ -104,7 +104,7 @@ impl<'a, 'tcx: 'a> CfgSimplifier<'a, 'tcx> { } } - pub fn simplify(mut self) { + pub(crate) fn simplify(mut self) { loop { let mut changed = false; @@ -281,7 +281,7 @@ impl<'a, 'tcx: 'a> CfgSimplifier<'a, 'tcx> { } } -pub fn remove_dead_blocks(mir: &mut Mir) { +pub(crate) fn remove_dead_blocks(mir: &mut Mir) { let mut seen = BitVector::new(mir.basic_blocks().len()); for (bb, _) in traversal::preorder(mir) { seen.insert(bb.index()); @@ -348,7 +348,7 @@ fn make_local_map<'tcx, I: Idx, V>(vec: &mut IndexVec, mask: BitVector) -> } struct DeclMarker { - pub locals: BitVector, + pub(crate) locals: BitVector, } impl<'tcx> Visitor<'tcx> for DeclMarker { diff --git a/src/librustc_mir/transform/type_check.rs b/src/librustc_mir/transform/type_check.rs index 7e6fccf30192c..9d844cfaa9809 100644 --- a/src/librustc_mir/transform/type_check.rs +++ b/src/librustc_mir/transform/type_check.rs @@ -318,7 +318,7 @@ impl<'a, 'b, 'gcx, 'tcx> TypeVerifier<'a, 'b, 'gcx, 'tcx> { } } -pub struct TypeChecker<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { +pub(crate) struct TypeChecker<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { infcx: &'a InferCtxt<'a, 'gcx, 'tcx>, param_env: ty::ParamEnv<'gcx>, fulfillment_cx: traits::FulfillmentContext<'tcx>, @@ -346,7 +346,7 @@ impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> { traits::ObligationCause::misc(span, self.body_id) } - pub fn register_infer_ok_obligations(&mut self, infer_ok: InferOk<'tcx, T>) -> T { + pub(crate) fn register_infer_ok_obligations(&mut self, infer_ok: InferOk<'tcx, T>) -> T { for obligation in infer_ok.obligations { self.fulfillment_cx.register_predicate_obligation(self.infcx, obligation); } @@ -739,12 +739,6 @@ impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> { pub struct TypeckMir; -impl TypeckMir { - pub fn new() -> Self { - TypeckMir - } -} - impl MirPass for TypeckMir { fn run_pass<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, diff --git a/src/librustc_mir/util/def_use.rs b/src/librustc_mir/util/def_use.rs index d20d50c561140..2380b7d0041df 100644 --- a/src/librustc_mir/util/def_use.rs +++ b/src/librustc_mir/util/def_use.rs @@ -16,29 +16,29 @@ use rustc_data_structures::indexed_vec::IndexVec; use std::marker::PhantomData; use std::mem; -pub struct DefUseAnalysis<'tcx> { +pub(crate) struct DefUseAnalysis<'tcx> { info: IndexVec>, } #[derive(Clone)] -pub struct Info<'tcx> { - pub defs_and_uses: Vec>, +pub(crate) struct Info<'tcx> { + pub(crate) defs_and_uses: Vec>, } #[derive(Clone)] -pub struct Use<'tcx> { - pub context: LvalueContext<'tcx>, - pub location: Location, +pub(crate) struct Use<'tcx> { + pub(crate) context: LvalueContext<'tcx>, + pub(crate) location: Location, } impl<'tcx> DefUseAnalysis<'tcx> { - pub fn new(mir: &Mir<'tcx>) -> DefUseAnalysis<'tcx> { + pub(crate) fn new(mir: &Mir<'tcx>) -> DefUseAnalysis<'tcx> { DefUseAnalysis { info: IndexVec::from_elem_n(Info::new(), mir.local_decls.len()), } } - pub fn analyze(&mut self, mir: &Mir<'tcx>) { + pub(crate) fn analyze(&mut self, mir: &Mir<'tcx>) { let mut finder = DefUseFinder { info: mem::replace(&mut self.info, IndexVec::new()), }; @@ -46,14 +46,10 @@ impl<'tcx> DefUseAnalysis<'tcx> { self.info = finder.info } - pub fn local_info(&self, local: Local) -> &Info<'tcx> { + pub(crate) fn local_info(&self, local: Local) -> &Info<'tcx> { &self.info[local] } - pub fn local_info_mut(&mut self, local: Local) -> &mut Info<'tcx> { - &mut self.info[local] - } - fn mutate_defs_and_uses(&self, local: Local, mir: &mut Mir<'tcx>, mut callback: F) where F: for<'a> FnMut(&'a mut Lvalue<'tcx>, LvalueContext<'tcx>, @@ -66,10 +62,10 @@ impl<'tcx> DefUseAnalysis<'tcx> { } /// FIXME(pcwalton): This should update the def-use chains. - pub fn replace_all_defs_and_uses_with(&self, - local: Local, - mir: &mut Mir<'tcx>, - new_lvalue: Lvalue<'tcx>) { + pub(crate) fn replace_all_defs_and_uses_with(&self, + local: Local, + mir: &mut Mir<'tcx>, + new_lvalue: Lvalue<'tcx>) { self.mutate_defs_and_uses(local, mir, |lvalue, _, _| *lvalue = new_lvalue.clone()) } } @@ -112,17 +108,17 @@ impl<'tcx> Info<'tcx> { } } - pub fn def_count(&self) -> usize { + pub(crate) fn def_count(&self) -> usize { self.defs_and_uses.iter().filter(|lvalue_use| lvalue_use.context.is_mutating_use()).count() } - pub fn def_count_not_including_drop(&self) -> usize { + pub(crate) fn def_count_not_including_drop(&self) -> usize { self.defs_and_uses.iter().filter(|lvalue_use| { lvalue_use.context.is_mutating_use() && !lvalue_use.context.is_drop() }).count() } - pub fn use_count(&self) -> usize { + pub(crate) fn use_count(&self) -> usize { self.defs_and_uses.iter().filter(|lvalue_use| { lvalue_use.context.is_nonmutating_use() }).count() diff --git a/src/librustc_mir/util/elaborate_drops.rs b/src/librustc_mir/util/elaborate_drops.rs index da7e218439cf0..9624135eb752f 100644 --- a/src/librustc_mir/util/elaborate_drops.rs +++ b/src/librustc_mir/util/elaborate_drops.rs @@ -22,13 +22,13 @@ use util::patch::MirPatch; use std::iter; #[derive(Debug, PartialEq, Eq, Copy, Clone)] -pub enum DropFlagState { +pub(crate) enum DropFlagState { Present, // i.e. initialized Absent, // i.e. deinitialized or "moved" } impl DropFlagState { - pub fn value(self) -> bool { + pub(crate) fn value(self) -> bool { match self { DropFlagState::Present => true, DropFlagState::Absent => false @@ -37,7 +37,7 @@ impl DropFlagState { } #[derive(Debug)] -pub enum DropStyle { +pub(crate) enum DropStyle { Dead, Static, Conditional, @@ -45,13 +45,13 @@ pub enum DropStyle { } #[derive(Debug)] -pub enum DropFlagMode { +pub(crate) enum DropFlagMode { Shallow, Deep } #[derive(Copy, Clone, Debug)] -pub enum Unwind { +pub(crate) enum Unwind { To(BasicBlock), InCleanup } @@ -79,7 +79,7 @@ impl Unwind { } } -pub trait DropElaborator<'a, 'tcx: 'a> : fmt::Debug { +pub(crate) trait DropElaborator<'a, 'tcx: 'a> : fmt::Debug { type Path : Copy + fmt::Debug; fn patch(&mut self) -> &mut MirPatch<'tcx>; @@ -111,7 +111,7 @@ struct DropCtxt<'l, 'b: 'l, 'tcx: 'b, D> unwind: Unwind, } -pub fn elaborate_drop<'b, 'tcx, D>( +pub(crate) fn elaborate_drop<'b, 'tcx, D>( elaborator: &mut D, source_info: SourceInfo, lvalue: &Lvalue<'tcx>, @@ -155,7 +155,7 @@ impl<'l, 'b, 'tcx, D> DropCtxt<'l, 'b, 'tcx, D> /// /// FIXME: I think we should just control the flags externally /// and then we do not need this machinery. - pub fn elaborate_drop<'a>(&mut self, bb: BasicBlock) { + pub(crate) fn elaborate_drop<'a>(&mut self, bb: BasicBlock) { debug!("elaborate_drop({:?})", self); let style = self.elaborator.drop_style(self.path, DropFlagMode::Deep); debug!("elaborate_drop({:?}): live - {:?}", self, style); diff --git a/src/librustc_mir/util/graphviz.rs b/src/librustc_mir/util/graphviz.rs index cf13a80e677b1..bfdcd72fef85f 100644 --- a/src/librustc_mir/util/graphviz.rs +++ b/src/librustc_mir/util/graphviz.rs @@ -62,12 +62,12 @@ pub fn write_mir_graphviz<'a, 'tcx, W>(tcx: TyCtxt<'a, 'tcx, 'tcx>, /// /// `init` and `fini` are callbacks for emitting additional rows of /// data (using HTML enclosed with `` in the emitted text). -pub fn write_node_label(block: BasicBlock, - mir: &Mir, - w: &mut W, - num_cols: u32, - init: INIT, - fini: FINI) -> io::Result<()> +pub(crate) fn write_node_label(block: BasicBlock, + mir: &Mir, + w: &mut W, + num_cols: u32, + init: INIT, + fini: FINI) -> io::Result<()> where INIT: Fn(&mut W) -> io::Result<()>, FINI: Fn(&mut W) -> io::Result<()> { diff --git a/src/librustc_mir/util/mod.rs b/src/librustc_mir/util/mod.rs index 4386bab38c039..05ae5d49e759f 100644 --- a/src/librustc_mir/util/mod.rs +++ b/src/librustc_mir/util/mod.rs @@ -8,13 +8,14 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -pub mod elaborate_drops; -pub mod def_use; -pub mod patch; +pub(crate) mod elaborate_drops; +pub(crate) mod def_use; +pub(crate) mod patch; mod graphviz; mod pretty; -pub use self::pretty::{dump_enabled, dump_mir, write_mir_pretty}; -pub use self::graphviz::{write_mir_graphviz}; -pub use self::graphviz::write_node_label as write_graphviz_node_label; +pub use self::pretty::write_mir_pretty; +pub(crate) use self::pretty::{dump_enabled, dump_mir}; +pub use self::graphviz::write_mir_graphviz; +pub(crate) use self::graphviz::write_node_label as write_graphviz_node_label; diff --git a/src/librustc_mir/util/patch.rs b/src/librustc_mir/util/patch.rs index ac121131eb999..b4e01512782e4 100644 --- a/src/librustc_mir/util/patch.rs +++ b/src/librustc_mir/util/patch.rs @@ -16,7 +16,7 @@ use syntax_pos::Span; /// This struct represents a patch to MIR, which can add /// new statements and basic blocks and patch over block /// terminators. -pub struct MirPatch<'tcx> { +pub(crate) struct MirPatch<'tcx> { patch_map: IndexVec>>, new_blocks: Vec>, new_statements: Vec<(Location, StatementKind<'tcx>)>, @@ -26,7 +26,7 @@ pub struct MirPatch<'tcx> { } impl<'tcx> MirPatch<'tcx> { - pub fn new(mir: &Mir<'tcx>) -> Self { + pub(crate) fn new(mir: &Mir<'tcx>) -> Self { let mut result = MirPatch { patch_map: IndexVec::from_elem(None, mir.basic_blocks()), new_blocks: vec![], @@ -75,15 +75,15 @@ impl<'tcx> MirPatch<'tcx> { result } - pub fn resume_block(&self) -> BasicBlock { + pub(crate) fn resume_block(&self) -> BasicBlock { self.resume_block } - pub fn is_patched(&self, bb: BasicBlock) -> bool { + pub(crate) fn is_patched(&self, bb: BasicBlock) -> bool { self.patch_map[bb].is_some() } - pub fn terminator_loc(&self, mir: &Mir<'tcx>, bb: BasicBlock) -> Location { + pub(crate) fn terminator_loc(&self, mir: &Mir<'tcx>, bb: BasicBlock) -> Location { let offset = match bb.index().checked_sub(mir.basic_blocks().len()) { Some(index) => self.new_blocks[index].statements.len(), None => mir[bb].statements.len() @@ -94,14 +94,14 @@ impl<'tcx> MirPatch<'tcx> { } } - pub fn new_temp(&mut self, ty: Ty<'tcx>, span: Span) -> Local { + pub(crate) fn new_temp(&mut self, ty: Ty<'tcx>, span: Span) -> Local { let index = self.next_local; self.next_local += 1; self.new_locals.push(LocalDecl::new_temp(ty, span)); Local::new(index as usize) } - pub fn new_block(&mut self, data: BasicBlockData<'tcx>) -> BasicBlock { + pub(crate) fn new_block(&mut self, data: BasicBlockData<'tcx>) -> BasicBlock { let block = BasicBlock::new(self.patch_map.len()); debug!("MirPatch: new_block: {:?}: {:?}", block, data); self.new_blocks.push(data); @@ -109,22 +109,22 @@ impl<'tcx> MirPatch<'tcx> { block } - pub fn patch_terminator(&mut self, block: BasicBlock, new: TerminatorKind<'tcx>) { + pub(crate) fn patch_terminator(&mut self, block: BasicBlock, new: TerminatorKind<'tcx>) { assert!(self.patch_map[block].is_none()); debug!("MirPatch: patch_terminator({:?}, {:?})", block, new); self.patch_map[block] = Some(new); } - pub fn add_statement(&mut self, loc: Location, stmt: StatementKind<'tcx>) { + pub(crate) fn add_statement(&mut self, loc: Location, stmt: StatementKind<'tcx>) { debug!("MirPatch: add_statement({:?}, {:?})", loc, stmt); self.new_statements.push((loc, stmt)); } - pub fn add_assign(&mut self, loc: Location, lv: Lvalue<'tcx>, rv: Rvalue<'tcx>) { + pub(crate) fn add_assign(&mut self, loc: Location, lv: Lvalue<'tcx>, rv: Rvalue<'tcx>) { self.add_statement(loc, StatementKind::Assign(lv, rv)); } - pub fn apply(self, mir: &mut Mir<'tcx>) { + pub(crate) fn apply(self, mir: &mut Mir<'tcx>) { debug!("MirPatch: {:?} new temps, starting from index {}: {:?}", self.new_locals.len(), mir.local_decls.len(), self.new_locals); debug!("MirPatch: {} new blocks, starting from index {}", @@ -163,14 +163,14 @@ impl<'tcx> MirPatch<'tcx> { } } - pub fn source_info_for_index(data: &BasicBlockData, loc: Location) -> SourceInfo { + pub(crate) fn source_info_for_index(data: &BasicBlockData, loc: Location) -> SourceInfo { match data.statements.get(loc.statement_index) { Some(stmt) => stmt.source_info, None => data.terminator().source_info } } - pub fn source_info_for_location(&self, mir: &Mir, loc: Location) -> SourceInfo { + pub(crate) fn source_info_for_location(&self, mir: &Mir, loc: Location) -> SourceInfo { let data = match loc.block.index().checked_sub(mir.basic_blocks().len()) { Some(new) => &self.new_blocks[new], None => &mir[loc.block] diff --git a/src/librustc_mir/util/pretty.rs b/src/librustc_mir/util/pretty.rs index 22a8c4378d4c3..facbe8644703e 100644 --- a/src/librustc_mir/util/pretty.rs +++ b/src/librustc_mir/util/pretty.rs @@ -39,12 +39,12 @@ const ALIGN: usize = 40; /// - `substring1&substring2,...` -- `&`-separated list of substrings /// that can appear in the pass-name or the `item_path_str` for the given /// node-id. If any one of the substrings match, the data is dumped out. -pub fn dump_mir<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - pass_num: Option<(MirSuite, MirPassIndex)>, - pass_name: &str, - disambiguator: &Display, - source: MirSource, - mir: &Mir<'tcx>) { +pub(crate) fn dump_mir<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, + pass_num: Option<(MirSuite, MirPassIndex)>, + pass_name: &str, + disambiguator: &Display, + source: MirSource, + mir: &Mir<'tcx>) { if !dump_enabled(tcx, pass_name, source) { return; } @@ -61,10 +61,10 @@ pub fn dump_mir<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } } -pub fn dump_enabled<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - pass_name: &str, - source: MirSource) - -> bool { +pub(crate) fn dump_enabled<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, + pass_name: &str, + source: MirSource) + -> bool { let filters = match tcx.sess.opts.debugging_opts.dump_mir { None => return false, Some(ref filters) => filters, @@ -158,11 +158,11 @@ pub fn write_mir_pretty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, Ok(()) } -pub fn write_mir_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - src: MirSource, - mir: &Mir<'tcx>, - w: &mut Write) - -> io::Result<()> { +pub(crate) fn write_mir_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, + src: MirSource, + mir: &Mir<'tcx>, + w: &mut Write) + -> io::Result<()> { write_mir_intro(tcx, src, mir, w)?; for block in mir.basic_blocks().indices() { write_basic_block(tcx, block, mir, w)?; @@ -356,7 +356,7 @@ fn write_temp_decls(mir: &Mir, w: &mut Write) -> io::Result<()> { Ok(()) } -pub fn dump_mir_def_ids(tcx: TyCtxt, single: Option) -> Vec { +pub(crate) fn dump_mir_def_ids(tcx: TyCtxt, single: Option) -> Vec { if let Some(i) = single { vec![i] } else { diff --git a/src/librustc_passes/lib.rs b/src/librustc_passes/lib.rs index 3949152e84896..8cc7a69bc80b8 100644 --- a/src/librustc_passes/lib.rs +++ b/src/librustc_passes/lib.rs @@ -36,12 +36,12 @@ extern crate syntax; extern crate syntax_pos; extern crate rustc_errors as errors; -pub mod diagnostics; +mod diagnostics; pub mod ast_validation; pub mod consts; pub mod hir_stats; pub mod loops; -pub mod mir_stats; +mod mir_stats; pub mod no_asm; pub mod static_recursion; diff --git a/src/librustc_passes/mir_stats.rs b/src/librustc_passes/mir_stats.rs index 4dd38cc515c77..61fc643304e6a 100644 --- a/src/librustc_passes/mir_stats.rs +++ b/src/librustc_passes/mir_stats.rs @@ -13,7 +13,6 @@ // completely accurate (some things might be counted twice, others missed). use rustc_const_math::{ConstUsize}; -use rustc::hir::def_id::LOCAL_CRATE; use rustc::middle::const_val::{ConstVal}; use rustc::mir::{AggregateKind, AssertMessage, BasicBlock, BasicBlockData}; use rustc::mir::{Constant, Literal, Location, LocalDecl}; @@ -22,9 +21,7 @@ use rustc::mir::{Mir, Operand, ProjectionElem}; use rustc::mir::{Rvalue, SourceInfo, Statement, StatementKind}; use rustc::mir::{Terminator, TerminatorKind, VisibilityScope, VisibilityScopeData}; use rustc::mir::visit as mir_visit; -use rustc::mir::visit::Visitor; use rustc::ty::{ClosureSubsts, TyCtxt}; -use rustc::util::common::to_readable_str; use rustc::util::nodemap::{FxHashMap}; struct NodeData { @@ -37,21 +34,6 @@ struct StatCollector<'a, 'tcx: 'a> { data: FxHashMap<&'static str, NodeData>, } -pub fn print_mir_stats<'tcx, 'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>, title: &str) { - let mut collector = StatCollector { - _tcx: tcx, - data: FxHashMap(), - }; - // For debugging instrumentation like this, we don't need to worry - // about maintaining the dep graph. - let _ignore = tcx.dep_graph.in_ignore(); - for &def_id in tcx.mir_keys(LOCAL_CRATE).iter() { - let mir = tcx.optimized_mir(def_id); - collector.visit_mir(&mir); - } - collector.print(title); -} - impl<'a, 'tcx> StatCollector<'a, 'tcx> { fn record_with_size(&mut self, label: &'static str, node_size: usize) { @@ -67,27 +49,6 @@ impl<'a, 'tcx> StatCollector<'a, 'tcx> { fn record(&mut self, label: &'static str, node: &T) { self.record_with_size(label, ::std::mem::size_of_val(node)); } - - fn print(&self, title: &str) { - let mut stats: Vec<_> = self.data.iter().collect(); - - stats.sort_by_key(|&(_, ref d)| d.count * d.size); - - println!("\n{}\n", title); - - println!("{:<32}{:>18}{:>14}{:>14}", - "Name", "Accumulated Size", "Count", "Item Size"); - println!("------------------------------------------------------------------------------"); - - for (label, data) in stats { - println!("{:<32}{:>18}{:>14}{:>14}", - label, - to_readable_str(data.count * data.size), - to_readable_str(data.count), - to_readable_str(data.size)); - } - println!("------------------------------------------------------------------------------"); - } } impl<'a, 'tcx> mir_visit::Visitor<'tcx> for StatCollector<'a, 'tcx> { diff --git a/src/librustc_platform_intrinsics/aarch64.rs b/src/librustc_platform_intrinsics/aarch64.rs index 0fb8513e138f3..668fdeea9ca63 100644 --- a/src/librustc_platform_intrinsics/aarch64.rs +++ b/src/librustc_platform_intrinsics/aarch64.rs @@ -19,7 +19,7 @@ use IntrinsicDef::Named; // The default inlining settings trigger a pathological behaviour in // LLVM, which causes makes compilation very slow. See #28273. #[inline(never)] -pub fn find(name: &str) -> Option { +pub(crate) fn find(name: &str) -> Option { if !name.starts_with("aarch64_v") { return None } Some(match &name["aarch64_v".len()..] { "hadd_s8" => Intrinsic { diff --git a/src/librustc_platform_intrinsics/arm.rs b/src/librustc_platform_intrinsics/arm.rs index 59ac5ccc53f51..b22a191e7b375 100644 --- a/src/librustc_platform_intrinsics/arm.rs +++ b/src/librustc_platform_intrinsics/arm.rs @@ -19,7 +19,7 @@ use IntrinsicDef::Named; // The default inlining settings trigger a pathological behaviour in // LLVM, which causes makes compilation very slow. See #28273. #[inline(never)] -pub fn find(name: &str) -> Option { +pub(crate) fn find(name: &str) -> Option { if !name.starts_with("arm_v") { return None } Some(match &name["arm_v".len()..] { "hadd_s8" => Intrinsic { diff --git a/src/librustc_platform_intrinsics/hexagon.rs b/src/librustc_platform_intrinsics/hexagon.rs index 56d639868e056..8651e24d72b8c 100644 --- a/src/librustc_platform_intrinsics/hexagon.rs +++ b/src/librustc_platform_intrinsics/hexagon.rs @@ -19,7 +19,7 @@ use IntrinsicDef::Named; // The default inlining settings trigger a pathological behaviour in // LLVM, which causes makes compilation very slow. See #28273. #[inline(never)] -pub fn find(name: &str) -> Option { +pub(crate) fn find(name: &str) -> Option { if !name.starts_with("Q6_") { return None } Some(match &name["Q6_".len()..] { "R_vextract64" => Intrinsic { diff --git a/src/librustc_platform_intrinsics/nvptx.rs b/src/librustc_platform_intrinsics/nvptx.rs index 82408723ebe6f..1a9d191af9a96 100644 --- a/src/librustc_platform_intrinsics/nvptx.rs +++ b/src/librustc_platform_intrinsics/nvptx.rs @@ -19,7 +19,7 @@ use IntrinsicDef::Named; // The default inlining settings trigger a pathological behaviour in // LLVM, which causes makes compilation very slow. See #28273. #[inline(never)] -pub fn find(name: &str) -> Option { +pub(crate) fn find(name: &str) -> Option { if !name.starts_with("nvptx") { return None } Some(match &name["nvptx".len()..] { "_syncthreads" => Intrinsic { diff --git a/src/librustc_platform_intrinsics/x86.rs b/src/librustc_platform_intrinsics/x86.rs index acb69423ffee3..3cd3b50179ec2 100644 --- a/src/librustc_platform_intrinsics/x86.rs +++ b/src/librustc_platform_intrinsics/x86.rs @@ -19,7 +19,7 @@ use IntrinsicDef::Named; // The default inlining settings trigger a pathological behaviour in // LLVM, which causes makes compilation very slow. See #28273. #[inline(never)] -pub fn find(name: &str) -> Option { +pub(crate) fn find(name: &str) -> Option { if !name.starts_with("x86") { return None } Some(match &name["x86".len()..] { "_mm256_abs_epi8" => Intrinsic { diff --git a/src/librustc_plugin/lib.rs b/src/librustc_plugin/lib.rs index 1de31c5d79154..12c435f1534a6 100644 --- a/src/librustc_plugin/lib.rs +++ b/src/librustc_plugin/lib.rs @@ -36,7 +36,7 @@ //! use syntax::tokenstream::TokenTree; //! //! #[plugin_registrar] -//! pub fn plugin_registrar(reg: &mut Registry) { +//! fn plugin_registrar(reg: &mut Registry) { //! reg.register_macro("mymacro", expand_mymacro); //! } //! @@ -80,7 +80,7 @@ extern crate rustc_errors as errors; pub use self::registry::Registry; -pub mod diagnostics; +mod diagnostics; pub mod registry; pub mod load; pub mod build; diff --git a/src/librustc_plugin/load.rs b/src/librustc_plugin/load.rs index ed49e8a14c8c7..324885518082b 100644 --- a/src/librustc_plugin/load.rs +++ b/src/librustc_plugin/load.rs @@ -23,7 +23,7 @@ use syntax::ast; use syntax_pos::{Span, DUMMY_SP}; /// Pointer to a registrar function. -pub type PluginRegistrarFun = +pub(crate) type PluginRegistrarFun = fn(&mut Registry); pub struct PluginRegistrar { diff --git a/src/librustc_plugin/registry.rs b/src/librustc_plugin/registry.rs index 3027489d65be2..faac23c8d4692 100644 --- a/src/librustc_plugin/registry.rs +++ b/src/librustc_plugin/registry.rs @@ -40,7 +40,7 @@ pub struct Registry<'a> { pub args_hidden: Option>, #[doc(hidden)] - pub krate_span: Span, + pub(crate) krate_span: Span, #[doc(hidden)] pub syntax_exts: Vec, diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index 64af24d92eecb..5b3aa890ced37 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -41,7 +41,7 @@ use std::cmp; use std::mem::replace; use std::rc::Rc; -pub mod diagnostics; +mod diagnostics; //////////////////////////////////////////////////////////////////////////////// /// Visitor used to determine if pub(restricted) is used anywhere in the crate. diff --git a/src/librustc_resolve/build_reduced_graph.rs b/src/librustc_resolve/build_reduced_graph.rs index 4b6b754dca655..9403d1921157a 100644 --- a/src/librustc_resolve/build_reduced_graph.rs +++ b/src/librustc_resolve/build_reduced_graph.rs @@ -77,7 +77,7 @@ struct LegacyMacroImports { impl<'a> Resolver<'a> { /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined; /// otherwise, reports an error. - pub fn define(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T) + pub(crate) fn define(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T) where T: ToNameBinding<'a>, { let binding = def.to_name_binding(self.arenas); @@ -505,7 +505,7 @@ impl<'a> Resolver<'a> { } } - pub fn get_module(&mut self, def_id: DefId) -> Module<'a> { + pub(crate) fn get_module(&mut self, def_id: DefId) -> Module<'a> { if def_id.krate == LOCAL_CRATE { return self.module_map[&def_id] } @@ -530,7 +530,7 @@ impl<'a> Resolver<'a> { module } - pub fn macro_def_scope(&mut self, expansion: Mark) -> Module<'a> { + pub(crate) fn macro_def_scope(&mut self, expansion: Mark) -> Module<'a> { let def_id = self.macro_defs[&expansion]; if let Some(id) = self.definitions.as_local_node_id(def_id) { self.local_macro_def_scopes[&id] @@ -543,7 +543,7 @@ impl<'a> Resolver<'a> { } } - pub fn get_macro(&mut self, def: Def) -> Rc { + pub(crate) fn get_macro(&mut self, def: Def) -> Rc { let def_id = match def { Def::Macro(def_id, ..) => def_id, _ => panic!("Expected Def::Macro(..)"), @@ -566,7 +566,7 @@ impl<'a> Resolver<'a> { /// Ensures that the reduced graph rooted at the given external module /// is built, building it if it is not. - pub fn populate_module_if_necessary(&mut self, module: Module<'a>) { + pub(crate) fn populate_module_if_necessary(&mut self, module: Module<'a>) { if module.populated.get() { return } for child in self.session.cstore.item_children(module.def_id().unwrap(), self.session) { self.build_reduced_graph_for_external_crate_def(module, child); @@ -713,10 +713,10 @@ impl<'a> Resolver<'a> { } } -pub struct BuildReducedGraphVisitor<'a, 'b: 'a> { - pub resolver: &'a mut Resolver<'b>, - pub legacy_scope: LegacyScope<'b>, - pub expansion: Mark, +pub(crate) struct BuildReducedGraphVisitor<'a, 'b: 'a> { + pub(crate) resolver: &'a mut Resolver<'b>, + pub(crate) legacy_scope: LegacyScope<'b>, + pub(crate) expansion: Mark, } impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> { diff --git a/src/librustc_resolve/check_unused.rs b/src/librustc_resolve/check_unused.rs index d150ff1ff81f5..6c9c4b5357d26 100644 --- a/src/librustc_resolve/check_unused.rs +++ b/src/librustc_resolve/check_unused.rs @@ -114,7 +114,7 @@ impl<'a, 'b> Visitor<'a> for UnusedImportCheckVisitor<'a, 'b> { } } -pub fn check_crate(resolver: &mut Resolver, krate: &ast::Crate) { +pub(crate) fn check_crate(resolver: &mut Resolver, krate: &ast::Crate) { for directive in resolver.potentially_unused_imports.iter() { match directive.subclass { _ if directive.used.get() || diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 49e6929aeef1d..c07d8d1f06dcb 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -406,7 +406,7 @@ enum PathSource<'a> { TupleStruct, // `m::A::B` in `::B::C`. TraitItem(Namespace), - // Path in `pub(path)` + // Path in `pub(in path)` Visibility, // Path in `use a::b::{...};` ImportPrefix, @@ -548,14 +548,14 @@ impl<'a> PathSource<'a> { } #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] -pub enum Namespace { +enum Namespace { TypeNS, ValueNS, MacroNS, } #[derive(Clone, Default, Debug)] -pub struct PerNS { +struct PerNS { value_ns: T, type_ns: T, macro_ns: Option, @@ -729,8 +729,6 @@ impl<'a, 'tcx> Visitor<'tcx> for Resolver<'a> { } } -pub type ErrorMessage = Option<(Span, String)>; - #[derive(Copy, Clone)] enum TypeParameters<'a, 'b> { NoTypeParameters, @@ -829,7 +827,7 @@ enum ModuleKind { } /// One node in the tree of modules. -pub struct ModuleData<'a> { +struct ModuleData<'a> { parent: Option>, kind: ModuleKind, @@ -862,7 +860,7 @@ pub struct ModuleData<'a> { expansion: Mark, } -pub type Module<'a> = &'a ModuleData<'a>; +type Module<'a> = &'a ModuleData<'a>; impl<'a> ModuleData<'a> { fn new(parent: Option>, @@ -937,14 +935,14 @@ impl<'a> fmt::Debug for ModuleData<'a> { // Records a possibly-private value, type, or module definition. #[derive(Clone, Debug)] -pub struct NameBinding<'a> { +struct NameBinding<'a> { kind: NameBindingKind<'a>, expansion: Mark, span: Span, vis: ty::Visibility, } -pub trait ToNameBinding<'a> { +trait ToNameBinding<'a> { fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>; } @@ -2896,31 +2894,6 @@ impl<'a> Resolver<'a> { return def; } - // Calls `f` with a `Resolver` whose current lexical scope is `module`'s lexical scope, - // i.e. the module's items and the prelude (unless the module is `#[no_implicit_prelude]`). - // FIXME #34673: This needs testing. - pub fn with_module_lexical_scope(&mut self, module: Module<'a>, f: F) -> T - where F: FnOnce(&mut Resolver<'a>) -> T, - { - self.with_empty_ribs(|this| { - this.ribs[ValueNS].push(Rib::new(ModuleRibKind(module))); - this.ribs[TypeNS].push(Rib::new(ModuleRibKind(module))); - f(this) - }) - } - - fn with_empty_ribs(&mut self, f: F) -> T - where F: FnOnce(&mut Resolver<'a>) -> T, - { - let ribs = replace(&mut self.ribs, PerNS::>::default()); - let label_ribs = replace(&mut self.label_ribs, Vec::new()); - - let result = f(self); - self.ribs = ribs; - self.label_ribs = label_ribs; - result - } - fn lookup_assoc_candidate(&mut self, ident: Ident, ns: Namespace, diff --git a/src/librustc_resolve/macros.rs b/src/librustc_resolve/macros.rs index a993aca92dd12..52e0ffec86c2d 100644 --- a/src/librustc_resolve/macros.rs +++ b/src/librustc_resolve/macros.rs @@ -41,21 +41,21 @@ use std::mem; use std::rc::Rc; #[derive(Clone)] -pub struct InvocationData<'a> { - pub module: Cell>, - pub def_index: DefIndex, +pub(crate) struct InvocationData<'a> { + pub(crate) module: Cell>, + pub(crate) def_index: DefIndex, // True if this expansion is in a `const_expr` position, for example `[u32; m!()]`. // c.f. `DefCollector::visit_const_expr`. - pub const_expr: bool, + pub(crate) const_expr: bool, // The scope in which the invocation path is resolved. - pub legacy_scope: Cell>, + pub(crate) legacy_scope: Cell>, // The smallest scope that includes this invocation's expansion, // or `Empty` if this invocation has not been expanded yet. - pub expansion: Cell>, + pub(crate) expansion: Cell>, } impl<'a> InvocationData<'a> { - pub fn root(graph_root: Module<'a>) -> Self { + pub(crate) fn root(graph_root: Module<'a>) -> Self { InvocationData { module: Cell::new(graph_root), def_index: CRATE_DEF_INDEX, @@ -67,36 +67,36 @@ impl<'a> InvocationData<'a> { } #[derive(Copy, Clone)] -pub enum LegacyScope<'a> { +pub(crate) enum LegacyScope<'a> { Empty, Invocation(&'a InvocationData<'a>), // The scope of the invocation, not including its expansion Expansion(&'a InvocationData<'a>), // The scope of the invocation, including its expansion Binding(&'a LegacyBinding<'a>), } -pub struct LegacyBinding<'a> { - pub parent: Cell>, - pub ident: Ident, +pub(crate) struct LegacyBinding<'a> { + pub(crate) parent: Cell>, + pub(crate) ident: Ident, def_id: DefId, - pub span: Span, + pub(crate) span: Span, } #[derive(Copy, Clone)] -pub enum MacroBinding<'a> { +pub(crate) enum MacroBinding<'a> { Legacy(&'a LegacyBinding<'a>), Global(&'a NameBinding<'a>), Modern(&'a NameBinding<'a>), } impl<'a> MacroBinding<'a> { - pub fn span(self) -> Span { + pub(crate) fn span(self) -> Span { match self { MacroBinding::Legacy(binding) => binding.span, MacroBinding::Global(binding) | MacroBinding::Modern(binding) => binding.span, } } - pub fn binding(self) -> &'a NameBinding<'a> { + pub(crate) fn binding(self) -> &'a NameBinding<'a> { match self { MacroBinding::Global(binding) | MacroBinding::Modern(binding) => binding, MacroBinding::Legacy(_) => panic!("unexpected MacroBinding::Legacy"), @@ -444,12 +444,12 @@ impl<'a> Resolver<'a> { } // Resolve the initial segment of a non-global macro path (e.g. `foo` in `foo::bar!();`) - pub fn resolve_lexical_macro_path_segment(&mut self, - mut ident: Ident, - ns: Namespace, - record_used: bool, - path_span: Span) - -> Result, Determinacy> { + pub(crate) fn resolve_lexical_macro_path_segment(&mut self, + mut ident: Ident, + ns: Namespace, + record_used: bool, + path_span: Span) + -> Result, Determinacy> { ident = ident.modern(); let mut module = Some(self.current_module); let mut potential_illegal_shadower = Err(Determinacy::Determined); @@ -508,11 +508,11 @@ impl<'a> Resolver<'a> { } } - pub fn resolve_legacy_scope(&mut self, - mut scope: &'a Cell>, - ident: Ident, - record_used: bool) - -> Option> { + pub(crate) fn resolve_legacy_scope(&mut self, + mut scope: &'a Cell>, + ident: Ident, + record_used: bool) + -> Option> { let ident = ident.modern(); let mut possible_time_travel = None; let mut relative_depth: u32 = 0; @@ -573,7 +573,7 @@ impl<'a> Resolver<'a> { Some(binding) } - pub fn finalize_current_module_macro_resolutions(&mut self) { + pub(crate) fn finalize_current_module_macro_resolutions(&mut self) { let module = self.current_module; for &(ref path, span) in module.macro_resolutions.borrow().iter() { match self.resolve_path(path, Some(MacroNS), true, span) { @@ -700,10 +700,10 @@ impl<'a> Resolver<'a> { }); } - pub fn define_macro(&mut self, - item: &ast::Item, - expansion: Mark, - legacy_scope: &mut LegacyScope<'a>) { + pub(crate) fn define_macro(&mut self, + item: &ast::Item, + expansion: Mark, + legacy_scope: &mut LegacyScope<'a>) { self.local_macro_def_scopes.insert(item.id, self.current_module); let ident = item.ident; if ident.name == "macro_rules" { diff --git a/src/librustc_resolve/resolve_imports.rs b/src/librustc_resolve/resolve_imports.rs index 4bff5da3d6b09..89c9e04c5a75b 100644 --- a/src/librustc_resolve/resolve_imports.rs +++ b/src/librustc_resolve/resolve_imports.rs @@ -36,7 +36,7 @@ use std::mem; /// Contains data for specific types of import directives. #[derive(Clone, Debug)] -pub enum ImportDirectiveSubclass<'a> { +pub(crate) enum ImportDirectiveSubclass<'a> { SingleImport { target: Ident, source: Ident, @@ -54,31 +54,31 @@ pub enum ImportDirectiveSubclass<'a> { /// One import directive. #[derive(Debug,Clone)] -pub struct ImportDirective<'a> { - pub id: NodeId, - pub parent: Module<'a>, - pub module_path: Vec, - pub imported_module: Cell>>, // the resolution of `module_path` - pub subclass: ImportDirectiveSubclass<'a>, - pub span: Span, - pub vis: Cell, - pub expansion: Mark, - pub used: Cell, +pub(crate) struct ImportDirective<'a> { + pub(crate) id: NodeId, + pub(crate) parent: Module<'a>, + pub(crate) module_path: Vec, + pub(crate) imported_module: Cell>>, // the resolution of `module_path` + pub(crate) subclass: ImportDirectiveSubclass<'a>, + pub(crate) span: Span, + pub(crate) vis: Cell, + pub(crate) expansion: Mark, + pub(crate) used: Cell, } impl<'a> ImportDirective<'a> { - pub fn is_glob(&self) -> bool { + pub(crate) fn is_glob(&self) -> bool { match self.subclass { ImportDirectiveSubclass::GlobImport { .. } => true, _ => false } } } #[derive(Clone, Default)] /// Records information about the resolution of a name in a namespace of a module. -pub struct NameResolution<'a> { +pub(crate) struct NameResolution<'a> { /// The single imports that define the name in the namespace. single_imports: SingleImports<'a>, /// The least shadowable known binding for this name, or None if there are no known bindings. - pub binding: Option<&'a NameBinding<'a>>, + pub(crate) binding: Option<&'a NameBinding<'a>>, shadows_glob: Option<&'a NameBinding<'a>>, } @@ -140,14 +140,14 @@ impl<'a> Resolver<'a> { /// Attempts to resolve `ident` in namespaces `ns` of `module`. /// Invariant: if `record_used` is `Some`, import resolution must be complete. - pub fn resolve_ident_in_module_unadjusted(&mut self, - module: Module<'a>, - ident: Ident, - ns: Namespace, - restricted_shadowing: bool, - record_used: bool, - path_span: Span) - -> Result<&'a NameBinding<'a>, Determinacy> { + pub(crate) fn resolve_ident_in_module_unadjusted(&mut self, + module: Module<'a>, + ident: Ident, + ns: Namespace, + restricted_shadowing: bool, + record_used: bool, + path_span: Span) + -> Result<&'a NameBinding<'a>, Determinacy> { self.populate_module_if_necessary(module); let resolution = self.resolution(module, ident, ns) @@ -255,13 +255,13 @@ impl<'a> Resolver<'a> { } // Add an import directive to the current module. - pub fn add_import_directive(&mut self, - module_path: Vec, - subclass: ImportDirectiveSubclass<'a>, - span: Span, - id: NodeId, - vis: ty::Visibility, - expansion: Mark) { + pub(crate) fn add_import_directive(&mut self, + module_path: Vec, + subclass: ImportDirectiveSubclass<'a>, + span: Span, + id: NodeId, + vis: ty::Visibility, + expansion: Mark) { let current_module = self.current_module; let directive = self.arenas.alloc_import_directive(ImportDirective { parent: current_module, @@ -293,7 +293,7 @@ impl<'a> Resolver<'a> { // Given a binding and an import directive that resolves to it, // return the corresponding binding defined by the import directive. - pub fn import(&self, binding: &'a NameBinding<'a>, directive: &'a ImportDirective<'a>) + pub(crate) fn import(&self, binding: &'a NameBinding<'a>, directive: &'a ImportDirective<'a>) -> &'a NameBinding<'a> { let vis = if binding.pseudo_vis().is_at_least(directive.vis.get(), self) || // c.f. `PUB_USE_OF_PRIVATE_EXTERN_CRATE` @@ -323,12 +323,12 @@ impl<'a> Resolver<'a> { } // Define the name or return the existing binding if there is a collision. - pub fn try_define(&mut self, - module: Module<'a>, - ident: Ident, - ns: Namespace, - binding: &'a NameBinding<'a>) - -> Result<(), &'a NameBinding<'a>> { + pub(crate) fn try_define(&mut self, + module: Module<'a>, + ident: Ident, + ns: Namespace, + binding: &'a NameBinding<'a>) + -> Result<(), &'a NameBinding<'a>> { self.update_resolution(module, ident, ns, |this, resolution| { if let Some(old_binding) = resolution.binding { if binding.is_glob_import() { @@ -360,7 +360,7 @@ impl<'a> Resolver<'a> { }) } - pub fn ambiguity(&self, b1: &'a NameBinding<'a>, b2: &'a NameBinding<'a>) + pub(crate) fn ambiguity(&self, b1: &'a NameBinding<'a>, b2: &'a NameBinding<'a>) -> &'a NameBinding<'a> { self.arenas.alloc_name_binding(NameBinding { kind: NameBindingKind::Ambiguity { b1: b1, b2: b2, legacy: false }, @@ -425,8 +425,8 @@ impl<'a> Resolver<'a> { } } -pub struct ImportResolver<'a, 'b: 'a> { - pub resolver: &'a mut Resolver<'b>, +pub(crate) struct ImportResolver<'a, 'b: 'a> { + pub(crate) resolver: &'a mut Resolver<'b>, } impl<'a, 'b: 'a> ::std::ops::Deref for ImportResolver<'a, 'b> { @@ -459,7 +459,7 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> { /// Resolves all imports for the crate. This method performs the fixed- /// point iteration. - pub fn resolve_imports(&mut self) { + pub(crate) fn resolve_imports(&mut self) { let mut prev_num_indeterminates = self.indeterminate_imports.len() + 1; while self.indeterminate_imports.len() < prev_num_indeterminates { prev_num_indeterminates = self.indeterminate_imports.len(); @@ -472,7 +472,7 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> { } } - pub fn finalize_imports(&mut self) { + pub(crate) fn finalize_imports(&mut self) { for module in self.arenas.local_modules().iter() { self.finalize_resolutions_in(module); } diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index cc33d3db8eba7..3cdd64e84f5ae 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -58,7 +58,7 @@ macro_rules! down_cast_data { }; } -pub struct DumpVisitor<'l, 'tcx: 'l, 'll, D: 'll> { +pub(crate) struct DumpVisitor<'l, 'tcx: 'l, 'll, D: 'll> { save_ctxt: SaveContext<'l, 'tcx>, sess: &'l Session, tcx: TyCtxt<'l, 'tcx, 'tcx>, @@ -76,9 +76,9 @@ pub struct DumpVisitor<'l, 'tcx: 'l, 'll, D: 'll> { } impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> { - pub fn new(save_ctxt: SaveContext<'l, 'tcx>, - dumper: &'ll mut D) - -> DumpVisitor<'l, 'tcx, 'll, D> { + pub(crate) fn new(save_ctxt: SaveContext<'l, 'tcx>, + dumper: &'ll mut D) + -> DumpVisitor<'l, 'tcx, 'll, D> { let span_utils = SpanUtils::new(&save_ctxt.tcx.sess); DumpVisitor { sess: &save_ctxt.tcx.sess, @@ -119,7 +119,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> { self.save_ctxt.span_from_span(span) } - pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) { + pub(crate) fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) { let source_file = self.tcx.sess.local_crate_source_file.as_ref(); let crate_root = source_file.map(|source_file| { let source_file = Path::new(source_file); diff --git a/src/librustc_save_analysis/json_api_dumper.rs b/src/librustc_save_analysis/json_api_dumper.rs index 4b2301fd7f804..b35f8be4a07d9 100644 --- a/src/librustc_save_analysis/json_api_dumper.rs +++ b/src/librustc_save_analysis/json_api_dumper.rs @@ -23,13 +23,13 @@ use rls_data::{Analysis, Import, Def, CratePreludeData, Format, Relation}; // information for navigating the source of the crate. // Relative to the regular JSON save-analysis info, this form is filtered to // remove non-visible items. -pub struct JsonApiDumper<'b, W: Write + 'b> { +pub(crate) struct JsonApiDumper<'b, W: Write + 'b> { output: &'b mut W, result: Analysis, } impl<'b, W: Write> JsonApiDumper<'b, W> { - pub fn new(writer: &'b mut W) -> JsonApiDumper<'b, W> { + pub(crate) fn new(writer: &'b mut W) -> JsonApiDumper<'b, W> { let mut result = Analysis::new(); result.kind = Format::JsonApi; JsonApiDumper { output: writer, result } diff --git a/src/librustc_save_analysis/json_dumper.rs b/src/librustc_save_analysis/json_dumper.rs index 9cd375e98558a..c1f41a98c37d6 100644 --- a/src/librustc_save_analysis/json_dumper.rs +++ b/src/librustc_save_analysis/json_dumper.rs @@ -18,16 +18,16 @@ use rls_span::{Column, Row}; use Dump; -pub struct JsonDumper { +pub(crate) struct JsonDumper { result: Analysis, output: O, } -pub trait DumpOutput { +pub(crate) trait DumpOutput { fn dump(&mut self, result: &Analysis); } -pub struct WriteOutput<'b, W: Write + 'b> { +pub(crate) struct WriteOutput<'b, W: Write + 'b> { output: &'b mut W, } @@ -39,7 +39,7 @@ impl<'b, W: Write> DumpOutput for WriteOutput<'b, W> { } } -pub struct CallbackOutput<'b> { +pub(crate) struct CallbackOutput<'b> { callback: &'b mut FnMut(&Analysis), } @@ -50,13 +50,14 @@ impl<'b> DumpOutput for CallbackOutput<'b> { } impl<'b, W: Write> JsonDumper> { - pub fn new(writer: &'b mut W) -> JsonDumper> { + pub(crate) fn new(writer: &'b mut W) -> JsonDumper> { JsonDumper { output: WriteOutput { output: writer }, result: Analysis::new() } } } impl<'b> JsonDumper> { - pub fn with_callback(callback: &'b mut FnMut(&Analysis)) -> JsonDumper> { + pub(crate) fn with_callback(callback: &'b mut FnMut(&Analysis)) + -> JsonDumper> { JsonDumper { output: CallbackOutput { callback: callback }, result: Analysis::new() } } } diff --git a/src/librustc_save_analysis/lib.rs b/src/librustc_save_analysis/lib.rs index ac2baa9e8b1d2..0bbdd4d6280d6 100644 --- a/src/librustc_save_analysis/lib.rs +++ b/src/librustc_save_analysis/lib.rs @@ -51,7 +51,7 @@ use std::env; use std::fs::File; use std::path::{Path, PathBuf}; -use syntax::ast::{self, NodeId, PatKind, Attribute, CRATE_NODE_ID}; +use syntax::ast::{self, NodeId, PatKind, Attribute}; use syntax::parse::lexer::comments::strip_doc_comment_decoration; use syntax::parse::token; use syntax::print::pprust; @@ -61,8 +61,8 @@ use syntax::print::pprust::{ty_to_string, arg_to_string}; use syntax::codemap::MacroAttribute; use syntax_pos::*; -pub use json_api_dumper::JsonApiDumper; -pub use json_dumper::JsonDumper; +use json_api_dumper::JsonApiDumper; +use json_dumper::JsonDumper; use dump_visitor::DumpVisitor; use span_utils::SpanUtils; @@ -79,8 +79,6 @@ pub struct SaveContext<'l, 'tcx: 'l> { #[derive(Debug)] pub enum Data { - /// Data about a macro use. - MacroUseData(MacroRef), RefData(Ref), DefData(Def), RelationData(Relation), @@ -764,11 +762,6 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { def => Some(def.def_id()), } } - - #[inline] - pub fn enclosing_scope(&self, id: NodeId) -> NodeId { - self.tcx.hir.get_enclosing_scope(id).unwrap_or(CRATE_NODE_ID) - } } fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String { diff --git a/src/librustc_save_analysis/sig.rs b/src/librustc_save_analysis/sig.rs index 1d03ab1383af1..de314eaf1d78a 100644 --- a/src/librustc_save_analysis/sig.rs +++ b/src/librustc_save_analysis/sig.rs @@ -44,48 +44,49 @@ use syntax::ast::{self, NodeId}; use syntax::print::pprust; -pub fn item_signature(item: &ast::Item, scx: &SaveContext) -> Option { +pub(crate) fn item_signature(item: &ast::Item, scx: &SaveContext) -> Option { item.make(0, None, scx).ok() } -pub fn foreign_item_signature(item: &ast::ForeignItem, scx: &SaveContext) -> Option { +pub(crate) fn foreign_item_signature(item: &ast::ForeignItem, scx: &SaveContext) + -> Option { item.make(0, None, scx).ok() } /// Signature for a struct or tuple field declaration. /// Does not include a trailing comma. -pub fn field_signature(field: &ast::StructField, scx: &SaveContext) -> Option { +pub(crate) fn field_signature(field: &ast::StructField, scx: &SaveContext) -> Option { field.make(0, None, scx).ok() } /// Does not include a trailing comma. -pub fn variant_signature(variant: &ast::Variant, scx: &SaveContext) -> Option { +pub(crate) fn variant_signature(variant: &ast::Variant, scx: &SaveContext) -> Option { variant.node.make(0, None, scx).ok() } -pub fn method_signature(id: NodeId, - ident: ast::Ident, - m: &ast::MethodSig, - scx: &SaveContext) - -> Option { +pub(crate) fn method_signature(id: NodeId, + ident: ast::Ident, + m: &ast::MethodSig, + scx: &SaveContext) + -> Option { make_method_signature(id, ident, m, scx).ok() } -pub fn assoc_const_signature(id: NodeId, - ident: ast::Name, - ty: &ast::Ty, - default: Option<&ast::Expr>, - scx: &SaveContext) - -> Option { +pub(crate) fn assoc_const_signature(id: NodeId, + ident: ast::Name, + ty: &ast::Ty, + default: Option<&ast::Expr>, + scx: &SaveContext) + -> Option { make_assoc_const_signature(id, ident, ty, default, scx).ok() } -pub fn assoc_type_signature(id: NodeId, - ident: ast::Ident, - bounds: Option<&ast::TyParamBounds>, - default: Option<&ast::Ty>, - scx: &SaveContext) - -> Option { +pub(crate) fn assoc_type_signature(id: NodeId, + ident: ast::Ident, + bounds: Option<&ast::TyParamBounds>, + default: Option<&ast::Ty>, + scx: &SaveContext) + -> Option { make_assoc_type_signature(id, ident, bounds, default, scx).ok() } diff --git a/src/librustc_save_analysis/span_utils.rs b/src/librustc_save_analysis/span_utils.rs index 77cde33e96205..4f473a5aa1eff 100644 --- a/src/librustc_save_analysis/span_utils.rs +++ b/src/librustc_save_analysis/span_utils.rs @@ -23,22 +23,22 @@ use syntax::symbol::keywords; use syntax_pos::*; #[derive(Clone)] -pub struct SpanUtils<'a> { - pub sess: &'a Session, +pub(crate) struct SpanUtils<'a> { + pub(crate) sess: &'a Session, // FIXME given that we clone SpanUtils all over the place, this err_count is // probably useless and any logic relying on it is bogus. - pub err_count: Cell, + pub(crate) err_count: Cell, } impl<'a> SpanUtils<'a> { - pub fn new(sess: &'a Session) -> SpanUtils<'a> { + pub(crate) fn new(sess: &'a Session) -> SpanUtils<'a> { SpanUtils { sess: sess, err_count: Cell::new(0), } } - pub fn make_path_string(file_name: &str) -> String { + pub(crate) fn make_path_string(file_name: &str) -> String { let path = Path::new(file_name); if path.is_absolute() { path.clone().display().to_string() @@ -47,19 +47,19 @@ impl<'a> SpanUtils<'a> { } } - pub fn snippet(&self, span: Span) -> String { + pub(crate) fn snippet(&self, span: Span) -> String { match self.sess.codemap().span_to_snippet(span) { Ok(s) => s, Err(_) => String::new(), } } - pub fn retokenise_span(&self, span: Span) -> StringReader<'a> { + pub(crate) fn retokenise_span(&self, span: Span) -> StringReader<'a> { lexer::StringReader::retokenize(&self.sess.parse_sess, span) } // Re-parses a path and returns the span for the last identifier in the path - pub fn span_for_last_ident(&self, span: Span) -> Option { + pub(crate) fn span_for_last_ident(&self, span: Span) -> Option { let mut result = None; let mut toks = self.retokenise_span(span); @@ -83,7 +83,7 @@ impl<'a> SpanUtils<'a> { } // Return the span for the first identifier in the path. - pub fn span_for_first_ident(&self, span: Span) -> Option { + pub(crate) fn span_for_first_ident(&self, span: Span) -> Option { let mut toks = self.retokenise_span(span); let mut bracket_count = 0; loop { @@ -106,7 +106,7 @@ impl<'a> SpanUtils<'a> { // Return the span for the last ident before a `(` or `<` or '::<' and outside any // any brackets, or the last span. - pub fn sub_span_for_meth_name(&self, span: Span) -> Option { + pub(crate) fn sub_span_for_meth_name(&self, span: Span) -> Option { let mut toks = self.retokenise_span(span); let mut prev = toks.real_token(); let mut result = None; @@ -147,7 +147,7 @@ impl<'a> SpanUtils<'a> { // Return the span for the last ident before a `<` and outside any // angle brackets, or the last span. - pub fn sub_span_for_type_name(&self, span: Span) -> Option { + pub(crate) fn sub_span_for_type_name(&self, span: Span) -> Option { let mut toks = self.retokenise_span(span); let mut prev = toks.real_token(); let mut result = None; @@ -212,7 +212,8 @@ impl<'a> SpanUtils<'a> { // example with Foo, Bar> // Nesting = 0: all idents outside of angle brackets: [Foo] // Nesting = 1: idents within one level of angle brackets: [Bar, Bar] - pub fn spans_with_brackets(&self, span: Span, nesting: isize, limit: isize) -> Vec { + pub(crate) fn spans_with_brackets(&self, span: Span, nesting: isize, limit: isize) + -> Vec { let mut result: Vec = vec![]; let mut toks = self.retokenise_span(span); @@ -276,7 +277,7 @@ impl<'a> SpanUtils<'a> { } } - pub fn sub_span_before_token(&self, span: Span, tok: Token) -> Option { + pub(crate) fn sub_span_before_token(&self, span: Span, tok: Token) -> Option { let mut toks = self.retokenise_span(span); let mut prev = toks.real_token(); loop { @@ -291,7 +292,7 @@ impl<'a> SpanUtils<'a> { } } - pub fn sub_span_of_token(&self, span: Span, tok: Token) -> Option { + pub(crate) fn sub_span_of_token(&self, span: Span, tok: Token) -> Option { let mut toks = self.retokenise_span(span); loop { let next = toks.real_token(); @@ -304,11 +305,12 @@ impl<'a> SpanUtils<'a> { } } - pub fn sub_span_after_keyword(&self, span: Span, keyword: keywords::Keyword) -> Option { + pub(crate) fn sub_span_after_keyword(&self, span: Span, keyword: keywords::Keyword) + -> Option { self.sub_span_after(span, |t| t.is_keyword(keyword)) } - pub fn sub_span_after_token(&self, span: Span, tok: Token) -> Option { + pub(crate) fn sub_span_after_token(&self, span: Span, tok: Token) -> Option { self.sub_span_after(span, |t| t == tok) } @@ -333,20 +335,20 @@ impl<'a> SpanUtils<'a> { // Returns a list of the spans of idents in a path. // E.g., For foo::bar::baz, we return [foo, bar, baz] (well, their spans) - pub fn spans_for_path_segments(&self, path: &ast::Path) -> Vec { + pub(crate) fn spans_for_path_segments(&self, path: &ast::Path) -> Vec { self.spans_with_brackets(path.span, 0, -1) } // Return an owned vector of the subspans of the param identifier // tokens found in span. - pub fn spans_for_ty_params(&self, span: Span, number: isize) -> Vec { + pub(crate) fn spans_for_ty_params(&self, span: Span, number: isize) -> Vec { // Type params are nested within one level of brackets: // i.e. we want Vec from Foo> self.spans_with_brackets(span, 1, number) } // // Return the name for a macro definition (identifier after first `!`) - // pub fn span_for_macro_def_name(&self, span: Span) -> Option { + // pub(crate) fn span_for_macro_def_name(&self, span: Span) -> Option { // let mut toks = self.retokenise_span(span); // loop { // let ts = toks.real_token(); @@ -365,7 +367,7 @@ impl<'a> SpanUtils<'a> { // } // // Return the name for a macro use (identifier before first `!`). - // pub fn span_for_macro_use_name(&self, span:Span) -> Option { + // pub(crate) fn span_for_macro_use_name(&self, span:Span) -> Option { // let mut toks = self.retokenise_span(span); // let mut prev = toks.real_token(); // loop { @@ -389,7 +391,7 @@ impl<'a> SpanUtils<'a> { /// /// Used to filter out spans of minimal value, /// such as references to macro internal variables. - pub fn filter_generated(&self, sub_span: Option, parent: Span) -> bool { + pub(crate) fn filter_generated(&self, sub_span: Option, parent: Span) -> bool { if !generated_code(parent) { if sub_span.is_none() { // Edge case - this occurs on generated code with incorrect expansion info. diff --git a/src/librustc_trans/abi.rs b/src/librustc_trans/abi.rs index 120f201a9c8b7..ed0c1d92692b0 100644 --- a/src/librustc_trans/abi.rs +++ b/src/librustc_trans/abi.rs @@ -42,8 +42,8 @@ use libc::c_uint; use std::cmp; use std::iter; -pub use syntax::abi::Abi; -pub use rustc::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA}; +pub(crate) use syntax::abi::Abi; +pub(crate) use rustc::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA}; #[derive(Clone, Copy, PartialEq, Debug)] enum ArgKind { @@ -58,7 +58,7 @@ enum ArgKind { // Hack to disable non_upper_case_globals only for the bitflags! and not for the rest // of this module -pub use self::attr_impl::ArgAttribute; +pub(crate) use self::attr_impl::ArgAttribute; #[allow(non_upper_case_globals)] #[allow(unused)] @@ -96,23 +96,23 @@ impl ArgAttribute { /// A compact representation of LLVM attributes (at least those relevant for this module) /// that can be manipulated without interacting with LLVM's Attribute machinery. #[derive(Copy, Clone, Debug, Default)] -pub struct ArgAttributes { +pub(crate) struct ArgAttributes { regular: ArgAttribute, dereferenceable_bytes: u64, } impl ArgAttributes { - pub fn set(&mut self, attr: ArgAttribute) -> &mut Self { + pub(crate) fn set(&mut self, attr: ArgAttribute) -> &mut Self { self.regular = self.regular | attr; self } - pub fn set_dereferenceable(&mut self, bytes: u64) -> &mut Self { + pub(crate) fn set_dereferenceable(&mut self, bytes: u64) -> &mut Self { self.dereferenceable_bytes = bytes; self } - pub fn apply_llfn(&self, idx: AttributePlace, llfn: ValueRef) { + pub(crate) fn apply_llfn(&self, idx: AttributePlace, llfn: ValueRef) { unsafe { self.regular.for_each_kind(|attr| attr.apply_llfn(idx, llfn)); if self.dereferenceable_bytes != 0 { @@ -123,7 +123,7 @@ impl ArgAttributes { } } - pub fn apply_callsite(&self, idx: AttributePlace, callsite: ValueRef) { + pub(crate) fn apply_callsite(&self, idx: AttributePlace, callsite: ValueRef) { unsafe { self.regular.for_each_kind(|attr| attr.apply_callsite(idx, callsite)); if self.dereferenceable_bytes != 0 { @@ -135,21 +135,21 @@ impl ArgAttributes { } } #[derive(Copy, Clone, PartialEq, Eq, Debug)] -pub enum RegKind { +pub(crate) enum RegKind { Integer, Float, Vector } #[derive(Copy, Clone, PartialEq, Eq, Debug)] -pub struct Reg { - pub kind: RegKind, - pub size: Size, +pub(crate) struct Reg { + pub(crate) kind: RegKind, + pub(crate) size: Size, } macro_rules! reg_ctor { ($name:ident, $kind:ident, $bits:expr) => { - pub fn $name() -> Reg { + pub(crate) fn $name() -> Reg { Reg { kind: RegKind::$kind, size: Size::from_bits($bits) @@ -189,8 +189,8 @@ impl Reg { /// An argument passed entirely registers with the /// same kind (e.g. HFA / HVA on PPC64 and AArch64). #[derive(Copy, Clone)] -pub struct Uniform { - pub unit: Reg, +pub(crate) struct Uniform { + pub(crate) unit: Reg, /// The total size of the argument, which can be: /// * equal to `unit.size` (one scalar/vector) @@ -198,7 +198,7 @@ pub struct Uniform { /// * if `unit.kind` is `Integer`, the last element /// can be shorter, i.e. `{ i64, i64, i32 }` for /// 64-bit integers with a total size of 20 bytes - pub total: Size, + pub(crate) total: Size, } impl From for Uniform { @@ -236,7 +236,7 @@ impl Uniform { } } -pub trait LayoutExt<'tcx> { +pub(crate) trait LayoutExt<'tcx> { fn is_aggregate(&self) -> bool; fn homogenous_aggregate<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> Option; } @@ -382,7 +382,7 @@ impl<'tcx> LayoutExt<'tcx> for TyLayout<'tcx> { } } -pub enum CastTarget { +pub(crate) enum CastTarget { Uniform(Uniform), Pair(Reg, Reg) } @@ -418,15 +418,15 @@ impl CastTarget { /// /// This is borrowed from clang's ABIInfo.h #[derive(Clone, Copy, Debug)] -pub struct ArgType<'tcx> { +pub(crate) struct ArgType<'tcx> { kind: ArgKind, - pub layout: TyLayout<'tcx>, + pub(crate) layout: TyLayout<'tcx>, /// Coerced LLVM Type - pub cast: Option, + pub(crate) cast: Option, /// Dummy argument, which is emitted before the real argument - pub pad: Option, + pub(crate) pad: Option, /// LLVM attributes of argument - pub attrs: ArgAttributes + pub(crate) attrs: ArgAttributes } impl<'a, 'tcx> ArgType<'tcx> { @@ -440,7 +440,7 @@ impl<'a, 'tcx> ArgType<'tcx> { } } - pub fn make_indirect(&mut self, ccx: &CrateContext<'a, 'tcx>) { + pub(crate) fn make_indirect(&mut self, ccx: &CrateContext<'a, 'tcx>) { assert_eq!(self.kind, ArgKind::Direct); // Wipe old attributes, likely not valid through indirection. @@ -458,12 +458,12 @@ impl<'a, 'tcx> ArgType<'tcx> { self.kind = ArgKind::Indirect; } - pub fn ignore(&mut self) { + pub(crate) fn ignore(&mut self) { assert_eq!(self.kind, ArgKind::Direct); self.kind = ArgKind::Ignore; } - pub fn extend_integer_width_to(&mut self, bits: u64) { + pub(crate) fn extend_integer_width_to(&mut self, bits: u64) { // Only integers have signedness let (i, signed) = match *self.layout { Layout::Scalar { value, .. } => { @@ -495,25 +495,25 @@ impl<'a, 'tcx> ArgType<'tcx> { } } - pub fn cast_to>(&mut self, ccx: &CrateContext, target: T) { + pub(crate) fn cast_to>(&mut self, ccx: &CrateContext, target: T) { self.cast = Some(target.into().llvm_type(ccx)); } - pub fn pad_with(&mut self, ccx: &CrateContext, reg: Reg) { + pub(crate) fn pad_with(&mut self, ccx: &CrateContext, reg: Reg) { self.pad = Some(reg.llvm_type(ccx)); } - pub fn is_indirect(&self) -> bool { + pub(crate) fn is_indirect(&self) -> bool { self.kind == ArgKind::Indirect } - pub fn is_ignore(&self) -> bool { + pub(crate) fn is_ignore(&self) -> bool { self.kind == ArgKind::Ignore } /// Get the LLVM type for an lvalue of the original Rust type of /// this argument/return, i.e. the result of `type_of::type_of`. - pub fn memory_ty(&self, ccx: &CrateContext<'a, 'tcx>) -> Type { + pub(crate) fn memory_ty(&self, ccx: &CrateContext<'a, 'tcx>) -> Type { type_of::type_of(ccx, self.layout.ty) } @@ -521,7 +521,7 @@ impl<'a, 'tcx> ArgType<'tcx> { /// lvalue for the original Rust type of this argument/return. /// Can be used for both storing formal arguments into Rust variables /// or results of call/invoke instructions into their destinations. - pub fn store(&self, bcx: &Builder<'a, 'tcx>, mut val: ValueRef, dst: ValueRef) { + pub(crate) fn store(&self, bcx: &Builder<'a, 'tcx>, mut val: ValueRef, dst: ValueRef) { if self.is_ignore() { return; } @@ -578,7 +578,7 @@ impl<'a, 'tcx> ArgType<'tcx> { } } - pub fn store_fn_arg(&self, bcx: &Builder<'a, 'tcx>, idx: &mut usize, dst: ValueRef) { + pub(crate) fn store_fn_arg(&self, bcx: &Builder<'a, 'tcx>, idx: &mut usize, dst: ValueRef) { if self.pad.is_some() { *idx += 1; } @@ -597,20 +597,20 @@ impl<'a, 'tcx> ArgType<'tcx> { /// I will do my best to describe this structure, but these /// comments are reverse-engineered and may be inaccurate. -NDM #[derive(Clone, Debug)] -pub struct FnType<'tcx> { +pub(crate) struct FnType<'tcx> { /// The LLVM types of each argument. - pub args: Vec>, + pub(crate) args: Vec>, /// LLVM return type. - pub ret: ArgType<'tcx>, + pub(crate) ret: ArgType<'tcx>, - pub variadic: bool, + pub(crate) variadic: bool, - pub cconv: llvm::CallConv + pub(crate) cconv: llvm::CallConv } impl<'a, 'tcx> FnType<'tcx> { - pub fn of_instance(ccx: &CrateContext<'a, 'tcx>, instance: &ty::Instance<'tcx>) + pub(crate) fn of_instance(ccx: &CrateContext<'a, 'tcx>, instance: &ty::Instance<'tcx>) -> Self { let fn_ty = instance_ty(ccx.shared(), &instance); let sig = ty_fn_sig(ccx, fn_ty); @@ -618,17 +618,17 @@ impl<'a, 'tcx> FnType<'tcx> { Self::new(ccx, sig, &[]) } - pub fn new(ccx: &CrateContext<'a, 'tcx>, - sig: ty::FnSig<'tcx>, - extra_args: &[Ty<'tcx>]) -> FnType<'tcx> { + pub(crate) fn new(ccx: &CrateContext<'a, 'tcx>, + sig: ty::FnSig<'tcx>, + extra_args: &[Ty<'tcx>]) -> FnType<'tcx> { let mut fn_ty = FnType::unadjusted(ccx, sig, extra_args); fn_ty.adjust_for_abi(ccx, sig); fn_ty } - pub fn new_vtable(ccx: &CrateContext<'a, 'tcx>, - sig: ty::FnSig<'tcx>, - extra_args: &[Ty<'tcx>]) -> FnType<'tcx> { + pub(crate) fn new_vtable(ccx: &CrateContext<'a, 'tcx>, + sig: ty::FnSig<'tcx>, + extra_args: &[Ty<'tcx>]) -> FnType<'tcx> { let mut fn_ty = FnType::unadjusted(ccx, sig, extra_args); // Don't pass the vtable, it's not an argument of the virtual fn. fn_ty.args[1].ignore(); @@ -636,9 +636,9 @@ impl<'a, 'tcx> FnType<'tcx> { fn_ty } - pub fn unadjusted(ccx: &CrateContext<'a, 'tcx>, - sig: ty::FnSig<'tcx>, - extra_args: &[Ty<'tcx>]) -> FnType<'tcx> { + pub(crate) fn unadjusted(ccx: &CrateContext<'a, 'tcx>, + sig: ty::FnSig<'tcx>, + extra_args: &[Ty<'tcx>]) -> FnType<'tcx> { debug!("FnType::unadjusted({:?}, {:?})", sig, extra_args); use self::Abi::*; @@ -917,7 +917,7 @@ impl<'a, 'tcx> FnType<'tcx> { } } - pub fn llvm_type(&self, ccx: &CrateContext<'a, 'tcx>) -> Type { + pub(crate) fn llvm_type(&self, ccx: &CrateContext<'a, 'tcx>) -> Type { let mut llargument_tys = Vec::new(); let llreturn_ty = if self.ret.is_ignore() { @@ -958,7 +958,7 @@ impl<'a, 'tcx> FnType<'tcx> { } } - pub fn apply_attrs_llfn(&self, llfn: ValueRef) { + pub(crate) fn apply_attrs_llfn(&self, llfn: ValueRef) { let mut i = if self.ret.is_indirect() { 1 } else { 0 }; if !self.ret.is_ignore() { self.ret.attrs.apply_llfn(llvm::AttributePlace::Argument(i), llfn); @@ -973,7 +973,7 @@ impl<'a, 'tcx> FnType<'tcx> { } } - pub fn apply_attrs_callsite(&self, callsite: ValueRef) { + pub(crate) fn apply_attrs_callsite(&self, callsite: ValueRef) { let mut i = if self.ret.is_indirect() { 1 } else { 0 }; if !self.ret.is_ignore() { self.ret.attrs.apply_callsite(llvm::AttributePlace::Argument(i), callsite); @@ -993,6 +993,6 @@ impl<'a, 'tcx> FnType<'tcx> { } } -pub fn align_up_to(off: u64, a: u64) -> u64 { +pub(crate) fn align_up_to(off: u64, a: u64) -> u64 { (off + a - 1) / a * a } diff --git a/src/librustc_trans/adt.rs b/src/librustc_trans/adt.rs index d1c1dd7436a5b..7fbae35ce0ff9 100644 --- a/src/librustc_trans/adt.rs +++ b/src/librustc_trans/adt.rs @@ -60,9 +60,9 @@ use mir::lvalue::Alignment; /// Treats closures as a struct with one variant. /// `empty_if_no_variants` is a switch to deal with empty enums. /// If true, `variant_index` is disregarded and an empty Vec returned in this case. -pub fn compute_fields<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>, - variant_index: usize, - empty_if_no_variants: bool) -> Vec> { +pub(crate) fn compute_fields<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>, + variant_index: usize, + empty_if_no_variants: bool) -> Vec> { match t.sty { ty::TyAdt(ref def, _) if def.variants.len() == 0 && empty_if_no_variants => { Vec::default() @@ -89,17 +89,17 @@ pub fn compute_fields<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>, /// For nominal types, in some cases, we need to use LLVM named structs /// and fill in the actual contents in a second pass to prevent /// unbounded recursion; see also the comments in `trans::type_of`. -pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { +pub(crate) fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { generic_type_of(cx, t, None) } -pub fn incomplete_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, - t: Ty<'tcx>, name: &str) -> Type { +pub(crate) fn incomplete_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, + t: Ty<'tcx>, name: &str) -> Type { generic_type_of(cx, t, Some(name)) } -pub fn finish_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, - t: Ty<'tcx>, llty: &mut Type) { +pub(crate) fn finish_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, + t: Ty<'tcx>, llty: &mut Type) { let l = cx.layout_of(t); debug!("finish_type_of: {} with layout {:#?}", t, l); match *l { @@ -248,13 +248,13 @@ fn struct_llfields_path(discrfield: &layout::FieldPath) -> Vec { // Lookup `Struct::memory_index` and double it to account for padding -pub fn struct_llfields_index(variant: &layout::Struct, index: usize) -> usize { +pub(crate) fn struct_llfields_index(variant: &layout::Struct, index: usize) -> usize { (variant.memory_index[index] as usize) << 1 } -pub fn struct_llfields<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, field_tys: &Vec>, - variant: &layout::Struct) -> Vec { +pub(crate) fn struct_llfields<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, field_tys: &Vec>, + variant: &layout::Struct) -> Vec { debug!("struct_llfields: variant: {:?}", variant); let mut first_field = true; let mut min_offset = 0; @@ -297,7 +297,7 @@ pub fn struct_llfields<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, field_tys: &Vec(l: &layout::Layout) -> bool { +pub(crate) fn is_discr_signed<'tcx>(l: &layout::Layout) -> bool { match *l { layout::CEnum { signed, .. }=> signed, _ => false, @@ -305,7 +305,7 @@ pub fn is_discr_signed<'tcx>(l: &layout::Layout) -> bool { } /// Obtain the actual discriminant of a value. -pub fn trans_get_discr<'a, 'tcx>( +pub(crate) fn trans_get_discr<'a, 'tcx>( bcx: &Builder<'a, 'tcx>, t: Ty<'tcx>, scrutinee: ValueRef, @@ -386,7 +386,8 @@ fn load_discr(bcx: &Builder, ity: layout::Integer, ptr: ValueRef, /// Set the discriminant for a new value of the given case of the given /// representation. -pub fn trans_set_discr<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, t: Ty<'tcx>, val: ValueRef, to: u64) { +pub(crate) fn trans_set_discr<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, t: Ty<'tcx>, + val: ValueRef, to: u64) { let l = bcx.ccx.layout_of(t); match *l { layout::CEnum{ discr, min, max, .. } => { @@ -436,7 +437,7 @@ fn target_sets_discr_via_memset<'a, 'tcx>(bcx: &Builder<'a, 'tcx>) -> bool { bcx.sess().target.target.arch == "arm" || bcx.sess().target.target.arch == "aarch64" } -pub fn assert_discr_in_range(min: D, max: D, discr: D) { +pub(crate) fn assert_discr_in_range(min: D, max: D, discr: D) { if min <= max { assert!(min <= discr && discr <= max) } else { @@ -453,9 +454,9 @@ fn roundup(x: u64, a: u32) -> u64 { let a = a as u64; ((x + (a - 1)) / a) * a } /// /// (Not to be confused with `common::const_get_elt`, which operates on /// raw LLVM-level structs and arrays.) -pub fn const_get_field<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>, - val: ValueRef, - ix: usize) -> ValueRef { +pub(crate) fn const_get_field<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>, + val: ValueRef, + ix: usize) -> ValueRef { let l = ccx.layout_of(t); match *l { layout::CEnum { .. } => bug!("element access in C-like enum const"), diff --git a/src/librustc_trans/allocator.rs b/src/librustc_trans/allocator.rs index 9abb6d66f9c0f..fd5aa1364d381 100644 --- a/src/librustc_trans/allocator.rs +++ b/src/librustc_trans/allocator.rs @@ -19,7 +19,7 @@ use rustc_allocator::{ALLOCATOR_METHODS, AllocatorTy}; use ModuleLlvm; use llvm::{self, False, True}; -pub unsafe fn trans(tcx: TyCtxt, mods: &ModuleLlvm, kind: AllocatorKind) { +pub(crate) unsafe fn trans(tcx: TyCtxt, mods: &ModuleLlvm, kind: AllocatorKind) { let llcx = mods.llcx; let llmod = mods.llmod; let usize = match &tcx.sess.target.target.target_pointer_width[..] { diff --git a/src/librustc_trans/asm.rs b/src/librustc_trans/asm.rs index 92cbd004206e7..2dfa9d86a0f38 100644 --- a/src/librustc_trans/asm.rs +++ b/src/librustc_trans/asm.rs @@ -27,7 +27,7 @@ use syntax::ast::AsmDialect; use libc::{c_uint, c_char}; // Take an inline assembly expression and splat it out via LLVM -pub fn trans_inline_asm<'a, 'tcx>( +pub(crate) fn trans_inline_asm<'a, 'tcx>( bcx: &Builder<'a, 'tcx>, ia: &hir::InlineAsm, outputs: Vec<(ValueRef, Ty<'tcx>)>, @@ -125,8 +125,8 @@ pub fn trans_inline_asm<'a, 'tcx>( } } -pub fn trans_global_asm<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, - ga: &hir::GlobalAsm) { +pub(crate) fn trans_global_asm<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, + ga: &hir::GlobalAsm) { let asm = CString::new(ga.asm.as_str().as_bytes()).unwrap(); unsafe { llvm::LLVMRustAppendModuleInlineAsm(ccx.llmod(), asm.as_ptr()); diff --git a/src/librustc_trans/attributes.rs b/src/librustc_trans/attributes.rs index cbad43066e4eb..ae60eb92e1dbd 100644 --- a/src/librustc_trans/attributes.rs +++ b/src/librustc_trans/attributes.rs @@ -15,13 +15,13 @@ use rustc::session::config::Sanitizer; use llvm::{self, Attribute, ValueRef}; use llvm::AttributePlace::Function; -pub use syntax::attr::{self, InlineAttr}; +pub(crate) use syntax::attr::InlineAttr; use syntax::ast; use context::CrateContext; /// Mark LLVM function to use provided inline heuristic. #[inline] -pub fn inline(val: ValueRef, inline: InlineAttr) { +pub(crate) fn inline(val: ValueRef, inline: InlineAttr) { use self::InlineAttr::*; match inline { Hint => Attribute::InlineHint.apply_llfn(Function, val), @@ -37,30 +37,30 @@ pub fn inline(val: ValueRef, inline: InlineAttr) { /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function. #[inline] -pub fn emit_uwtable(val: ValueRef, emit: bool) { +pub(crate) fn emit_uwtable(val: ValueRef, emit: bool) { Attribute::UWTable.toggle_llfn(Function, val, emit); } /// Tell LLVM whether the function can or cannot unwind. #[inline] -pub fn unwind(val: ValueRef, can_unwind: bool) { +pub(crate) fn unwind(val: ValueRef, can_unwind: bool) { Attribute::NoUnwind.toggle_llfn(Function, val, !can_unwind); } /// Tell LLVM whether it should optimise function for size. #[inline] #[allow(dead_code)] // possibly useful function -pub fn set_optimize_for_size(val: ValueRef, optimize: bool) { +pub(crate) fn set_optimize_for_size(val: ValueRef, optimize: bool) { Attribute::OptimizeForSize.toggle_llfn(Function, val, optimize); } /// Tell LLVM if this function should be 'naked', i.e. skip the epilogue and prologue. #[inline] -pub fn naked(val: ValueRef, is_naked: bool) { +pub(crate) fn naked(val: ValueRef, is_naked: bool) { Attribute::Naked.toggle_llfn(Function, val, is_naked); } -pub fn set_frame_pointer_elimination(ccx: &CrateContext, llfn: ValueRef) { +pub(crate) fn set_frame_pointer_elimination(ccx: &CrateContext, llfn: ValueRef) { // FIXME: #11906: Omitting frame pointers breaks retrieving the value of a // parameter. if ccx.sess().must_not_eliminate_frame_pointers() { @@ -70,7 +70,7 @@ pub fn set_frame_pointer_elimination(ccx: &CrateContext, llfn: ValueRef) { } } -pub fn set_probestack(ccx: &CrateContext, llfn: ValueRef) { +pub(crate) fn set_probestack(ccx: &CrateContext, llfn: ValueRef) { // Only use stack probes if the target specification indicates that we // should be using stack probes if !ccx.sess().target.target.options.stack_probes { @@ -94,7 +94,7 @@ pub fn set_probestack(ccx: &CrateContext, llfn: ValueRef) { /// Composite function which sets LLVM attributes for function depending on its AST (#[attribute]) /// attributes. -pub fn from_fn_attrs(ccx: &CrateContext, attrs: &[ast::Attribute], llfn: ValueRef) { +pub(crate) fn from_fn_attrs(ccx: &CrateContext, attrs: &[ast::Attribute], llfn: ValueRef) { use syntax::attr::*; inline(llfn, find_inline_attr(Some(ccx.sess().diagnostic()), attrs)); diff --git a/src/librustc_trans/back/archive.rs b/src/librustc_trans/back/archive.rs index 902065c8688d0..03ff397865d70 100644 --- a/src/librustc_trans/back/archive.rs +++ b/src/librustc_trans/back/archive.rs @@ -10,7 +10,7 @@ //! A helper class for dealing with static archives -use std::ffi::{CString, CStr, OsString}; +use std::ffi::{CString, CStr}; use std::io; use std::mem; use std::path::{Path, PathBuf}; @@ -23,19 +23,17 @@ use llvm::{self, ArchiveKind}; use metadata::METADATA_FILENAME; use rustc::session::Session; -pub struct ArchiveConfig<'a> { - pub sess: &'a Session, - pub dst: PathBuf, - pub src: Option, - pub lib_search_paths: Vec, - pub ar_prog: String, - pub command_path: OsString, +pub(crate) struct ArchiveConfig<'a> { + pub(crate) sess: &'a Session, + pub(crate) dst: PathBuf, + pub(crate) src: Option, + pub(crate) lib_search_paths: Vec, } /// Helper for adding many files to an archive with a single invocation of /// `ar`. #[must_use = "must call build() to finish building the archive"] -pub struct ArchiveBuilder<'a> { +pub(crate) struct ArchiveBuilder<'a> { config: ArchiveConfig<'a>, removals: Vec, additions: Vec, @@ -54,7 +52,7 @@ enum Addition { }, } -pub fn find_library(name: &str, search_paths: &[PathBuf], sess: &Session) +pub(crate) fn find_library(name: &str, search_paths: &[PathBuf], sess: &Session) -> PathBuf { // On Windows, static libraries sometimes show up as libfoo.a and other // times show up as foo.lib @@ -87,7 +85,7 @@ fn is_relevant_child(c: &Child) -> bool { impl<'a> ArchiveBuilder<'a> { /// Create a new static archive, ready for modifying the archive specified /// by `config`. - pub fn new(config: ArchiveConfig<'a>) -> ArchiveBuilder<'a> { + pub(crate) fn new(config: ArchiveConfig<'a>) -> ArchiveBuilder<'a> { ArchiveBuilder { config: config, removals: Vec::new(), @@ -98,12 +96,12 @@ impl<'a> ArchiveBuilder<'a> { } /// Removes a file from this archive - pub fn remove_file(&mut self, file: &str) { + pub(crate) fn remove_file(&mut self, file: &str) { self.removals.push(file.to_string()); } /// Lists all files in an archive - pub fn src_files(&mut self) -> Vec { + pub(crate) fn src_files(&mut self) -> Vec { if self.src_archive().is_none() { return Vec::new() } @@ -132,7 +130,7 @@ impl<'a> ArchiveBuilder<'a> { /// Adds all of the contents of a native library to this archive. This will /// search in the relevant locations for a library named `name`. - pub fn add_native_library(&mut self, name: &str) { + pub(crate) fn add_native_library(&mut self, name: &str) { let location = find_library(name, &self.config.lib_search_paths, self.config.sess); self.add_archive(&location, |_| false).unwrap_or_else(|e| { @@ -146,11 +144,11 @@ impl<'a> ArchiveBuilder<'a> { /// /// This ignores adding the bytecode from the rlib, and if LTO is enabled /// then the object file also isn't added. - pub fn add_rlib(&mut self, - rlib: &Path, - name: &str, - lto: bool, - skip_objects: bool) -> io::Result<()> { + pub(crate) fn add_rlib(&mut self, + rlib: &Path, + name: &str, + lto: bool, + skip_objects: bool) -> io::Result<()> { // Ignoring obj file starting with the crate name // as simple comparison is not enough - there // might be also an extra name suffix @@ -198,7 +196,7 @@ impl<'a> ArchiveBuilder<'a> { } /// Adds an arbitrary file to this archive - pub fn add_file(&mut self, file: &Path) { + pub(crate) fn add_file(&mut self, file: &Path) { let name = file.file_name().unwrap().to_str().unwrap(); self.additions.push(Addition::File { path: file.to_path_buf(), @@ -208,13 +206,13 @@ impl<'a> ArchiveBuilder<'a> { /// Indicate that the next call to `build` should updates all symbols in /// the archive (run 'ar s' over it). - pub fn update_symbols(&mut self) { + pub(crate) fn update_symbols(&mut self) { self.should_update_symbols = true; } /// Combine the provided files, rlibs, and native libraries into a single /// `Archive`. - pub fn build(&mut self) { + pub(crate) fn build(&mut self) { let kind = match self.llvm_archive_kind() { Ok(kind) => kind, Err(kind) => { diff --git a/src/librustc_trans/back/link.rs b/src/librustc_trans/back/link.rs index 5e85771217b95..7f271ecbbfd85 100644 --- a/src/librustc_trans/back/link.rs +++ b/src/librustc_trans/back/link.rs @@ -50,14 +50,14 @@ use syntax_pos::Span; /// The LLVM module name containing crate-metadata. This includes a `.` on /// purpose, so it cannot clash with the name of a user-defined module. -pub const METADATA_MODULE_NAME: &'static str = "crate.metadata"; +pub(crate) const METADATA_MODULE_NAME: &'static str = "crate.metadata"; /// The name of the crate-metadata object file the compiler generates. Must /// match up with `METADATA_MODULE_NAME`. -pub const METADATA_OBJ_NAME: &'static str = "crate.metadata.o"; +pub(crate) const METADATA_OBJ_NAME: &'static str = "crate.metadata.o"; // same as for metadata above, but for allocator shim -pub const ALLOCATOR_MODULE_NAME: &'static str = "crate.allocator"; -pub const ALLOCATOR_OBJ_NAME: &'static str = "crate.allocator.o"; +pub(crate) const ALLOCATOR_MODULE_NAME: &'static str = "crate.allocator"; +pub(crate) const ALLOCATOR_OBJ_NAME: &'static str = "crate.allocator.o"; // RLIB LLVM-BYTECODE OBJECT LAYOUT // Version 1 @@ -70,22 +70,22 @@ pub const ALLOCATOR_OBJ_NAME: &'static str = "crate.allocator.o"; // This is the "magic number" expected at the beginning of a LLVM bytecode // object in an rlib. -pub const RLIB_BYTECODE_OBJECT_MAGIC: &'static [u8] = b"RUST_OBJECT"; +pub(crate) const RLIB_BYTECODE_OBJECT_MAGIC: &'static [u8] = b"RUST_OBJECT"; // The version number this compiler will write to bytecode objects in rlibs -pub const RLIB_BYTECODE_OBJECT_VERSION: u32 = 1; +pub(crate) const RLIB_BYTECODE_OBJECT_VERSION: u32 = 1; // The offset in bytes the bytecode object format version number can be found at -pub const RLIB_BYTECODE_OBJECT_VERSION_OFFSET: usize = 11; +pub(crate) const RLIB_BYTECODE_OBJECT_VERSION_OFFSET: usize = 11; // The offset in bytes the size of the compressed bytecode can be found at in // format version 1 -pub const RLIB_BYTECODE_OBJECT_V1_DATASIZE_OFFSET: usize = +pub(crate) const RLIB_BYTECODE_OBJECT_V1_DATASIZE_OFFSET: usize = RLIB_BYTECODE_OBJECT_VERSION_OFFSET + 4; // The offset in bytes the compressed LLVM bytecode can be found at in format // version 1 -pub const RLIB_BYTECODE_OBJECT_V1_DATA_OFFSET: usize = +pub(crate) const RLIB_BYTECODE_OBJECT_V1_DATA_OFFSET: usize = RLIB_BYTECODE_OBJECT_V1_DATASIZE_OFFSET + 8; @@ -138,7 +138,7 @@ pub fn find_crate_name(sess: Option<&Session>, "rust_out".to_string() } -pub fn build_link_meta(incremental_hashes_map: &IncrementalHashesMap) -> LinkMeta { +pub(crate) fn build_link_meta(incremental_hashes_map: &IncrementalHashesMap) -> LinkMeta { let krate_dep_node = &DepNode::new_no_params(DepKind::Krate); let r = LinkMeta { crate_hash: Svh::new(incremental_hashes_map[krate_dep_node].to_smaller_hash()), @@ -150,7 +150,7 @@ pub fn build_link_meta(incremental_hashes_map: &IncrementalHashesMap) -> LinkMet // The third parameter is for env vars, used on windows to set up the // path for MSVC to find its DLLs, and gcc to find its bundled // toolchain -pub fn get_linker(sess: &Session) -> (String, Command, Vec<(OsString, OsString)>) { +pub(crate) fn get_linker(sess: &Session) -> (String, Command, Vec<(OsString, OsString)>) { let envs = vec![("PATH".into(), command_path(sess))]; if let Some(ref linker) = sess.opts.cg.linker { @@ -165,7 +165,7 @@ pub fn get_linker(sess: &Session) -> (String, Command, Vec<(OsString, OsString)> } #[cfg(windows)] -pub fn msvc_link_exe_cmd(sess: &Session) -> (Command, Vec<(OsString, OsString)>) { +pub(crate) fn msvc_link_exe_cmd(sess: &Session) -> (Command, Vec<(OsString, OsString)>) { use gcc::windows_registry; let target = &sess.opts.target_triple; @@ -181,16 +181,10 @@ pub fn msvc_link_exe_cmd(sess: &Session) -> (Command, Vec<(OsString, OsString)>) } #[cfg(not(windows))] -pub fn msvc_link_exe_cmd(_sess: &Session) -> (Command, Vec<(OsString, OsString)>) { +pub(crate) fn msvc_link_exe_cmd(_sess: &Session) -> (Command, Vec<(OsString, OsString)>) { (Command::new("link.exe"), vec![]) } -pub fn get_ar_prog(sess: &Session) -> String { - sess.opts.cg.ar.clone().unwrap_or_else(|| { - sess.target.target.options.ar.clone() - }) -} - fn command_path(sess: &Session) -> OsString { // The compiler's sysroot often has some bundled tools, so add it to the // PATH for the child. @@ -202,7 +196,7 @@ fn command_path(sess: &Session) -> OsString { env::join_paths(new_path).unwrap() } -pub fn remove(sess: &Session, path: &Path) { +pub(crate) fn remove(sess: &Session, path: &Path) { match fs::remove_file(path) { Ok(..) => {} Err(e) => { @@ -335,8 +329,8 @@ pub fn filename_for_input(sess: &Session, } } -pub fn each_linked_rlib(sess: &Session, - f: &mut FnMut(CrateNum, &Path)) -> Result<(), String> { +pub(crate) fn each_linked_rlib(sess: &Session, + f: &mut FnMut(CrateNum, &Path)) -> Result<(), String> { let crates = sess.cstore.used_crates(LinkagePreference::RequireStatic).into_iter(); let fmts = sess.dependency_formats.borrow(); let fmts = fmts.get(&config::CrateTypeExecutable) @@ -380,7 +374,7 @@ pub fn each_linked_rlib(sess: &Session, /// It's unusual for a crate to not participate in LTO. Typically only /// compiler-specific and unstable crates have a reason to not participate in /// LTO. -pub fn ignored_for_lto(sess: &Session, cnum: CrateNum) -> bool { +pub(crate) fn ignored_for_lto(sess: &Session, cnum: CrateNum) -> bool { // `#![no_builtins]` crates don't participate in LTO because the state // of builtins gets messed up (our crate isn't tagged with no builtins). // Similarly `#![compiler_builtins]` doesn't participate because we want @@ -497,8 +491,6 @@ fn archive_config<'a>(sess: &'a Session, dst: output.to_path_buf(), src: input.map(|p| p.to_path_buf()), lib_search_paths: archive_search_paths(sess), - ar_prog: get_ar_prog(sess), - command_path: command_path(sess), } } diff --git a/src/librustc_trans/back/linker.rs b/src/librustc_trans/back/linker.rs index 0541fbe15ec5b..9d9f5e7c0f1ab 100644 --- a/src/librustc_trans/back/linker.rs +++ b/src/librustc_trans/back/linker.rs @@ -29,13 +29,13 @@ use serialize::{json, Encoder}; /// For all the linkers we support, and information they might /// need out of the shared crate context before we get rid of it. -pub struct LinkerInfo { +pub(crate) struct LinkerInfo { exports: HashMap>, } impl<'a, 'tcx> LinkerInfo { - pub fn new(scx: &SharedCrateContext<'a, 'tcx>, - exports: &ExportedSymbols) -> LinkerInfo { + pub(crate) fn new(scx: &SharedCrateContext<'a, 'tcx>, + exports: &ExportedSymbols) -> LinkerInfo { LinkerInfo { exports: scx.sess().crate_types.borrow().iter().map(|&c| { (c, exported_symbols(scx, exports, c)) @@ -43,9 +43,9 @@ impl<'a, 'tcx> LinkerInfo { } } - pub fn to_linker(&'a self, - cmd: Command, - sess: &'a Session) -> Box { + pub(crate) fn to_linker(&'a self, + cmd: Command, + sess: &'a Session) -> Box { match sess.linker_flavor() { LinkerFlavor::Msvc => { Box::new(MsvcLinker { @@ -90,7 +90,7 @@ impl<'a, 'tcx> LinkerInfo { /// represents the meaning of each option being passed down. This trait is then /// used to dispatch on whether a GNU-like linker (generally `ld.exe`) or an /// MSVC linker (e.g. `link.exe`) is being used. -pub trait Linker { +pub(crate) trait Linker { fn link_dylib(&mut self, lib: &str); fn link_rust_dylib(&mut self, lib: &str, path: &Path); fn link_framework(&mut self, framework: &str); @@ -117,7 +117,7 @@ pub trait Linker { fn finalize(&mut self) -> Command; } -pub struct GccLinker<'a> { +pub(crate) struct GccLinker<'a> { cmd: Command, sess: &'a Session, info: &'a LinkerInfo, @@ -378,7 +378,7 @@ impl<'a> Linker for GccLinker<'a> { } } -pub struct MsvcLinker<'a> { +pub(crate) struct MsvcLinker<'a> { cmd: Command, sess: &'a Session, info: &'a LinkerInfo @@ -557,7 +557,7 @@ impl<'a> Linker for MsvcLinker<'a> { } } -pub struct EmLinker<'a> { +pub(crate) struct EmLinker<'a> { cmd: Command, sess: &'a Session, info: &'a LinkerInfo diff --git a/src/librustc_trans/back/lto.rs b/src/librustc_trans/back/lto.rs index feed127b0b60b..ae76b24bc2a9d 100644 --- a/src/librustc_trans/back/lto.rs +++ b/src/librustc_trans/back/lto.rs @@ -28,7 +28,7 @@ use std::io::Read; use std::ffi::CString; use std::path::Path; -pub fn crate_type_allows_lto(crate_type: config::CrateType) -> bool { +pub(crate) fn crate_type_allows_lto(crate_type: config::CrateType) -> bool { match crate_type { config::CrateTypeExecutable | config::CrateTypeStaticlib | @@ -40,11 +40,11 @@ pub fn crate_type_allows_lto(crate_type: config::CrateType) -> bool { } } -pub fn run(cgcx: &CodegenContext, - llmod: ModuleRef, - tm: TargetMachineRef, - config: &ModuleConfig, - temp_no_opt_bc_filename: &Path) -> Result<(), FatalError> { +pub(crate) fn run(cgcx: &CodegenContext, + llmod: ModuleRef, + tm: TargetMachineRef, + config: &ModuleConfig, + temp_no_opt_bc_filename: &Path) -> Result<(), FatalError> { let handler = cgcx.handler; if cgcx.opts.cg.prefer_dynamic { handler.struct_err("cannot prefer dynamic linking when performing LTO") diff --git a/src/librustc_trans/back/rpath.rs b/src/librustc_trans/back/rpath.rs index 104e7bc6a52bd..d9216e438e62e 100644 --- a/src/librustc_trans/back/rpath.rs +++ b/src/librustc_trans/back/rpath.rs @@ -16,16 +16,16 @@ use std::fs; use rustc::hir::def_id::CrateNum; use rustc::middle::cstore::LibSource; -pub struct RPathConfig<'a> { - pub used_crates: Vec<(CrateNum, LibSource)>, - pub out_filename: PathBuf, - pub is_like_osx: bool, - pub has_rpath: bool, - pub linker_is_gnu: bool, - pub get_install_prefix_lib_path: &'a mut FnMut() -> PathBuf, +pub(crate) struct RPathConfig<'a> { + pub(crate) used_crates: Vec<(CrateNum, LibSource)>, + pub(crate) out_filename: PathBuf, + pub(crate) is_like_osx: bool, + pub(crate) has_rpath: bool, + pub(crate) linker_is_gnu: bool, + pub(crate) get_install_prefix_lib_path: &'a mut FnMut() -> PathBuf, } -pub fn get_rpath_flags(config: &mut RPathConfig) -> Vec { +pub(crate) fn get_rpath_flags(config: &mut RPathConfig) -> Vec { // No rpath on windows if !config.has_rpath { return Vec::new(); diff --git a/src/librustc_trans/back/symbol_export.rs b/src/librustc_trans/back/symbol_export.rs index 72071f8cec990..15b59bf0e21a4 100644 --- a/src/librustc_trans/back/symbol_export.rs +++ b/src/librustc_trans/back/symbol_export.rs @@ -21,21 +21,21 @@ use syntax::attr; /// `Rust` will only be exported if the crate produced is a Rust /// dylib. #[derive(Eq, PartialEq, Debug, Copy, Clone)] -pub enum SymbolExportLevel { +pub(crate) enum SymbolExportLevel { C, Rust, } /// The set of symbols exported from each crate in the crate graph. #[derive(Debug)] -pub struct ExportedSymbols { - pub export_threshold: SymbolExportLevel, +pub(crate) struct ExportedSymbols { + pub(crate) export_threshold: SymbolExportLevel, exports: FxHashMap>, local_exports: NodeSet, } impl ExportedSymbols { - pub fn empty() -> ExportedSymbols { + pub(crate) fn empty() -> ExportedSymbols { ExportedSymbols { export_threshold: SymbolExportLevel::C, exports: FxHashMap(), @@ -43,9 +43,9 @@ impl ExportedSymbols { } } - pub fn compute<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - local_exported_symbols: &NodeSet) - -> ExportedSymbols { + pub(crate) fn compute<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, + local_exported_symbols: &NodeSet) + -> ExportedSymbols { let export_threshold = crates_export_threshold(&tcx.sess.crate_types.borrow()); let mut local_crate: Vec<_> = local_exported_symbols @@ -173,22 +173,20 @@ impl ExportedSymbols { } } - pub fn local_exports(&self) -> &NodeSet { + pub(crate) fn local_exports(&self) -> &NodeSet { &self.local_exports } - pub fn exported_symbols(&self, - cnum: CrateNum) - -> &[(String, DefId, SymbolExportLevel)] { + pub(crate) fn exported_symbols(&self, + cnum: CrateNum) + -> &[(String, DefId, SymbolExportLevel)] { match self.exports.get(&cnum) { Some(exports) => exports, None => &[] } } - pub fn for_each_exported_symbol(&self, - cnum: CrateNum, - mut f: F) + pub(crate) fn for_each_exported_symbol(&self, cnum: CrateNum, mut f: F) where F: FnMut(&str, DefId, SymbolExportLevel) { for &(ref name, def_id, export_level) in self.exported_symbols(cnum) { @@ -199,13 +197,13 @@ impl ExportedSymbols { } } -pub fn metadata_symbol_name(tcx: TyCtxt) -> String { +pub(crate) fn metadata_symbol_name(tcx: TyCtxt) -> String { format!("rust_metadata_{}_{}", tcx.crate_name(LOCAL_CRATE), tcx.crate_disambiguator(LOCAL_CRATE)) } -pub fn crate_export_threshold(crate_type: config::CrateType) +pub(crate) fn crate_export_threshold(crate_type: config::CrateType) -> SymbolExportLevel { match crate_type { config::CrateTypeExecutable | @@ -217,7 +215,7 @@ pub fn crate_export_threshold(crate_type: config::CrateType) } } -pub fn crates_export_threshold(crate_types: &[config::CrateType]) +pub(crate) fn crates_export_threshold(crate_types: &[config::CrateType]) -> SymbolExportLevel { if crate_types.iter().any(|&crate_type| { crate_export_threshold(crate_type) == SymbolExportLevel::Rust @@ -228,9 +226,9 @@ pub fn crates_export_threshold(crate_types: &[config::CrateType]) } } -pub fn is_below_threshold(level: SymbolExportLevel, - threshold: SymbolExportLevel) - -> bool { +pub(crate) fn is_below_threshold(level: SymbolExportLevel, + threshold: SymbolExportLevel) + -> bool { if threshold == SymbolExportLevel::Rust { // We export everything from Rust dylibs true diff --git a/src/librustc_trans/back/symbol_names.rs b/src/librustc_trans/back/symbol_names.rs index 10b66fb199108..41a34f438cc00 100644 --- a/src/librustc_trans/back/symbol_names.rs +++ b/src/librustc_trans/back/symbol_names.rs @@ -360,7 +360,7 @@ impl ItemPathBuffer for SymbolPathBuffer { // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $ // // returns true if an underscore must be added at the start -pub fn sanitize(result: &mut String, s: &str) -> bool { +pub(crate) fn sanitize(result: &mut String, s: &str) -> bool { for c in s.chars() { match c { // Escape these with $ sequences diff --git a/src/librustc_trans/back/write.rs b/src/librustc_trans/back/write.rs index 5e227ec467abb..3dfd1bb670a24 100644 --- a/src/librustc_trans/back/write.rs +++ b/src/librustc_trans/back/write.rs @@ -60,14 +60,14 @@ pub const CODE_GEN_MODEL_ARGS : [(&'static str, llvm::CodeModel); 5] = [ ("large", llvm::CodeModel::Large), ]; -pub fn llvm_err(handler: &errors::Handler, msg: String) -> FatalError { +pub(crate) fn llvm_err(handler: &errors::Handler, msg: String) -> FatalError { match llvm::last_error() { Some(err) => handler.fatal(&format!("{}: {}", msg, err)), None => handler.fatal(&msg), } } -pub fn write_output_file( +pub(crate) fn write_output_file( handler: &errors::Handler, target: llvm::TargetMachineRef, pm: llvm::PassManagerRef, @@ -130,7 +130,7 @@ fn get_llvm_opt_size(optimize: config::OptLevel) -> llvm::CodeGenOptSize { } } -pub fn create_target_machine(sess: &Session) -> TargetMachineRef { +pub(crate) fn create_target_machine(sess: &Session) -> TargetMachineRef { let reloc_model = get_reloc_model(sess); let opt_level = get_llvm_opt_level(sess.opts.optimize); @@ -191,7 +191,7 @@ pub fn create_target_machine(sess: &Session) -> TargetMachineRef { /// Module-specific configuration for `optimize_and_codegen`. #[derive(Clone)] -pub struct ModuleConfig { +pub(crate) struct ModuleConfig { /// LLVM TargetMachine to use for codegen. tm: TargetMachineRef, /// Names of additional optimization passes to run. @@ -282,28 +282,28 @@ impl ModuleConfig { } /// Additional resources used by optimize_and_codegen (not module specific) -pub struct CodegenContext<'a> { +pub(crate) struct CodegenContext<'a> { // Resouces needed when running LTO - pub time_passes: bool, - pub lto: bool, - pub no_landing_pads: bool, - pub exported_symbols: &'a ExportedSymbols, - pub opts: &'a config::Options, - pub crate_types: Vec, - pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>, + pub(crate) time_passes: bool, + pub(crate) lto: bool, + pub(crate) no_landing_pads: bool, + pub(crate) exported_symbols: &'a ExportedSymbols, + pub(crate) opts: &'a config::Options, + pub(crate) crate_types: Vec, + pub(crate) each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>, // Handler to use for diagnostics produced during codegen. - pub handler: &'a Handler, + pub(crate) handler: &'a Handler, // LLVM passes added by plugins. - pub plugin_passes: Vec, + pub(crate) plugin_passes: Vec, // LLVM optimizations for which we want to print remarks. - pub remark: Passes, + pub(crate) remark: Passes, // Worker thread number - pub worker: usize, + pub(crate) worker: usize, // The incremental compilation session directory, or None if we are not // compiling incrementally - pub incr_comp_session_dir: Option, + pub(crate) incr_comp_session_dir: Option, // Channel back to the main control thread to send messages to - pub tx: Sender, + pub(crate) tx: Sender, } struct HandlerFreeVars<'a> { @@ -1015,7 +1015,7 @@ fn execute_work_item(cgcx: &CodegenContext, work_item: WorkItem) Ok(()) } -pub enum Message { +pub(crate) enum Message { Token(io::Result), Diagnostic(Diagnostic), Done { success: bool }, @@ -1023,7 +1023,7 @@ pub enum Message { AbortIfErrors, } -pub struct Diagnostic { +pub(crate) struct Diagnostic { msg: String, code: Option, lvl: Level, @@ -1320,9 +1320,9 @@ pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) { } } -pub unsafe fn with_llvm_pmb(llmod: ModuleRef, - config: &ModuleConfig, - f: &mut FnMut(llvm::PassManagerBuilderRef)) { +pub(crate) unsafe fn with_llvm_pmb(llmod: ModuleRef, + config: &ModuleConfig, + f: &mut FnMut(llvm::PassManagerBuilderRef)) { // Create the PassManagerBuilder for LLVM. We configure it with // reasonable defaults and prepare it to actually populate the pass // manager. diff --git a/src/librustc_trans/base.rs b/src/librustc_trans/base.rs index 7b836399f9cb5..5e51602647d68 100644 --- a/src/librustc_trans/base.rs +++ b/src/librustc_trans/base.rs @@ -86,14 +86,14 @@ use syntax::ast; use mir::lvalue::Alignment; -pub struct StatRecorder<'a, 'tcx: 'a> { +pub(crate) struct StatRecorder<'a, 'tcx: 'a> { ccx: &'a CrateContext<'a, 'tcx>, name: Option, istart: usize, } impl<'a, 'tcx> StatRecorder<'a, 'tcx> { - pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> { + pub(crate) fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> { let istart = ccx.stats().n_llvm_insns.get(); StatRecorder { ccx: ccx, @@ -116,17 +116,17 @@ impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> { } } -pub fn get_meta(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef { +pub(crate) fn get_meta(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef { bcx.struct_gep(fat_ptr, abi::FAT_PTR_EXTRA) } -pub fn get_dataptr(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef { +pub(crate) fn get_dataptr(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef { bcx.struct_gep(fat_ptr, abi::FAT_PTR_ADDR) } -pub fn bin_op_to_icmp_predicate(op: hir::BinOp_, - signed: bool) - -> llvm::IntPredicate { +pub(crate) fn bin_op_to_icmp_predicate(op: hir::BinOp_, + signed: bool) + -> llvm::IntPredicate { match op { hir::BiEq => llvm::IntEQ, hir::BiNe => llvm::IntNE, @@ -142,7 +142,7 @@ pub fn bin_op_to_icmp_predicate(op: hir::BinOp_, } } -pub fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate { +pub(crate) fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate { match op { hir::BiEq => llvm::RealOEQ, hir::BiNe => llvm::RealUNE, @@ -158,7 +158,7 @@ pub fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate { } } -pub fn compare_simd_types<'a, 'tcx>( +pub(crate) fn compare_simd_types<'a, 'tcx>( bcx: &Builder<'a, 'tcx>, lhs: ValueRef, rhs: ValueRef, @@ -190,11 +190,11 @@ pub fn compare_simd_types<'a, 'tcx>( /// The `old_info` argument is a bit funny. It is intended for use /// in an upcast, where the new vtable for an object will be drived /// from the old one. -pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>, - source: Ty<'tcx>, - target: Ty<'tcx>, - old_info: Option) - -> ValueRef { +pub(crate) fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>, + source: Ty<'tcx>, + target: Ty<'tcx>, + old_info: Option) + -> ValueRef { let (source, target) = ccx.tcx().struct_lockstep_tails(source, target); match (&source.sty, &target.sty) { (&ty::TyArray(_, len), &ty::TySlice(_)) => C_uint(ccx, len), @@ -215,7 +215,7 @@ pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>, } /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer. -pub fn unsize_thin_ptr<'a, 'tcx>( +pub(crate) fn unsize_thin_ptr<'a, 'tcx>( bcx: &Builder<'a, 'tcx>, src: ValueRef, src_ty: Ty<'tcx>, @@ -245,9 +245,9 @@ pub fn unsize_thin_ptr<'a, 'tcx>( /// Coerce `src`, which is a reference to a value of type `src_ty`, /// to a value of type `dst_ty` and store the result in `dst` -pub fn coerce_unsized_into<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, - src: &LvalueRef<'tcx>, - dst: &LvalueRef<'tcx>) { +pub(crate) fn coerce_unsized_into<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, + src: &LvalueRef<'tcx>, + dst: &LvalueRef<'tcx>) { let src_ty = src.ty.to_ty(bcx.tcx()); let dst_ty = dst.ty.to_ty(bcx.tcx()); let coerce_ptr = || { @@ -311,13 +311,13 @@ pub fn coerce_unsized_into<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, } } -pub fn cast_shift_expr_rhs( +pub(crate) fn cast_shift_expr_rhs( cx: &Builder, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef ) -> ValueRef { cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b)) } -pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef { +pub(crate) fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef { cast_shift_rhs(op, lhs, rhs, @@ -365,11 +365,11 @@ fn cast_shift_rhs(op: hir::BinOp_, /// This is only true for MSVC targets, and even then the 64-bit MSVC target /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as /// 64-bit MinGW) instead of "full SEH". -pub fn wants_msvc_seh(sess: &Session) -> bool { +pub(crate) fn wants_msvc_seh(sess: &Session) -> bool { sess.target.target.options.is_like_msvc } -pub fn call_assume<'a, 'tcx>(b: &Builder<'a, 'tcx>, val: ValueRef) { +pub(crate) fn call_assume<'a, 'tcx>(b: &Builder<'a, 'tcx>, val: ValueRef) { let assume_intrinsic = b.ccx.get_intrinsic("llvm.assume"); b.call(assume_intrinsic, &[val], None); } @@ -377,8 +377,8 @@ pub fn call_assume<'a, 'tcx>(b: &Builder<'a, 'tcx>, val: ValueRef) { /// Helper for loading values from memory. Does the necessary conversion if the in-memory type /// differs from the type used for SSA values. Also handles various special cases where the type /// gives us better information about what we are loading. -pub fn load_ty<'a, 'tcx>(b: &Builder<'a, 'tcx>, ptr: ValueRef, - alignment: Alignment, t: Ty<'tcx>) -> ValueRef { +pub(crate) fn load_ty<'a, 'tcx>(b: &Builder<'a, 'tcx>, ptr: ValueRef, + alignment: Alignment, t: Ty<'tcx>) -> ValueRef { let ccx = b.ccx; if type_is_zero_size(ccx, t) { return C_undef(type_of::type_of(ccx, t)); @@ -415,8 +415,8 @@ pub fn load_ty<'a, 'tcx>(b: &Builder<'a, 'tcx>, ptr: ValueRef, /// Helper for storing values in memory. Does the necessary conversion if the in-memory type /// differs from the type used for SSA values. -pub fn store_ty<'a, 'tcx>(cx: &Builder<'a, 'tcx>, v: ValueRef, dst: ValueRef, - dst_align: Alignment, t: Ty<'tcx>) { +pub(crate) fn store_ty<'a, 'tcx>(cx: &Builder<'a, 'tcx>, v: ValueRef, dst: ValueRef, + dst_align: Alignment, t: Ty<'tcx>) { debug!("store_ty: {:?} : {:?} <- {:?}", Value(dst), t, Value(v)); if common::type_is_fat_ptr(cx.ccx, t) { @@ -428,18 +428,18 @@ pub fn store_ty<'a, 'tcx>(cx: &Builder<'a, 'tcx>, v: ValueRef, dst: ValueRef, } } -pub fn store_fat_ptr<'a, 'tcx>(cx: &Builder<'a, 'tcx>, - data: ValueRef, - extra: ValueRef, - dst: ValueRef, - dst_align: Alignment, - _ty: Ty<'tcx>) { +pub(crate) fn store_fat_ptr<'a, 'tcx>(cx: &Builder<'a, 'tcx>, + data: ValueRef, + extra: ValueRef, + dst: ValueRef, + dst_align: Alignment, + _ty: Ty<'tcx>) { // FIXME: emit metadata cx.store(data, get_dataptr(cx, dst), dst_align.to_align()); cx.store(extra, get_meta(cx, dst), dst_align.to_align()); } -pub fn load_fat_ptr<'a, 'tcx>( +pub(crate) fn load_fat_ptr<'a, 'tcx>( b: &Builder<'a, 'tcx>, src: ValueRef, alignment: Alignment, t: Ty<'tcx> ) -> (ValueRef, ValueRef) { let ptr = get_dataptr(b, src); @@ -462,7 +462,7 @@ pub fn load_fat_ptr<'a, 'tcx>( (ptr, meta) } -pub fn from_immediate(bcx: &Builder, val: ValueRef) -> ValueRef { +pub(crate) fn from_immediate(bcx: &Builder, val: ValueRef) -> ValueRef { if val_ty(val) == Type::i1(bcx.ccx) { bcx.zext(val, Type::i8(bcx.ccx)) } else { @@ -470,7 +470,7 @@ pub fn from_immediate(bcx: &Builder, val: ValueRef) -> ValueRef { } } -pub fn to_immediate(bcx: &Builder, val: ValueRef, ty: Ty) -> ValueRef { +pub(crate) fn to_immediate(bcx: &Builder, val: ValueRef, ty: Ty) -> ValueRef { if ty.is_bool() { bcx.trunc(val, Type::i1(bcx.ccx)) } else { @@ -478,7 +478,7 @@ pub fn to_immediate(bcx: &Builder, val: ValueRef, ty: Ty) -> ValueRef { } } -pub enum Lifetime { Start, End } +pub(crate) enum Lifetime { Start, End } impl Lifetime { // If LLVM lifetime intrinsic support is enabled (i.e. optimizations @@ -489,7 +489,7 @@ impl Lifetime { // // If LLVM lifetime intrinsic support is disabled (i.e. optimizations // off) or `ptr` is zero-sized, then no-op (does not call `emit`). - pub fn call(self, b: &Builder, ptr: ValueRef) { + pub(crate) fn call(self, b: &Builder, ptr: ValueRef) { if b.ccx.sess().opts.optimize == config::OptLevel::No { return; } @@ -509,11 +509,11 @@ impl Lifetime { } } -pub fn call_memcpy<'a, 'tcx>(b: &Builder<'a, 'tcx>, - dst: ValueRef, - src: ValueRef, - n_bytes: ValueRef, - align: u32) { +pub(crate) fn call_memcpy<'a, 'tcx>(b: &Builder<'a, 'tcx>, + dst: ValueRef, + src: ValueRef, + n_bytes: ValueRef, + align: u32) { let ccx = b.ccx; let ptr_width = &ccx.sess().target.target.target_pointer_width; let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width); @@ -526,7 +526,7 @@ pub fn call_memcpy<'a, 'tcx>(b: &Builder<'a, 'tcx>, b.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None); } -pub fn memcpy_ty<'a, 'tcx>( +pub(crate) fn memcpy_ty<'a, 'tcx>( bcx: &Builder<'a, 'tcx>, dst: ValueRef, src: ValueRef, @@ -544,12 +544,12 @@ pub fn memcpy_ty<'a, 'tcx>( call_memcpy(bcx, dst, src, C_uint(ccx, size), align); } -pub fn call_memset<'a, 'tcx>(b: &Builder<'a, 'tcx>, - ptr: ValueRef, - fill_byte: ValueRef, - size: ValueRef, - align: ValueRef, - volatile: bool) -> ValueRef { +pub(crate) fn call_memset<'a, 'tcx>(b: &Builder<'a, 'tcx>, + ptr: ValueRef, + fill_byte: ValueRef, + size: ValueRef, + align: ValueRef, + volatile: bool) -> ValueRef { let ptr_width = &b.ccx.sess().target.target.target_pointer_width; let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width); let llintrinsicfn = b.ccx.get_intrinsic(&intrinsic_key); @@ -557,7 +557,7 @@ pub fn call_memset<'a, 'tcx>(b: &Builder<'a, 'tcx>, b.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None) } -pub fn trans_instance<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, instance: Instance<'tcx>) { +pub(crate) fn trans_instance<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, instance: Instance<'tcx>) { let _s = if ccx.sess().trans_stats() { let mut instance_name = String::new(); DefPathBasedNames::new(ccx.tcx(), true, true) @@ -608,7 +608,7 @@ pub fn trans_instance<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, instance: Instance mir::trans_mir(ccx, lldecl, &mir, instance, sig); } -pub fn llvm_linkage_by_name(name: &str) -> Option { +pub(crate) fn llvm_linkage_by_name(name: &str) -> Option { // Use the names from src/llvm/docs/LangRef.rst here. Most types are only // applicable to variable declarations and may not really make sense for // Rust code in the first place but whitelist them anyway and trust that @@ -633,9 +633,9 @@ pub fn llvm_linkage_by_name(name: &str) -> Option { } } -pub fn set_link_section(ccx: &CrateContext, - llval: ValueRef, - attrs: &[ast::Attribute]) { +pub(crate) fn set_link_section(ccx: &CrateContext, + llval: ValueRef, + attrs: &[ast::Attribute]) { if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") { if contains_null(§.as_str()) { ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", §)); @@ -649,7 +649,7 @@ pub fn set_link_section(ccx: &CrateContext, /// Create the `main` function which will initialise the rust runtime and call /// users main function. -pub fn maybe_create_entry_wrapper(ccx: &CrateContext) { +pub(crate) fn maybe_create_entry_wrapper(ccx: &CrateContext) { let (main_def_id, span) = match *ccx.sess().entry_fn.borrow() { Some((id, span)) => { (ccx.tcx().hir.local_def_id(id), span) @@ -876,7 +876,7 @@ fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter { /// /// This list is later used by linkers to determine the set of symbols needed to /// be exposed from a dynamic library and it's also encoded into the metadata. -pub fn find_exported_symbols(tcx: TyCtxt, reachable: &NodeSet) -> NodeSet { +pub(crate) fn find_exported_symbols(tcx: TyCtxt, reachable: &NodeSet) -> NodeSet { reachable.iter().cloned().filter(|&id| { // Next, we want to ignore some FFI functions that are not exposed from // this crate. Reachable FFI functions can be lumped into two diff --git a/src/librustc_trans/builder.rs b/src/librustc_trans/builder.rs index 5103ca5c5e109..87a5e7ce9aa66 100644 --- a/src/librustc_trans/builder.rs +++ b/src/librustc_trans/builder.rs @@ -29,9 +29,9 @@ use syntax_pos::Span; // All Builders must have an llfn associated with them #[must_use] -pub struct Builder<'a, 'tcx: 'a> { - pub llbuilder: BuilderRef, - pub ccx: &'a CrateContext<'a, 'tcx>, +pub(crate) struct Builder<'a, 'tcx: 'a> { + pub(crate) llbuilder: BuilderRef, + pub(crate) ccx: &'a CrateContext<'a, 'tcx>, } impl<'a, 'tcx> Drop for Builder<'a, 'tcx> { @@ -50,7 +50,8 @@ fn noname() -> *const c_char { } impl<'a, 'tcx> Builder<'a, 'tcx> { - pub fn new_block<'b>(ccx: &'a CrateContext<'a, 'tcx>, llfn: ValueRef, name: &'b str) -> Self { + pub(crate) fn new_block<'b>(ccx: &'a CrateContext<'a, 'tcx>, llfn: ValueRef, name: &'b str) + -> Self { let builder = Builder::with_ccx(ccx); let llbb = unsafe { let name = CString::new(name).unwrap(); @@ -64,7 +65,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { builder } - pub fn with_ccx(ccx: &'a CrateContext<'a, 'tcx>) -> Self { + pub(crate) fn with_ccx(ccx: &'a CrateContext<'a, 'tcx>) -> Self { // Create a fresh builder from the crate context. let llbuilder = unsafe { llvm::LLVMCreateBuilderInContext(ccx.llcx()) @@ -75,25 +76,25 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn build_sibling_block<'b>(&self, name: &'b str) -> Builder<'a, 'tcx> { + pub(crate) fn build_sibling_block<'b>(&self, name: &'b str) -> Builder<'a, 'tcx> { Builder::new_block(self.ccx, self.llfn(), name) } - pub fn sess(&self) -> &Session { + pub(crate) fn sess(&self) -> &Session { self.ccx.sess() } - pub fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { + pub(crate) fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { self.ccx.tcx() } - pub fn llfn(&self) -> ValueRef { + pub(crate) fn llfn(&self) -> ValueRef { unsafe { llvm::LLVMGetBasicBlockParent(self.llbb()) } } - pub fn llbb(&self) -> BasicBlockRef { + pub(crate) fn llbb(&self) -> BasicBlockRef { unsafe { llvm::LLVMGetInsertBlock(self.llbuilder) } @@ -109,39 +110,39 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn position_before(&self, insn: ValueRef) { + pub(crate) fn position_before(&self, insn: ValueRef) { unsafe { llvm::LLVMPositionBuilderBefore(self.llbuilder, insn); } } - pub fn position_at_end(&self, llbb: BasicBlockRef) { + pub(crate) fn position_at_end(&self, llbb: BasicBlockRef) { unsafe { llvm::LLVMPositionBuilderAtEnd(self.llbuilder, llbb); } } - pub fn position_at_start(&self, llbb: BasicBlockRef) { + pub(crate) fn position_at_start(&self, llbb: BasicBlockRef) { unsafe { llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb); } } - pub fn ret_void(&self) { + pub(crate) fn ret_void(&self) { self.count_insn("retvoid"); unsafe { llvm::LLVMBuildRetVoid(self.llbuilder); } } - pub fn ret(&self, v: ValueRef) { + pub(crate) fn ret(&self, v: ValueRef) { self.count_insn("ret"); unsafe { llvm::LLVMBuildRet(self.llbuilder, v); } } - pub fn aggregate_ret(&self, ret_vals: &[ValueRef]) { + pub(crate) fn aggregate_ret(&self, ret_vals: &[ValueRef]) { unsafe { llvm::LLVMBuildAggregateRet(self.llbuilder, ret_vals.as_ptr(), @@ -149,39 +150,43 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn br(&self, dest: BasicBlockRef) { + pub(crate) fn br(&self, dest: BasicBlockRef) { self.count_insn("br"); unsafe { llvm::LLVMBuildBr(self.llbuilder, dest); } } - pub fn cond_br(&self, cond: ValueRef, then_llbb: BasicBlockRef, else_llbb: BasicBlockRef) { + pub(crate) fn cond_br(&self, + cond: ValueRef, + then_llbb: BasicBlockRef, + else_llbb: BasicBlockRef) { self.count_insn("condbr"); unsafe { llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb); } } - pub fn switch(&self, v: ValueRef, else_llbb: BasicBlockRef, num_cases: usize) -> ValueRef { + pub(crate) fn switch(&self, v: ValueRef, else_llbb: BasicBlockRef, num_cases: usize) + -> ValueRef { unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, num_cases as c_uint) } } - pub fn indirect_br(&self, addr: ValueRef, num_dests: usize) { + pub(crate) fn indirect_br(&self, addr: ValueRef, num_dests: usize) { self.count_insn("indirectbr"); unsafe { llvm::LLVMBuildIndirectBr(self.llbuilder, addr, num_dests as c_uint); } } - pub fn invoke(&self, - llfn: ValueRef, - args: &[ValueRef], - then: BasicBlockRef, - catch: BasicBlockRef, - bundle: Option<&OperandBundleDef>) -> ValueRef { + pub(crate) fn invoke(&self, + llfn: ValueRef, + args: &[ValueRef], + then: BasicBlockRef, + catch: BasicBlockRef, + bundle: Option<&OperandBundleDef>) -> ValueRef { self.count_insn("invoke"); debug!("Invoke {:?} with args ({})", @@ -206,7 +211,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn unreachable(&self) { + pub(crate) fn unreachable(&self) { self.count_insn("unreachable"); unsafe { llvm::LLVMBuildUnreachable(self.llbuilder); @@ -214,35 +219,35 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } /* Arithmetic */ - pub fn add(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn add(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("add"); unsafe { llvm::LLVMBuildAdd(self.llbuilder, lhs, rhs, noname()) } } - pub fn nswadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn nswadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("nswadd"); unsafe { llvm::LLVMBuildNSWAdd(self.llbuilder, lhs, rhs, noname()) } } - pub fn nuwadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn nuwadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("nuwadd"); unsafe { llvm::LLVMBuildNUWAdd(self.llbuilder, lhs, rhs, noname()) } } - pub fn fadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn fadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("fadd"); unsafe { llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname()) } } - pub fn fadd_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn fadd_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("fadd"); unsafe { let instr = llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname()); @@ -251,35 +256,35 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn sub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn sub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("sub"); unsafe { llvm::LLVMBuildSub(self.llbuilder, lhs, rhs, noname()) } } - pub fn nswsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn nswsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("nwsub"); unsafe { llvm::LLVMBuildNSWSub(self.llbuilder, lhs, rhs, noname()) } } - pub fn nuwsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn nuwsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("nuwsub"); unsafe { llvm::LLVMBuildNUWSub(self.llbuilder, lhs, rhs, noname()) } } - pub fn fsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn fsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("sub"); unsafe { llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname()) } } - pub fn fsub_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn fsub_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("sub"); unsafe { let instr = llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname()); @@ -288,35 +293,35 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn mul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn mul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("mul"); unsafe { llvm::LLVMBuildMul(self.llbuilder, lhs, rhs, noname()) } } - pub fn nswmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn nswmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("nswmul"); unsafe { llvm::LLVMBuildNSWMul(self.llbuilder, lhs, rhs, noname()) } } - pub fn nuwmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn nuwmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("nuwmul"); unsafe { llvm::LLVMBuildNUWMul(self.llbuilder, lhs, rhs, noname()) } } - pub fn fmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn fmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("fmul"); unsafe { llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname()) } } - pub fn fmul_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn fmul_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("fmul"); unsafe { let instr = llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname()); @@ -326,35 +331,35 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } - pub fn udiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn udiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("udiv"); unsafe { llvm::LLVMBuildUDiv(self.llbuilder, lhs, rhs, noname()) } } - pub fn sdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn sdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("sdiv"); unsafe { llvm::LLVMBuildSDiv(self.llbuilder, lhs, rhs, noname()) } } - pub fn exactsdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn exactsdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("exactsdiv"); unsafe { llvm::LLVMBuildExactSDiv(self.llbuilder, lhs, rhs, noname()) } } - pub fn fdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn fdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("fdiv"); unsafe { llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname()) } } - pub fn fdiv_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn fdiv_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("fdiv"); unsafe { let instr = llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname()); @@ -363,28 +368,28 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn urem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn urem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("urem"); unsafe { llvm::LLVMBuildURem(self.llbuilder, lhs, rhs, noname()) } } - pub fn srem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn srem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("srem"); unsafe { llvm::LLVMBuildSRem(self.llbuilder, lhs, rhs, noname()) } } - pub fn frem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn frem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("frem"); unsafe { llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname()) } } - pub fn frem_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn frem_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("frem"); unsafe { let instr = llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname()); @@ -393,49 +398,49 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn shl(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn shl(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("shl"); unsafe { llvm::LLVMBuildShl(self.llbuilder, lhs, rhs, noname()) } } - pub fn lshr(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn lshr(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("lshr"); unsafe { llvm::LLVMBuildLShr(self.llbuilder, lhs, rhs, noname()) } } - pub fn ashr(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn ashr(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("ashr"); unsafe { llvm::LLVMBuildAShr(self.llbuilder, lhs, rhs, noname()) } } - pub fn and(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn and(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("and"); unsafe { llvm::LLVMBuildAnd(self.llbuilder, lhs, rhs, noname()) } } - pub fn or(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn or(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("or"); unsafe { llvm::LLVMBuildOr(self.llbuilder, lhs, rhs, noname()) } } - pub fn xor(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn xor(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("xor"); unsafe { llvm::LLVMBuildXor(self.llbuilder, lhs, rhs, noname()) } } - pub fn binop(&self, op: Opcode, lhs: ValueRef, rhs: ValueRef) + pub(crate) fn binop(&self, op: Opcode, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("binop"); unsafe { @@ -443,41 +448,41 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn neg(&self, v: ValueRef) -> ValueRef { + pub(crate) fn neg(&self, v: ValueRef) -> ValueRef { self.count_insn("neg"); unsafe { llvm::LLVMBuildNeg(self.llbuilder, v, noname()) } } - pub fn nswneg(&self, v: ValueRef) -> ValueRef { + pub(crate) fn nswneg(&self, v: ValueRef) -> ValueRef { self.count_insn("nswneg"); unsafe { llvm::LLVMBuildNSWNeg(self.llbuilder, v, noname()) } } - pub fn nuwneg(&self, v: ValueRef) -> ValueRef { + pub(crate) fn nuwneg(&self, v: ValueRef) -> ValueRef { self.count_insn("nuwneg"); unsafe { llvm::LLVMBuildNUWNeg(self.llbuilder, v, noname()) } } - pub fn fneg(&self, v: ValueRef) -> ValueRef { + pub(crate) fn fneg(&self, v: ValueRef) -> ValueRef { self.count_insn("fneg"); unsafe { llvm::LLVMBuildFNeg(self.llbuilder, v, noname()) } } - pub fn not(&self, v: ValueRef) -> ValueRef { + pub(crate) fn not(&self, v: ValueRef) -> ValueRef { self.count_insn("not"); unsafe { llvm::LLVMBuildNot(self.llbuilder, v, noname()) } } - pub fn alloca(&self, ty: Type, name: &str, align: Option) -> ValueRef { + pub(crate) fn alloca(&self, ty: Type, name: &str, align: Option) -> ValueRef { let builder = Builder::with_ccx(self.ccx); builder.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) @@ -485,7 +490,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { builder.dynamic_alloca(ty, name, align) } - pub fn dynamic_alloca(&self, ty: Type, name: &str, align: Option) -> ValueRef { + pub(crate) fn dynamic_alloca(&self, ty: Type, name: &str, align: Option) -> ValueRef { self.count_insn("alloca"); unsafe { let alloca = if name.is_empty() { @@ -502,14 +507,14 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn free(&self, ptr: ValueRef) { + pub(crate) fn free(&self, ptr: ValueRef) { self.count_insn("free"); unsafe { llvm::LLVMBuildFree(self.llbuilder, ptr); } } - pub fn load(&self, ptr: ValueRef, align: Option) -> ValueRef { + pub(crate) fn load(&self, ptr: ValueRef, align: Option) -> ValueRef { self.count_insn("load"); unsafe { let load = llvm::LLVMBuildLoad(self.llbuilder, ptr, noname()); @@ -520,7 +525,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn volatile_load(&self, ptr: ValueRef) -> ValueRef { + pub(crate) fn volatile_load(&self, ptr: ValueRef) -> ValueRef { self.count_insn("load.volatile"); unsafe { let insn = llvm::LLVMBuildLoad(self.llbuilder, ptr, noname()); @@ -529,7 +534,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn atomic_load(&self, ptr: ValueRef, order: AtomicOrdering) -> ValueRef { + pub(crate) fn atomic_load(&self, ptr: ValueRef, order: AtomicOrdering) -> ValueRef { self.count_insn("load.atomic"); unsafe { let ty = Type::from_ref(llvm::LLVMTypeOf(ptr)); @@ -540,9 +545,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } - pub fn load_range_assert(&self, ptr: ValueRef, lo: u64, - hi: u64, signed: llvm::Bool, - align: Option) -> ValueRef { + pub(crate) fn load_range_assert(&self, ptr: ValueRef, lo: u64, + hi: u64, signed: llvm::Bool, + align: Option) -> ValueRef { let value = self.load(ptr, align); unsafe { @@ -561,7 +566,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { value } - pub fn load_nonnull(&self, ptr: ValueRef, align: Option) -> ValueRef { + pub(crate) fn load_nonnull(&self, ptr: ValueRef, align: Option) -> ValueRef { let value = self.load(ptr, align); unsafe { llvm::LLVMSetMetadata(value, llvm::MD_nonnull as c_uint, @@ -571,7 +576,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { value } - pub fn store(&self, val: ValueRef, ptr: ValueRef, align: Option) -> ValueRef { + pub(crate) fn store(&self, val: ValueRef, ptr: ValueRef, align: Option) -> ValueRef { debug!("Store {:?} -> {:?}", Value(val), Value(ptr)); assert!(!self.llbuilder.is_null()); self.count_insn("store"); @@ -585,7 +590,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn volatile_store(&self, val: ValueRef, ptr: ValueRef) -> ValueRef { + pub(crate) fn volatile_store(&self, val: ValueRef, ptr: ValueRef) -> ValueRef { debug!("Store {:?} -> {:?}", Value(val), Value(ptr)); assert!(!self.llbuilder.is_null()); self.count_insn("store.volatile"); @@ -597,7 +602,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn atomic_store(&self, val: ValueRef, ptr: ValueRef, order: AtomicOrdering) { + pub(crate) fn atomic_store(&self, val: ValueRef, ptr: ValueRef, order: AtomicOrdering) { debug!("Store {:?} -> {:?}", Value(val), Value(ptr)); self.count_insn("store.atomic"); let ptr = self.check_store(val, ptr); @@ -608,7 +613,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn gep(&self, ptr: ValueRef, indices: &[ValueRef]) -> ValueRef { + pub(crate) fn gep(&self, ptr: ValueRef, indices: &[ValueRef]) -> ValueRef { self.count_insn("gep"); unsafe { llvm::LLVMBuildGEP(self.llbuilder, ptr, indices.as_ptr(), @@ -619,7 +624,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // Simple wrapper around GEP that takes an array of ints and wraps them // in C_i32() #[inline] - pub fn gepi(&self, base: ValueRef, ixs: &[usize]) -> ValueRef { + pub(crate) fn gepi(&self, base: ValueRef, ixs: &[usize]) -> ValueRef { // Small vector optimization. This should catch 100% of the cases that // we care about. if ixs.len() < 16 { @@ -635,7 +640,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn inbounds_gep(&self, ptr: ValueRef, indices: &[ValueRef]) -> ValueRef { + pub(crate) fn inbounds_gep(&self, ptr: ValueRef, indices: &[ValueRef]) -> ValueRef { self.count_insn("inboundsgep"); unsafe { llvm::LLVMBuildInBoundsGEP( @@ -643,21 +648,21 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn struct_gep(&self, ptr: ValueRef, idx: usize) -> ValueRef { + pub(crate) fn struct_gep(&self, ptr: ValueRef, idx: usize) -> ValueRef { self.count_insn("structgep"); unsafe { llvm::LLVMBuildStructGEP(self.llbuilder, ptr, idx as c_uint, noname()) } } - pub fn global_string(&self, _str: *const c_char) -> ValueRef { + pub(crate) fn global_string(&self, _str: *const c_char) -> ValueRef { self.count_insn("globalstring"); unsafe { llvm::LLVMBuildGlobalString(self.llbuilder, _str, noname()) } } - pub fn global_string_ptr(&self, _str: *const c_char) -> ValueRef { + pub(crate) fn global_string_ptr(&self, _str: *const c_char) -> ValueRef { self.count_insn("globalstringptr"); unsafe { llvm::LLVMBuildGlobalStringPtr(self.llbuilder, _str, noname()) @@ -665,133 +670,133 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } /* Casts */ - pub fn trunc(&self, val: ValueRef, dest_ty: Type) -> ValueRef { + pub(crate) fn trunc(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("trunc"); unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty.to_ref(), noname()) } } - pub fn zext(&self, val: ValueRef, dest_ty: Type) -> ValueRef { + pub(crate) fn zext(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("zext"); unsafe { llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty.to_ref(), noname()) } } - pub fn sext(&self, val: ValueRef, dest_ty: Type) -> ValueRef { + pub(crate) fn sext(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("sext"); unsafe { llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty.to_ref(), noname()) } } - pub fn fptoui(&self, val: ValueRef, dest_ty: Type) -> ValueRef { + pub(crate) fn fptoui(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("fptoui"); unsafe { llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty.to_ref(), noname()) } } - pub fn fptosi(&self, val: ValueRef, dest_ty: Type) -> ValueRef { + pub(crate) fn fptosi(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("fptosi"); unsafe { llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty.to_ref(),noname()) } } - pub fn uitofp(&self, val: ValueRef, dest_ty: Type) -> ValueRef { + pub(crate) fn uitofp(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("uitofp"); unsafe { llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty.to_ref(), noname()) } } - pub fn sitofp(&self, val: ValueRef, dest_ty: Type) -> ValueRef { + pub(crate) fn sitofp(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("sitofp"); unsafe { llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty.to_ref(), noname()) } } - pub fn fptrunc(&self, val: ValueRef, dest_ty: Type) -> ValueRef { + pub(crate) fn fptrunc(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("fptrunc"); unsafe { llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty.to_ref(), noname()) } } - pub fn fpext(&self, val: ValueRef, dest_ty: Type) -> ValueRef { + pub(crate) fn fpext(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("fpext"); unsafe { llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty.to_ref(), noname()) } } - pub fn ptrtoint(&self, val: ValueRef, dest_ty: Type) -> ValueRef { + pub(crate) fn ptrtoint(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("ptrtoint"); unsafe { llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty.to_ref(), noname()) } } - pub fn inttoptr(&self, val: ValueRef, dest_ty: Type) -> ValueRef { + pub(crate) fn inttoptr(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("inttoptr"); unsafe { llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty.to_ref(), noname()) } } - pub fn bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef { + pub(crate) fn bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("bitcast"); unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty.to_ref(), noname()) } } - pub fn zext_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef { + pub(crate) fn zext_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("zextorbitcast"); unsafe { llvm::LLVMBuildZExtOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname()) } } - pub fn sext_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef { + pub(crate) fn sext_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("sextorbitcast"); unsafe { llvm::LLVMBuildSExtOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname()) } } - pub fn trunc_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef { + pub(crate) fn trunc_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("truncorbitcast"); unsafe { llvm::LLVMBuildTruncOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname()) } } - pub fn cast(&self, op: Opcode, val: ValueRef, dest_ty: Type) -> ValueRef { + pub(crate) fn cast(&self, op: Opcode, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("cast"); unsafe { llvm::LLVMBuildCast(self.llbuilder, op, val, dest_ty.to_ref(), noname()) } } - pub fn pointercast(&self, val: ValueRef, dest_ty: Type) -> ValueRef { + pub(crate) fn pointercast(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("pointercast"); unsafe { llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty.to_ref(), noname()) } } - pub fn intcast(&self, val: ValueRef, dest_ty: Type, is_signed: bool) -> ValueRef { + pub(crate) fn intcast(&self, val: ValueRef, dest_ty: Type, is_signed: bool) -> ValueRef { self.count_insn("intcast"); unsafe { llvm::LLVMRustBuildIntCast(self.llbuilder, val, dest_ty.to_ref(), is_signed) } } - pub fn fpcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef { + pub(crate) fn fpcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("fpcast"); unsafe { llvm::LLVMBuildFPCast(self.llbuilder, val, dest_ty.to_ref(), noname()) @@ -800,14 +805,14 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { /* Comparisons */ - pub fn icmp(&self, op: IntPredicate, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn icmp(&self, op: IntPredicate, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("icmp"); unsafe { llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, noname()) } } - pub fn fcmp(&self, op: RealPredicate, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn fcmp(&self, op: RealPredicate, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("fcmp"); unsafe { llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, noname()) @@ -815,14 +820,14 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } /* Miscellaneous instructions */ - pub fn empty_phi(&self, ty: Type) -> ValueRef { + pub(crate) fn empty_phi(&self, ty: Type) -> ValueRef { self.count_insn("emptyphi"); unsafe { llvm::LLVMBuildPhi(self.llbuilder, ty.to_ref(), noname()) } } - pub fn phi(&self, ty: Type, vals: &[ValueRef], bbs: &[BasicBlockRef]) -> ValueRef { + pub(crate) fn phi(&self, ty: Type, vals: &[ValueRef], bbs: &[BasicBlockRef]) -> ValueRef { assert_eq!(vals.len(), bbs.len()); let phi = self.empty_phi(ty); self.count_insn("addincoming"); @@ -834,7 +839,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn add_span_comment(&self, sp: Span, text: &str) { + pub(crate) fn add_span_comment(&self, sp: Span, text: &str) { if self.ccx.sess().asm_comments() { let s = format!("{} ({})", text, @@ -844,7 +849,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn add_comment(&self, text: &str) { + pub(crate) fn add_comment(&self, text: &str) { if self.ccx.sess().asm_comments() { let sanitized = text.replace("$", ""); let comment_text = format!("{} {}", "#", @@ -860,10 +865,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn inline_asm_call(&self, asm: *const c_char, cons: *const c_char, - inputs: &[ValueRef], output: Type, - volatile: bool, alignstack: bool, - dia: AsmDialect) -> ValueRef { + pub(crate) fn inline_asm_call(&self, asm: *const c_char, cons: *const c_char, + inputs: &[ValueRef], output: Type, + volatile: bool, alignstack: bool, + dia: AsmDialect) -> ValueRef { self.count_insn("inlineasm"); let volatile = if volatile { llvm::True } @@ -885,8 +890,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn call(&self, llfn: ValueRef, args: &[ValueRef], - bundle: Option<&OperandBundleDef>) -> ValueRef { + pub(crate) fn call(&self, llfn: ValueRef, args: &[ValueRef], + bundle: Option<&OperandBundleDef>) -> ValueRef { self.count_insn("call"); debug!("Call {:?} with args ({})", @@ -905,42 +910,43 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn select(&self, cond: ValueRef, then_val: ValueRef, else_val: ValueRef) -> ValueRef { + pub(crate) fn select(&self, cond: ValueRef, then_val: ValueRef, else_val: ValueRef) + -> ValueRef { self.count_insn("select"); unsafe { llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, noname()) } } - pub fn va_arg(&self, list: ValueRef, ty: Type) -> ValueRef { + pub(crate) fn va_arg(&self, list: ValueRef, ty: Type) -> ValueRef { self.count_insn("vaarg"); unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty.to_ref(), noname()) } } - pub fn extract_element(&self, vec: ValueRef, idx: ValueRef) -> ValueRef { + pub(crate) fn extract_element(&self, vec: ValueRef, idx: ValueRef) -> ValueRef { self.count_insn("extractelement"); unsafe { llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, noname()) } } - pub fn insert_element(&self, vec: ValueRef, elt: ValueRef, idx: ValueRef) -> ValueRef { + pub(crate) fn insert_element(&self, vec: ValueRef, elt: ValueRef, idx: ValueRef) -> ValueRef { self.count_insn("insertelement"); unsafe { llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, noname()) } } - pub fn shuffle_vector(&self, v1: ValueRef, v2: ValueRef, mask: ValueRef) -> ValueRef { + pub(crate) fn shuffle_vector(&self, v1: ValueRef, v2: ValueRef, mask: ValueRef) -> ValueRef { self.count_insn("shufflevector"); unsafe { llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, noname()) } } - pub fn vector_splat(&self, num_elts: usize, elt: ValueRef) -> ValueRef { + pub(crate) fn vector_splat(&self, num_elts: usize, elt: ValueRef) -> ValueRef { unsafe { let elt_ty = val_ty(elt); let undef = llvm::LLVMGetUndef(Type::vector(&elt_ty, num_elts as u64).to_ref()); @@ -950,15 +956,15 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn extract_value(&self, agg_val: ValueRef, idx: usize) -> ValueRef { + pub(crate) fn extract_value(&self, agg_val: ValueRef, idx: usize) -> ValueRef { self.count_insn("extractvalue"); unsafe { llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, noname()) } } - pub fn insert_value(&self, agg_val: ValueRef, elt: ValueRef, - idx: usize) -> ValueRef { + pub(crate) fn insert_value(&self, agg_val: ValueRef, elt: ValueRef, + idx: usize) -> ValueRef { self.count_insn("insertvalue"); unsafe { llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint, @@ -966,28 +972,28 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn is_null(&self, val: ValueRef) -> ValueRef { + pub(crate) fn is_null(&self, val: ValueRef) -> ValueRef { self.count_insn("isnull"); unsafe { llvm::LLVMBuildIsNull(self.llbuilder, val, noname()) } } - pub fn is_not_null(&self, val: ValueRef) -> ValueRef { + pub(crate) fn is_not_null(&self, val: ValueRef) -> ValueRef { self.count_insn("isnotnull"); unsafe { llvm::LLVMBuildIsNotNull(self.llbuilder, val, noname()) } } - pub fn ptrdiff(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + pub(crate) fn ptrdiff(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("ptrdiff"); unsafe { llvm::LLVMBuildPtrDiff(self.llbuilder, lhs, rhs, noname()) } } - pub fn trap(&self) { + pub(crate) fn trap(&self) { unsafe { let bb: BasicBlockRef = llvm::LLVMGetInsertBlock(self.llbuilder); let fn_: ValueRef = llvm::LLVMGetBasicBlockParent(bb); @@ -1004,9 +1010,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn landing_pad(&self, ty: Type, pers_fn: ValueRef, - num_clauses: usize, - llfn: ValueRef) -> ValueRef { + pub(crate) fn landing_pad(&self, ty: Type, pers_fn: ValueRef, + num_clauses: usize, + llfn: ValueRef) -> ValueRef { self.count_insn("landingpad"); unsafe { llvm::LLVMRustBuildLandingPad(self.llbuilder, ty.to_ref(), pers_fn, @@ -1014,29 +1020,29 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - pub fn add_clause(&self, landing_pad: ValueRef, clause: ValueRef) { + pub(crate) fn add_clause(&self, landing_pad: ValueRef, clause: ValueRef) { unsafe { llvm::LLVMAddClause(landing_pad, clause); } } - pub fn set_cleanup(&self, landing_pad: ValueRef) { + pub(crate) fn set_cleanup(&self, landing_pad: ValueRef) { self.count_insn("setcleanup"); unsafe { llvm::LLVMSetCleanup(landing_pad, llvm::True); } } - pub fn resume(&self, exn: ValueRef) -> ValueRef { + pub(crate) fn resume(&self, exn: ValueRef) -> ValueRef { self.count_insn("resume"); unsafe { llvm::LLVMBuildResume(self.llbuilder, exn) } } - pub fn cleanup_pad(&self, - parent: Option, - args: &[ValueRef]) -> ValueRef { + pub(crate) fn cleanup_pad(&self, + parent: Option, + args: &[ValueRef]) -> ValueRef { self.count_insn("cleanuppad"); let parent = parent.unwrap_or(ptr::null_mut()); let name = CString::new("cleanuppad").unwrap(); @@ -1051,8 +1057,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { return ret } - pub fn cleanup_ret(&self, cleanup: ValueRef, - unwind: Option) -> ValueRef { + pub(crate) fn cleanup_ret(&self, cleanup: ValueRef, + unwind: Option) -> ValueRef { self.count_insn("cleanupret"); let unwind = unwind.unwrap_or(ptr::null_mut()); let ret = unsafe { @@ -1062,9 +1068,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { return ret } - pub fn catch_pad(&self, - parent: ValueRef, - args: &[ValueRef]) -> ValueRef { + pub(crate) fn catch_pad(&self, + parent: ValueRef, + args: &[ValueRef]) -> ValueRef { self.count_insn("catchpad"); let name = CString::new("catchpad").unwrap(); let ret = unsafe { @@ -1076,7 +1082,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { return ret } - pub fn catch_ret(&self, pad: ValueRef, unwind: BasicBlockRef) -> ValueRef { + pub(crate) fn catch_ret(&self, pad: ValueRef, unwind: BasicBlockRef) -> ValueRef { self.count_insn("catchret"); let ret = unsafe { llvm::LLVMRustBuildCatchRet(self.llbuilder, pad, unwind) @@ -1085,10 +1091,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { return ret } - pub fn catch_switch(&self, - parent: Option, - unwind: Option, - num_handlers: usize) -> ValueRef { + pub(crate) fn catch_switch(&self, + parent: Option, + unwind: Option, + num_handlers: usize) -> ValueRef { self.count_insn("catchswitch"); let parent = parent.unwrap_or(ptr::null_mut()); let unwind = unwind.unwrap_or(ptr::null_mut()); @@ -1102,58 +1108,58 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { return ret } - pub fn add_handler(&self, catch_switch: ValueRef, handler: BasicBlockRef) { + pub(crate) fn add_handler(&self, catch_switch: ValueRef, handler: BasicBlockRef) { unsafe { llvm::LLVMRustAddHandler(catch_switch, handler); } } - pub fn set_personality_fn(&self, personality: ValueRef) { + pub(crate) fn set_personality_fn(&self, personality: ValueRef) { unsafe { llvm::LLVMSetPersonalityFn(self.llfn(), personality); } } // Atomic Operations - pub fn atomic_cmpxchg(&self, dst: ValueRef, - cmp: ValueRef, src: ValueRef, - order: AtomicOrdering, - failure_order: AtomicOrdering, - weak: llvm::Bool) -> ValueRef { + pub(crate) fn atomic_cmpxchg(&self, dst: ValueRef, + cmp: ValueRef, src: ValueRef, + order: AtomicOrdering, + failure_order: AtomicOrdering, + weak: llvm::Bool) -> ValueRef { unsafe { llvm::LLVMRustBuildAtomicCmpXchg(self.llbuilder, dst, cmp, src, order, failure_order, weak) } } - pub fn atomic_rmw(&self, op: AtomicRmwBinOp, - dst: ValueRef, src: ValueRef, - order: AtomicOrdering) -> ValueRef { + pub(crate) fn atomic_rmw(&self, op: AtomicRmwBinOp, + dst: ValueRef, src: ValueRef, + order: AtomicOrdering) -> ValueRef { unsafe { llvm::LLVMBuildAtomicRMW(self.llbuilder, op, dst, src, order, False) } } - pub fn atomic_fence(&self, order: AtomicOrdering, scope: SynchronizationScope) { + pub(crate) fn atomic_fence(&self, order: AtomicOrdering, scope: SynchronizationScope) { unsafe { llvm::LLVMRustBuildAtomicFence(self.llbuilder, order, scope); } } - pub fn add_case(&self, s: ValueRef, on_val: ValueRef, dest: BasicBlockRef) { + pub(crate) fn add_case(&self, s: ValueRef, on_val: ValueRef, dest: BasicBlockRef) { unsafe { if llvm::LLVMIsUndef(s) == llvm::True { return; } llvm::LLVMAddCase(s, on_val, dest) } } - pub fn add_incoming_to_phi(&self, phi: ValueRef, val: ValueRef, bb: BasicBlockRef) { + pub(crate) fn add_incoming_to_phi(&self, phi: ValueRef, val: ValueRef, bb: BasicBlockRef) { unsafe { if llvm::LLVMIsUndef(phi) == llvm::True { return; } llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint); } } - pub fn set_invariant_load(&self, load: ValueRef) { + pub(crate) fn set_invariant_load(&self, load: ValueRef) { unsafe { llvm::LLVMSetMetadata(load, llvm::MD_invariant_load as c_uint, llvm::LLVMMDNodeInContext(self.ccx.llcx(), ptr::null(), 0)); diff --git a/src/librustc_trans/cabi_aarch64.rs b/src/librustc_trans/cabi_aarch64.rs index c8c5af714d92a..5b5dbaad1fcd4 100644 --- a/src/librustc_trans/cabi_aarch64.rs +++ b/src/librustc_trans/cabi_aarch64.rs @@ -100,7 +100,7 @@ fn classify_arg_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg: &mut ArgType<'tc arg.make_indirect(ccx); } -pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { +pub(crate) fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { if !fty.ret.is_ignore() { classify_ret_ty(ccx, &mut fty.ret); } diff --git a/src/librustc_trans/cabi_arm.rs b/src/librustc_trans/cabi_arm.rs index 7a91cad511d6d..ec077b9be6789 100644 --- a/src/librustc_trans/cabi_arm.rs +++ b/src/librustc_trans/cabi_arm.rs @@ -48,7 +48,7 @@ fn classify_arg_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg: &mut ArgType<'tc }); } -pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { +pub(crate) fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { if !fty.ret.is_ignore() { classify_ret_ty(ccx, &mut fty.ret); } diff --git a/src/librustc_trans/cabi_asmjs.rs b/src/librustc_trans/cabi_asmjs.rs index f05dda8bce21a..6da52e7cdcb41 100644 --- a/src/librustc_trans/cabi_asmjs.rs +++ b/src/librustc_trans/cabi_asmjs.rs @@ -40,7 +40,7 @@ fn classify_arg_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg: &mut ArgType<'tc } } -pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { +pub(crate) fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { if !fty.ret.is_ignore() { classify_ret_ty(ccx, &mut fty.ret); } diff --git a/src/librustc_trans/cabi_hexagon.rs b/src/librustc_trans/cabi_hexagon.rs index 1acda72675c31..17cadce03b9b8 100644 --- a/src/librustc_trans/cabi_hexagon.rs +++ b/src/librustc_trans/cabi_hexagon.rs @@ -29,7 +29,7 @@ fn classify_arg_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg: &mut ArgType<'tc } } -pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { +pub(crate) fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { if !fty.ret.is_ignore() { classify_ret_ty(ccx, &mut fty.ret); } diff --git a/src/librustc_trans/cabi_mips.rs b/src/librustc_trans/cabi_mips.rs index b7b60859d4a04..5b4b47fac7b0a 100644 --- a/src/librustc_trans/cabi_mips.rs +++ b/src/librustc_trans/cabi_mips.rs @@ -41,7 +41,7 @@ fn classify_arg_ty(ccx: &CrateContext, arg: &mut ArgType, offset: &mut u64) { *offset += align_up_to(size.bytes(), align); } -pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { +pub(crate) fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { if !fty.ret.is_ignore() { classify_ret_ty(ccx, &mut fty.ret); } diff --git a/src/librustc_trans/cabi_mips64.rs b/src/librustc_trans/cabi_mips64.rs index dff75e628de10..ddf9244741681 100644 --- a/src/librustc_trans/cabi_mips64.rs +++ b/src/librustc_trans/cabi_mips64.rs @@ -41,7 +41,7 @@ fn classify_arg_ty(ccx: &CrateContext, arg: &mut ArgType, offset: &mut u64) { *offset += align_up_to(size.bytes(), align); } -pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { +pub(crate) fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { if !fty.ret.is_ignore() { classify_ret_ty(ccx, &mut fty.ret); } diff --git a/src/librustc_trans/cabi_msp430.rs b/src/librustc_trans/cabi_msp430.rs index 546bb5ad9b44e..64389fd64a560 100644 --- a/src/librustc_trans/cabi_msp430.rs +++ b/src/librustc_trans/cabi_msp430.rs @@ -36,7 +36,7 @@ fn classify_arg_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg: &mut ArgType<'tc } } -pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { +pub(crate) fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { if !fty.ret.is_ignore() { classify_ret_ty(ccx, &mut fty.ret); } diff --git a/src/librustc_trans/cabi_nvptx.rs b/src/librustc_trans/cabi_nvptx.rs index 3873752b25470..b10faa4b5f9bb 100644 --- a/src/librustc_trans/cabi_nvptx.rs +++ b/src/librustc_trans/cabi_nvptx.rs @@ -30,7 +30,7 @@ fn classify_arg_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg: &mut ArgType<'tc } } -pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { +pub(crate) fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { if !fty.ret.is_ignore() { classify_ret_ty(ccx, &mut fty.ret); } diff --git a/src/librustc_trans/cabi_nvptx64.rs b/src/librustc_trans/cabi_nvptx64.rs index 24bf4920c16c1..8ab06d3de6a91 100644 --- a/src/librustc_trans/cabi_nvptx64.rs +++ b/src/librustc_trans/cabi_nvptx64.rs @@ -30,7 +30,7 @@ fn classify_arg_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg: &mut ArgType<'tc } } -pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { +pub(crate) fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { if !fty.ret.is_ignore() { classify_ret_ty(ccx, &mut fty.ret); } diff --git a/src/librustc_trans/cabi_powerpc.rs b/src/librustc_trans/cabi_powerpc.rs index f951ac76391f6..5b058e54bb467 100644 --- a/src/librustc_trans/cabi_powerpc.rs +++ b/src/librustc_trans/cabi_powerpc.rs @@ -42,7 +42,7 @@ fn classify_arg_ty(ccx: &CrateContext, arg: &mut ArgType, offset: &mut u64) { *offset += align_up_to(size.bytes(), align); } -pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { +pub(crate) fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { if !fty.ret.is_ignore() { classify_ret_ty(ccx, &mut fty.ret); } diff --git a/src/librustc_trans/cabi_powerpc64.rs b/src/librustc_trans/cabi_powerpc64.rs index c4f8d0b4b9637..63d1d3ebca790 100644 --- a/src/librustc_trans/cabi_powerpc64.rs +++ b/src/librustc_trans/cabi_powerpc64.rs @@ -98,7 +98,7 @@ fn classify_arg_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg: &mut ArgType<'tc }); } -pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { +pub(crate) fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { if !fty.ret.is_ignore() { classify_ret_ty(ccx, &mut fty.ret); } diff --git a/src/librustc_trans/cabi_s390x.rs b/src/librustc_trans/cabi_s390x.rs index fedebea3f4c99..a86c8ee8a73e3 100644 --- a/src/librustc_trans/cabi_s390x.rs +++ b/src/librustc_trans/cabi_s390x.rs @@ -64,7 +64,7 @@ fn classify_arg_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg: &mut ArgType<'tc } } -pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { +pub(crate) fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { if !fty.ret.is_ignore() { classify_ret_ty(ccx, &mut fty.ret); } diff --git a/src/librustc_trans/cabi_sparc.rs b/src/librustc_trans/cabi_sparc.rs index c17901e1adebc..85031e46abc43 100644 --- a/src/librustc_trans/cabi_sparc.rs +++ b/src/librustc_trans/cabi_sparc.rs @@ -41,7 +41,7 @@ fn classify_arg_ty(ccx: &CrateContext, arg: &mut ArgType, offset: &mut u64) { *offset += align_up_to(size.bytes(), align); } -pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { +pub(crate) fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { if !fty.ret.is_ignore() { classify_ret_ty(ccx, &mut fty.ret); } diff --git a/src/librustc_trans/cabi_sparc64.rs b/src/librustc_trans/cabi_sparc64.rs index b75fa97f948ec..ce690937026b8 100644 --- a/src/librustc_trans/cabi_sparc64.rs +++ b/src/librustc_trans/cabi_sparc64.rs @@ -92,7 +92,7 @@ fn classify_arg_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, arg: &mut ArgType<'tc }); } -pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { +pub(crate) fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { if !fty.ret.is_ignore() { classify_ret_ty(ccx, &mut fty.ret); } diff --git a/src/librustc_trans/cabi_x86.rs b/src/librustc_trans/cabi_x86.rs index 9f5520dabe334..cd0b52a9d2bec 100644 --- a/src/librustc_trans/cabi_x86.rs +++ b/src/librustc_trans/cabi_x86.rs @@ -12,14 +12,14 @@ use abi::{ArgAttribute, FnType, LayoutExt, Reg, RegKind}; use common::CrateContext; #[derive(PartialEq)] -pub enum Flavor { +pub(crate) enum Flavor { General, Fastcall } -pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, - fty: &mut FnType<'tcx>, - flavor: Flavor) { +pub(crate) fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, + fty: &mut FnType<'tcx>, + flavor: Flavor) { if !fty.ret.is_ignore() { if fty.ret.layout.is_aggregate() { // Returning a structure. Most often, this will use diff --git a/src/librustc_trans/cabi_x86_64.rs b/src/librustc_trans/cabi_x86_64.rs index 2cfab7df8b30b..5a0aebea561b9 100644 --- a/src/librustc_trans/cabi_x86_64.rs +++ b/src/librustc_trans/cabi_x86_64.rs @@ -203,7 +203,7 @@ fn cast_target(cls: &[Class], size: u64) -> CastTarget { target } -pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { +pub(crate) fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { let mut int_regs = 6; // RDI, RSI, RDX, RCX, R8, R9 let mut sse_regs = 8; // XMM0-7 diff --git a/src/librustc_trans/cabi_x86_win64.rs b/src/librustc_trans/cabi_x86_win64.rs index 39e728d4e4f9b..18a04bc581041 100644 --- a/src/librustc_trans/cabi_x86_win64.rs +++ b/src/librustc_trans/cabi_x86_win64.rs @@ -15,7 +15,7 @@ use rustc::ty::layout::Layout; // Win64 ABI: http://msdn.microsoft.com/en-us/library/zthk2dkh.aspx -pub fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { +pub(crate) fn compute_abi_info<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fty: &mut FnType<'tcx>) { let fixup = |a: &mut ArgType<'tcx>| { let size = a.layout.size(ccx); if a.layout.is_aggregate() { diff --git a/src/librustc_trans/callee.rs b/src/librustc_trans/callee.rs index 76f94565bae51..49491c89415f6 100644 --- a/src/librustc_trans/callee.rs +++ b/src/librustc_trans/callee.rs @@ -33,9 +33,9 @@ use type_of; /// /// - `ccx`: the crate context /// - `instance`: the instance to be instantiated -pub fn get_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, - instance: Instance<'tcx>) - -> ValueRef +pub(crate) fn get_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, + instance: Instance<'tcx>) + -> ValueRef { let tcx = ccx.tcx(); @@ -139,10 +139,10 @@ pub fn get_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, llfn } -pub fn resolve_and_get_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, - def_id: DefId, - substs: &'tcx Substs<'tcx>) - -> ValueRef +pub(crate) fn resolve_and_get_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, + def_id: DefId, + substs: &'tcx Substs<'tcx>) + -> ValueRef { get_fn(ccx, monomorphize::resolve(ccx.shared(), def_id, substs)) } diff --git a/src/librustc_trans/collector.rs b/src/librustc_trans/collector.rs index b31295f4022ed..11d5c9b48bc8c 100644 --- a/src/librustc_trans/collector.rs +++ b/src/librustc_trans/collector.rs @@ -212,14 +212,14 @@ use rustc_data_structures::bitvec::BitVector; use back::symbol_export::ExportedSymbols; #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)] -pub enum TransItemCollectionMode { +pub(crate) enum TransItemCollectionMode { Eager, Lazy } /// Maps every translation item to all translation items it references in its /// body. -pub struct InliningMap<'tcx> { +pub(crate) struct InliningMap<'tcx> { // Maps a source translation item to the range of translation items // accessed by it. // The two numbers in the tuple are the start (inclusive) and @@ -269,7 +269,7 @@ impl<'tcx> InliningMap<'tcx> { // Internally iterate over all items referenced by `source` which will be // made available for inlining. - pub fn with_inlining_candidates(&self, source: TransItem<'tcx>, mut f: F) + pub(crate) fn with_inlining_candidates(&self, source: TransItem<'tcx>, mut f: F) where F: FnMut(TransItem<'tcx>) { if let Some(&(start_index, end_index)) = self.index.get(&source) { @@ -293,11 +293,11 @@ impl<'tcx> InliningMap<'tcx> { } } -pub fn collect_crate_translation_items<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>, - exported_symbols: &ExportedSymbols, - mode: TransItemCollectionMode) - -> (FxHashSet>, - InliningMap<'tcx>) { +pub(crate) fn collect_crate_translation_items<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>, + exported_symbols: &ExportedSymbols, + mode: TransItemCollectionMode) + -> (FxHashSet>, + InliningMap<'tcx>) { // We are not tracking dependencies of this pass as it has to be re-executed // every time no matter what. scx.tcx().dep_graph.with_ignore(|| { diff --git a/src/librustc_trans/common.rs b/src/librustc_trans/common.rs index 9b0803908b162..0c074a1dcf4a7 100644 --- a/src/librustc_trans/common.rs +++ b/src/librustc_trans/common.rs @@ -38,9 +38,9 @@ use syntax::attr; use syntax::symbol::InternedString; use syntax_pos::Span; -pub use context::{CrateContext, SharedCrateContext}; +pub(crate) use context::{CrateContext, SharedCrateContext}; -pub fn type_is_fat_ptr<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool { +pub(crate) fn type_is_fat_ptr<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool { if let Layout::FatPointer { .. } = *ccx.layout_of(ty) { true } else { @@ -48,7 +48,7 @@ pub fn type_is_fat_ptr<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> } } -pub fn type_is_immediate<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool { +pub(crate) fn type_is_immediate<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool { let layout = ccx.layout_of(ty); match *layout { Layout::CEnum { .. } | @@ -69,7 +69,7 @@ pub fn type_is_immediate<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) - } /// Returns Some([a, b]) if the type has a pair of fields with types a and b. -pub fn type_pair_fields<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) +pub(crate) fn type_pair_fields<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> Option<[Ty<'tcx>; 2]> { match ty.sty { ty::TyAdt(adt, substs) => { @@ -102,7 +102,7 @@ pub fn type_pair_fields<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) } /// Returns true if the type is represented as a pair of immediates. -pub fn type_is_imm_pair<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) +pub(crate) fn type_is_imm_pair<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool { match *ccx.layout_of(ty) { Layout::FatPointer { .. } => true, @@ -124,7 +124,7 @@ pub fn type_is_imm_pair<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) } /// Identify types which have size zero at runtime. -pub fn type_is_zero_size<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool { +pub(crate) fn type_is_zero_size<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool { let layout = ccx.layout_of(ty); !layout.is_unsized() && layout.size(ccx).bytes() == 0 } @@ -169,87 +169,87 @@ pub fn type_is_zero_size<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) - /// When inside of a landing pad, each function call in LLVM IR needs to be /// annotated with which landing pad it's a part of. This is accomplished via /// the `OperandBundleDef` value created for MSVC landing pads. -pub struct Funclet { +pub(crate) struct Funclet { cleanuppad: ValueRef, operand: OperandBundleDef, } impl Funclet { - pub fn new(cleanuppad: ValueRef) -> Funclet { + pub(crate) fn new(cleanuppad: ValueRef) -> Funclet { Funclet { cleanuppad: cleanuppad, operand: OperandBundleDef::new("funclet", &[cleanuppad]), } } - pub fn cleanuppad(&self) -> ValueRef { + pub(crate) fn cleanuppad(&self) -> ValueRef { self.cleanuppad } - pub fn bundle(&self) -> &OperandBundleDef { + pub(crate) fn bundle(&self) -> &OperandBundleDef { &self.operand } } -pub fn val_ty(v: ValueRef) -> Type { +pub(crate) fn val_ty(v: ValueRef) -> Type { unsafe { Type::from_ref(llvm::LLVMTypeOf(v)) } } // LLVM constant constructors. -pub fn C_null(t: Type) -> ValueRef { +pub(crate) fn C_null(t: Type) -> ValueRef { unsafe { llvm::LLVMConstNull(t.to_ref()) } } -pub fn C_undef(t: Type) -> ValueRef { +pub(crate) fn C_undef(t: Type) -> ValueRef { unsafe { llvm::LLVMGetUndef(t.to_ref()) } } -pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef { +pub(crate) fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef { unsafe { llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool) } } -pub fn C_big_integral(t: Type, u: u128) -> ValueRef { +pub(crate) fn C_big_integral(t: Type, u: u128) -> ValueRef { unsafe { let words = [u as u64, u.wrapping_shr(64) as u64]; llvm::LLVMConstIntOfArbitraryPrecision(t.to_ref(), 2, words.as_ptr()) } } -pub fn C_floating_f64(f: f64, t: Type) -> ValueRef { +pub(crate) fn C_floating_f64(f: f64, t: Type) -> ValueRef { unsafe { llvm::LLVMConstReal(t.to_ref(), f) } } -pub fn C_nil(ccx: &CrateContext) -> ValueRef { +pub(crate) fn C_nil(ccx: &CrateContext) -> ValueRef { C_struct(ccx, &[], false) } -pub fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef { +pub(crate) fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef { C_integral(Type::i1(ccx), val as u64, false) } -pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef { +pub(crate) fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef { C_integral(Type::i32(ccx), i as u64, true) } -pub fn C_u32(ccx: &CrateContext, i: u32) -> ValueRef { +pub(crate) fn C_u32(ccx: &CrateContext, i: u32) -> ValueRef { C_integral(Type::i32(ccx), i as u64, false) } -pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef { +pub(crate) fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef { C_integral(Type::i64(ccx), i, false) } -pub fn C_uint(ccx: &CrateContext, i: I) -> ValueRef { +pub(crate) fn C_uint(ccx: &CrateContext, i: I) -> ValueRef { let v = i.as_u64(); let bit_size = machine::llbitsize_of_real(ccx, ccx.int_type()); @@ -262,8 +262,8 @@ pub fn C_uint(ccx: &CrateContext, i: I) -> ValueRef { C_integral(ccx.int_type(), v, false) } -pub trait AsI64 { fn as_i64(self) -> i64; } -pub trait AsU64 { fn as_u64(self) -> u64; } +pub(crate) trait AsI64 { fn as_i64(self) -> i64; } +pub(crate) trait AsU64 { fn as_u64(self) -> u64; } // FIXME: remove the intptr conversions, because they // are host-architecture-dependent @@ -275,14 +275,14 @@ impl AsU64 for u64 { fn as_u64(self) -> u64 { self as u64 }} impl AsU64 for u32 { fn as_u64(self) -> u64 { self as u64 }} impl AsU64 for usize { fn as_u64(self) -> u64 { self as u64 }} -pub fn C_u8(ccx: &CrateContext, i: u8) -> ValueRef { +pub(crate) fn C_u8(ccx: &CrateContext, i: u8) -> ValueRef { C_integral(Type::i8(ccx), i as u64, false) } // This is a 'c-like' raw string, which differs from // our boxed-and-length-annotated strings. -pub fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> ValueRef { +pub(crate) fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> ValueRef { unsafe { if let Some(&llval) = cx.const_cstr_cache().borrow().get(&s) { return llval; @@ -307,17 +307,17 @@ pub fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> Va // NB: Do not use `do_spill_noroot` to make this into a constant string, or // you will be kicked off fast isel. See issue #4352 for an example of this. -pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef { +pub(crate) fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef { let len = s.len(); let cs = consts::ptrcast(C_cstr(cx, s, false), Type::i8p(cx)); C_named_struct(cx.str_slice_type(), &[cs, C_uint(cx, len)]) } -pub fn C_struct(cx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef { +pub(crate) fn C_struct(cx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef { C_struct_in_context(cx.llcx(), elts, packed) } -pub fn C_struct_in_context(llcx: ContextRef, elts: &[ValueRef], packed: bool) -> ValueRef { +pub(crate) fn C_struct_in_context(llcx: ContextRef, elts: &[ValueRef], packed: bool) -> ValueRef { unsafe { llvm::LLVMConstStructInContext(llcx, elts.as_ptr(), elts.len() as c_uint, @@ -325,36 +325,36 @@ pub fn C_struct_in_context(llcx: ContextRef, elts: &[ValueRef], packed: bool) -> } } -pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef { +pub(crate) fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef { unsafe { llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint) } } -pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef { +pub(crate) fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef { unsafe { return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint); } } -pub fn C_vector(elts: &[ValueRef]) -> ValueRef { +pub(crate) fn C_vector(elts: &[ValueRef]) -> ValueRef { unsafe { return llvm::LLVMConstVector(elts.as_ptr(), elts.len() as c_uint); } } -pub fn C_bytes(cx: &CrateContext, bytes: &[u8]) -> ValueRef { +pub(crate) fn C_bytes(cx: &CrateContext, bytes: &[u8]) -> ValueRef { C_bytes_in_context(cx.llcx(), bytes) } -pub fn C_bytes_in_context(llcx: ContextRef, bytes: &[u8]) -> ValueRef { +pub(crate) fn C_bytes_in_context(llcx: ContextRef, bytes: &[u8]) -> ValueRef { unsafe { let ptr = bytes.as_ptr() as *const c_char; return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True); } } -pub fn const_get_elt(v: ValueRef, us: &[c_uint]) +pub(crate) fn const_get_elt(v: ValueRef, us: &[c_uint]) -> ValueRef { unsafe { let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint); @@ -366,7 +366,7 @@ pub fn const_get_elt(v: ValueRef, us: &[c_uint]) } } -pub fn const_to_uint(v: ValueRef) -> u64 { +pub(crate) fn const_to_uint(v: ValueRef) -> u64 { unsafe { llvm::LLVMConstIntGetZExtValue(v) } @@ -383,7 +383,7 @@ fn hi_lo_to_u128(lo: u64, hi: u64) -> u128 { ((hi as u128) << 64) | (lo as u128) } -pub fn const_to_opt_u128(v: ValueRef, sign_ext: bool) -> Option { +pub(crate) fn const_to_opt_u128(v: ValueRef, sign_ext: bool) -> Option { unsafe { if is_const_integral(v) { let (mut lo, mut hi) = (0u64, 0u64); @@ -400,24 +400,24 @@ pub fn const_to_opt_u128(v: ValueRef, sign_ext: bool) -> Option { } } -pub fn is_undef(val: ValueRef) -> bool { +pub(crate) fn is_undef(val: ValueRef) -> bool { unsafe { llvm::LLVMIsUndef(val) != False } } #[allow(dead_code)] // potentially useful -pub fn is_null(val: ValueRef) -> bool { +pub(crate) fn is_null(val: ValueRef) -> bool { unsafe { llvm::LLVMIsNull(val) != False } } -pub fn langcall(tcx: TyCtxt, - span: Option, - msg: &str, - li: LangItem) - -> DefId { +pub(crate) fn langcall(tcx: TyCtxt, + span: Option, + msg: &str, + li: LangItem) + -> DefId { match tcx.lang_items.require(li) { Ok(id) => id, Err(s) => { @@ -435,7 +435,7 @@ pub fn langcall(tcx: TyCtxt, // all shifts). For 32- and 64-bit types, this matches the semantics // of Java. (See related discussion on #1877 and #10183.) -pub fn build_unchecked_lshift<'a, 'tcx>( +pub(crate) fn build_unchecked_lshift<'a, 'tcx>( bcx: &Builder<'a, 'tcx>, lhs: ValueRef, rhs: ValueRef @@ -446,7 +446,7 @@ pub fn build_unchecked_lshift<'a, 'tcx>( bcx.shl(lhs, rhs) } -pub fn build_unchecked_rshift<'a, 'tcx>( +pub(crate) fn build_unchecked_rshift<'a, 'tcx>( bcx: &Builder<'a, 'tcx>, lhs_t: Ty<'tcx>, lhs: ValueRef, rhs: ValueRef ) -> ValueRef { let rhs = base::cast_shift_expr_rhs(bcx, hir::BinOp_::BiShr, lhs, rhs); @@ -465,7 +465,7 @@ fn shift_mask_rhs<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, rhs: ValueRef) -> ValueRef bcx.and(rhs, shift_mask_val(bcx, rhs_llty, rhs_llty, false)) } -pub fn shift_mask_val<'a, 'tcx>( +pub(crate) fn shift_mask_val<'a, 'tcx>( bcx: &Builder<'a, 'tcx>, llty: Type, mask_llty: Type, @@ -490,9 +490,9 @@ pub fn shift_mask_val<'a, 'tcx>( } } -pub fn ty_fn_sig<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, - ty: Ty<'tcx>) - -> ty::PolyFnSig<'tcx> +pub(crate) fn ty_fn_sig<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, + ty: Ty<'tcx>) + -> ty::PolyFnSig<'tcx> { match ty.sty { ty::TyFnDef(..) | @@ -521,7 +521,7 @@ pub fn ty_fn_sig<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, } } -pub fn requests_inline<'a, 'tcx>( +pub(crate) fn requests_inline<'a, 'tcx>( tcx: TyCtxt<'a, 'tcx, 'tcx>, instance: &ty::Instance<'tcx> ) -> bool { @@ -537,7 +537,7 @@ pub fn requests_inline<'a, 'tcx>( attr::requests_inline(&instance.def.attrs(tcx)[..]) } -pub fn is_inline_instance<'a, 'tcx>( +pub(crate) fn is_inline_instance<'a, 'tcx>( tcx: TyCtxt<'a, 'tcx, 'tcx>, instance: &ty::Instance<'tcx> ) -> bool { @@ -555,19 +555,19 @@ pub fn is_inline_instance<'a, 'tcx>( } /// Given a DefId and some Substs, produces the monomorphic item type. -pub fn def_ty<'a, 'tcx>(shared: &SharedCrateContext<'a, 'tcx>, - def_id: DefId, - substs: &'tcx Substs<'tcx>) - -> Ty<'tcx> +pub(crate) fn def_ty<'a, 'tcx>(shared: &SharedCrateContext<'a, 'tcx>, + def_id: DefId, + substs: &'tcx Substs<'tcx>) + -> Ty<'tcx> { let ty = shared.tcx().type_of(def_id); shared.tcx().trans_apply_param_substs(substs, &ty) } /// Return the substituted type of an instance. -pub fn instance_ty<'a, 'tcx>(shared: &SharedCrateContext<'a, 'tcx>, - instance: &ty::Instance<'tcx>) - -> Ty<'tcx> +pub(crate) fn instance_ty<'a, 'tcx>(shared: &SharedCrateContext<'a, 'tcx>, + instance: &ty::Instance<'tcx>) + -> Ty<'tcx> { let ty = instance.def.def_ty(shared.tcx()); shared.tcx().trans_apply_param_substs(instance.substs, &ty) diff --git a/src/librustc_trans/consts.rs b/src/librustc_trans/consts.rs index da2a58398634e..bfb7809176db2 100644 --- a/src/librustc_trans/consts.rs +++ b/src/librustc_trans/consts.rs @@ -30,17 +30,17 @@ use std::ffi::{CStr, CString}; use syntax::ast; use syntax::attr; -pub fn ptrcast(val: ValueRef, ty: Type) -> ValueRef { +pub(crate) fn ptrcast(val: ValueRef, ty: Type) -> ValueRef { unsafe { llvm::LLVMConstPointerCast(val, ty.to_ref()) } } -pub fn addr_of_mut(ccx: &CrateContext, - cv: ValueRef, - align: machine::llalign, - kind: &str) - -> ValueRef { +pub(crate) fn addr_of_mut(ccx: &CrateContext, + cv: ValueRef, + align: machine::llalign, + kind: &str) + -> ValueRef { unsafe { let name = ccx.generate_local_symbol_name(kind); let gv = declare::define_global(ccx, &name[..], val_ty(cv)).unwrap_or_else(||{ @@ -54,11 +54,11 @@ pub fn addr_of_mut(ccx: &CrateContext, } } -pub fn addr_of(ccx: &CrateContext, - cv: ValueRef, - align: machine::llalign, - kind: &str) - -> ValueRef { +pub(crate) fn addr_of(ccx: &CrateContext, + cv: ValueRef, + align: machine::llalign, + kind: &str) + -> ValueRef { if let Some(&gv) = ccx.const_globals().borrow().get(&cv) { unsafe { // Upgrade the alignment in cases where the same constant is used with different @@ -77,7 +77,7 @@ pub fn addr_of(ccx: &CrateContext, gv } -pub fn get_static(ccx: &CrateContext, def_id: DefId) -> ValueRef { +pub(crate) fn get_static(ccx: &CrateContext, def_id: DefId) -> ValueRef { let instance = Instance::mono(ccx.tcx(), def_id); if let Some(&g) = ccx.instances().borrow().get(&instance) { return g; @@ -216,11 +216,11 @@ pub fn get_static(ccx: &CrateContext, def_id: DefId) -> ValueRef { g } -pub fn trans_static<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, - m: hir::Mutability, - id: ast::NodeId, - attrs: &[ast::Attribute]) - -> Result> { +pub(crate) fn trans_static<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, + m: hir::Mutability, + id: ast::NodeId, + attrs: &[ast::Attribute]) + -> Result> { unsafe { let def_id = ccx.tcx().hir.local_def_id(id); let g = get_static(ccx, def_id); diff --git a/src/librustc_trans/context.rs b/src/librustc_trans/context.rs index bec39e3cde6d0..057da3b2ab5e5 100644 --- a/src/librustc_trans/context.rs +++ b/src/librustc_trans/context.rs @@ -27,10 +27,9 @@ use type_::Type; use rustc_data_structures::base_n; use rustc::session::config::{self, NoDebugInfo, OutputFilenames}; use rustc::session::Session; -use rustc::ty::subst::Substs; use rustc::ty::{self, Ty, TyCtxt}; use rustc::ty::layout::{LayoutCx, LayoutError, LayoutTyper, TyLayout}; -use rustc::util::nodemap::{DefIdMap, FxHashMap, FxHashSet}; +use rustc::util::nodemap::{FxHashMap, FxHashSet}; use std::ffi::{CStr, CString}; use std::cell::{Cell, RefCell}; @@ -39,27 +38,26 @@ use std::iter; use std::str; use std::sync::Arc; use std::marker::PhantomData; -use syntax::ast; use syntax::symbol::InternedString; use syntax_pos::DUMMY_SP; use abi::Abi; #[derive(Clone, Default)] -pub struct Stats { - pub n_glues_created: Cell, - pub n_null_glues: Cell, - pub n_real_glues: Cell, - pub n_fns: Cell, - pub n_inlines: Cell, - pub n_closures: Cell, - pub n_llvm_insns: Cell, - pub llvm_insns: RefCell>, +pub(crate) struct Stats { + pub(crate) n_glues_created: Cell, + pub(crate) n_null_glues: Cell, + pub(crate) n_real_glues: Cell, + pub(crate) n_fns: Cell, + pub(crate) n_inlines: Cell, + pub(crate) n_closures: Cell, + pub(crate) n_llvm_insns: Cell, + pub(crate) llvm_insns: RefCell>, // (ident, llvm-instructions) - pub fn_stats: RefCell >, + pub(crate) fn_stats: RefCell >, } impl Stats { - pub fn extend(&mut self, stats: Stats) { + pub(crate) fn extend(&mut self, stats: Stats) { self.n_glues_created.set(self.n_glues_created.get() + stats.n_glues_created.get()); self.n_null_glues.set(self.n_null_glues.get() + stats.n_null_glues.get()); self.n_real_glues.set(self.n_real_glues.get() + stats.n_real_glues.get()); @@ -78,7 +76,7 @@ impl Stats { /// per crate. The data here is shared between all compilation units of the /// crate, so it must not contain references to any LLVM data structures /// (aside from metadata-related ones). -pub struct SharedCrateContext<'a, 'tcx: 'a> { +pub(crate) struct SharedCrateContext<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx>, check_overflow: bool, @@ -91,7 +89,7 @@ pub struct SharedCrateContext<'a, 'tcx: 'a> { /// per compilation unit. Each one has its own LLVM `ContextRef` so that /// several compilation units may be optimized in parallel. All other LLVM /// data structures in the `LocalCrateContext` are tied to that `ContextRef`. -pub struct LocalCrateContext<'a, 'tcx: 'a> { +pub(crate) struct LocalCrateContext<'a, 'tcx: 'a> { llmod: ModuleRef, llcx: ContextRef, stats: Stats, @@ -124,12 +122,6 @@ pub struct LocalCrateContext<'a, 'tcx: 'a> { /// Cache of emitted const globals (value -> global) const_globals: RefCell>, - /// Cache of emitted const values - const_values: RefCell), ValueRef>>, - - /// Cache of external const values - extern_const_values: RefCell>, - /// Mapping from static definitions to their DefId's. statics: RefCell>, @@ -144,7 +136,6 @@ pub struct LocalCrateContext<'a, 'tcx: 'a> { used_statics: RefCell>, lltypes: RefCell, Type>>, - type_hashcodes: RefCell, String>>, int_type: Type, opaque_vec_type: Type, str_slice_type: Type, @@ -157,9 +148,6 @@ pub struct LocalCrateContext<'a, 'tcx: 'a> { intrinsics: RefCell>, - /// Depth of the current type-of computation - used to bail out - type_of_depth: Cell, - /// A counter that is used for generating local symbol names local_gen_sym_counter: Cell, @@ -170,15 +158,15 @@ pub struct LocalCrateContext<'a, 'tcx: 'a> { /// A CrateContext value binds together one LocalCrateContext with the /// SharedCrateContext. It exists as a convenience wrapper, so we don't have to /// pass around (SharedCrateContext, LocalCrateContext) tuples all over trans. -pub struct CrateContext<'a, 'tcx: 'a> { +pub(crate) struct CrateContext<'a, 'tcx: 'a> { shared: &'a SharedCrateContext<'a, 'tcx>, local_ccx: &'a LocalCrateContext<'a, 'tcx>, } impl<'a, 'tcx> CrateContext<'a, 'tcx> { - pub fn new(shared: &'a SharedCrateContext<'a, 'tcx>, - local_ccx: &'a LocalCrateContext<'a, 'tcx>) - -> Self { + pub(crate) fn new(shared: &'a SharedCrateContext<'a, 'tcx>, + local_ccx: &'a LocalCrateContext<'a, 'tcx>) + -> Self { CrateContext { shared, local_ccx } } } @@ -186,7 +174,7 @@ impl<'a, 'tcx> CrateContext<'a, 'tcx> { impl<'a, 'tcx> DepGraphSafe for CrateContext<'a, 'tcx> { } -pub fn get_reloc_model(sess: &Session) -> llvm::RelocMode { +pub(crate) fn get_reloc_model(sess: &Session) -> llvm::RelocMode { let reloc_model_arg = match sess.opts.cg.relocation_model { Some(ref s) => &s[..], None => &sess.target.target.options.relocation_model[..], @@ -212,11 +200,12 @@ fn is_any_library(sess: &Session) -> bool { }) } -pub fn is_pie_binary(sess: &Session) -> bool { +pub(crate) fn is_pie_binary(sess: &Session) -> bool { !is_any_library(sess) && get_reloc_model(sess) == llvm::RelocMode::PIC } -pub unsafe fn create_context_and_module(sess: &Session, mod_name: &str) -> (ContextRef, ModuleRef) { +pub(crate) unsafe fn create_context_and_module(sess: &Session, mod_name: &str) + -> (ContextRef, ModuleRef) { let llcx = llvm::LLVMContextCreate(); let mod_name = CString::new(mod_name).unwrap(); let llmod = llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx); @@ -273,10 +262,10 @@ pub unsafe fn create_context_and_module(sess: &Session, mod_name: &str) -> (Cont } impl<'b, 'tcx> SharedCrateContext<'b, 'tcx> { - pub fn new(tcx: TyCtxt<'b, 'tcx, 'tcx>, - check_overflow: bool, - output_filenames: &'b OutputFilenames) - -> SharedCrateContext<'b, 'tcx> { + pub(crate) fn new(tcx: TyCtxt<'b, 'tcx, 'tcx>, + check_overflow: bool, + output_filenames: &'b OutputFilenames) + -> SharedCrateContext<'b, 'tcx> { // An interesting part of Windows which MSVC forces our hand on (and // apparently MinGW didn't) is the usage of `dllimport` and `dllexport` // attributes in LLVM IR as well as native dependencies (in C these @@ -330,45 +319,45 @@ impl<'b, 'tcx> SharedCrateContext<'b, 'tcx> { } } - pub fn type_needs_drop(&self, ty: Ty<'tcx>) -> bool { + pub(crate) fn type_needs_drop(&self, ty: Ty<'tcx>) -> bool { ty.needs_drop(self.tcx, ty::ParamEnv::empty(traits::Reveal::All)) } - pub fn type_is_sized(&self, ty: Ty<'tcx>) -> bool { + pub(crate) fn type_is_sized(&self, ty: Ty<'tcx>) -> bool { ty.is_sized(self.tcx, ty::ParamEnv::empty(traits::Reveal::All), DUMMY_SP) } - pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool { + pub(crate) fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool { ty.is_freeze(self.tcx, ty::ParamEnv::empty(traits::Reveal::All), DUMMY_SP) } - pub fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> { + pub(crate) fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> { self.tcx } - pub fn sess<'a>(&'a self) -> &'a Session { + pub(crate) fn sess<'a>(&'a self) -> &'a Session { &self.tcx.sess } - pub fn dep_graph<'a>(&'a self) -> &'a DepGraph { + pub(crate) fn dep_graph<'a>(&'a self) -> &'a DepGraph { &self.tcx.dep_graph } - pub fn use_dll_storage_attrs(&self) -> bool { + pub(crate) fn use_dll_storage_attrs(&self) -> bool { self.use_dll_storage_attrs } - pub fn output_filenames(&self) -> &OutputFilenames { + pub(crate) fn output_filenames(&self) -> &OutputFilenames { self.output_filenames } } impl<'a, 'tcx> LocalCrateContext<'a, 'tcx> { - pub fn new(shared: &SharedCrateContext<'a, 'tcx>, - codegen_unit: CodegenUnit<'tcx>, - crate_trans_items: Arc>>, - exported_symbols: Arc,) - -> LocalCrateContext<'a, 'tcx> { + pub(crate) fn new(shared: &SharedCrateContext<'a, 'tcx>, + codegen_unit: CodegenUnit<'tcx>, + crate_trans_items: Arc>>, + exported_symbols: Arc,) + -> LocalCrateContext<'a, 'tcx> { unsafe { // Append ".rs" to LLVM module identifier. // @@ -406,13 +395,10 @@ impl<'a, 'tcx> LocalCrateContext<'a, 'tcx> { const_cstr_cache: RefCell::new(FxHashMap()), const_unsized: RefCell::new(FxHashMap()), const_globals: RefCell::new(FxHashMap()), - const_values: RefCell::new(FxHashMap()), - extern_const_values: RefCell::new(DefIdMap()), statics: RefCell::new(FxHashMap()), statics_to_rauw: RefCell::new(Vec::new()), used_statics: RefCell::new(Vec::new()), lltypes: RefCell::new(FxHashMap()), - type_hashcodes: RefCell::new(FxHashMap()), int_type: Type::from_ref(ptr::null_mut()), opaque_vec_type: Type::from_ref(ptr::null_mut()), str_slice_type: Type::from_ref(ptr::null_mut()), @@ -421,7 +407,6 @@ impl<'a, 'tcx> LocalCrateContext<'a, 'tcx> { eh_unwind_resume: Cell::new(None), rust_try_fn: Cell::new(None), intrinsics: RefCell::new(FxHashMap()), - type_of_depth: Cell::new(0), local_gen_sym_counter: Cell::new(0), placeholder: PhantomData, }; @@ -467,13 +452,13 @@ impl<'a, 'tcx> LocalCrateContext<'a, 'tcx> { } } - pub fn into_stats(self) -> Stats { + pub(crate) fn into_stats(self) -> Stats { self.stats } } impl<'b, 'tcx> CrateContext<'b, 'tcx> { - pub fn shared(&self) -> &'b SharedCrateContext<'b, 'tcx> { + pub(crate) fn shared(&self) -> &'b SharedCrateContext<'b, 'tcx> { self.shared } @@ -481,15 +466,15 @@ impl<'b, 'tcx> CrateContext<'b, 'tcx> { self.local_ccx } - pub fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> { + pub(crate) fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> { self.shared.tcx } - pub fn sess<'a>(&'a self) -> &'a Session { + pub(crate) fn sess<'a>(&'a self) -> &'a Session { &self.shared.tcx.sess } - pub fn get_intrinsic(&self, key: &str) -> ValueRef { + pub(crate) fn get_intrinsic(&self, key: &str) -> ValueRef { if let Some(v) = self.intrinsics().borrow().get(key).cloned() { return v; } @@ -499,102 +484,86 @@ impl<'b, 'tcx> CrateContext<'b, 'tcx> { } } - pub fn llmod(&self) -> ModuleRef { + pub(crate) fn llmod(&self) -> ModuleRef { self.local().llmod } - pub fn llcx(&self) -> ContextRef { + pub(crate) fn llcx(&self) -> ContextRef { self.local().llcx } - pub fn codegen_unit(&self) -> &CodegenUnit<'tcx> { + pub(crate) fn codegen_unit(&self) -> &CodegenUnit<'tcx> { &self.local().codegen_unit } - pub fn crate_trans_items(&self) -> &FxHashSet> { + pub(crate) fn crate_trans_items(&self) -> &FxHashSet> { &self.local().crate_trans_items } - pub fn exported_symbols(&self) -> &ExportedSymbols { + pub(crate) fn exported_symbols(&self) -> &ExportedSymbols { &self.local().exported_symbols } - pub fn td(&self) -> llvm::TargetDataRef { + pub(crate) fn td(&self) -> llvm::TargetDataRef { unsafe { llvm::LLVMRustGetModuleDataLayout(self.llmod()) } } - pub fn instances<'a>(&'a self) -> &'a RefCell, ValueRef>> { + pub(crate) fn instances<'a>(&'a self) -> &'a RefCell, ValueRef>> { &self.local().instances } - pub fn vtables<'a>(&'a self) + pub(crate) fn vtables<'a>(&'a self) -> &'a RefCell, Option>), ValueRef>> { &self.local().vtables } - pub fn const_cstr_cache<'a>(&'a self) -> &'a RefCell> { + pub(crate) fn const_cstr_cache<'a>(&'a self) + -> &'a RefCell> { &self.local().const_cstr_cache } - pub fn const_unsized<'a>(&'a self) -> &'a RefCell> { + pub(crate) fn const_unsized<'a>(&'a self) -> &'a RefCell> { &self.local().const_unsized } - pub fn const_globals<'a>(&'a self) -> &'a RefCell> { + pub(crate) fn const_globals<'a>(&'a self) -> &'a RefCell> { &self.local().const_globals } - pub fn const_values<'a>(&'a self) -> &'a RefCell), - ValueRef>> { - &self.local().const_values - } - - pub fn extern_const_values<'a>(&'a self) -> &'a RefCell> { - &self.local().extern_const_values - } - - pub fn statics<'a>(&'a self) -> &'a RefCell> { + pub(crate) fn statics<'a>(&'a self) -> &'a RefCell> { &self.local().statics } - pub fn statics_to_rauw<'a>(&'a self) -> &'a RefCell> { + pub(crate) fn statics_to_rauw<'a>(&'a self) -> &'a RefCell> { &self.local().statics_to_rauw } - pub fn used_statics<'a>(&'a self) -> &'a RefCell> { + pub(crate) fn used_statics<'a>(&'a self) -> &'a RefCell> { &self.local().used_statics } - pub fn lltypes<'a>(&'a self) -> &'a RefCell, Type>> { + pub(crate) fn lltypes<'a>(&'a self) -> &'a RefCell, Type>> { &self.local().lltypes } - pub fn type_hashcodes<'a>(&'a self) -> &'a RefCell, String>> { - &self.local().type_hashcodes - } - - pub fn stats<'a>(&'a self) -> &'a Stats { + pub(crate) fn stats<'a>(&'a self) -> &'a Stats { &self.local().stats } - pub fn int_type(&self) -> Type { + pub(crate) fn int_type(&self) -> Type { self.local().int_type } - pub fn opaque_vec_type(&self) -> Type { - self.local().opaque_vec_type - } - - pub fn str_slice_type(&self) -> Type { + pub(crate) fn str_slice_type(&self) -> Type { self.local().str_slice_type } - pub fn dbg_cx<'a>(&'a self) -> &'a Option> { + pub(crate) fn dbg_cx<'a>(&'a self) -> &'a Option> { &self.local().dbg_cx } - pub fn rust_try_fn<'a>(&'a self) -> &'a Cell> { + pub(crate) fn rust_try_fn<'a>(&'a self) -> &'a Cell> { &self.local().rust_try_fn } @@ -602,44 +571,17 @@ impl<'b, 'tcx> CrateContext<'b, 'tcx> { &self.local().intrinsics } - pub fn obj_size_bound(&self) -> u64 { - self.tcx().data_layout.obj_size_bound() - } - - pub fn report_overbig_object(&self, obj: Ty<'tcx>) -> ! { - self.sess().fatal( - &format!("the type `{:?}` is too big for the current architecture", - obj)) - } - - pub fn enter_type_of(&self, ty: Ty<'tcx>) -> TypeOfDepthLock<'b, 'tcx> { - let current_depth = self.local().type_of_depth.get(); - debug!("enter_type_of({:?}) at depth {:?}", ty, current_depth); - if current_depth > self.sess().recursion_limit.get() { - self.sess().fatal( - &format!("overflow representing the type `{}`", ty)) - } - self.local().type_of_depth.set(current_depth + 1); - TypeOfDepthLock(self.local()) - } - - pub fn check_overflow(&self) -> bool { + pub(crate) fn check_overflow(&self) -> bool { self.shared.check_overflow } - pub fn use_dll_storage_attrs(&self) -> bool { + pub(crate) fn use_dll_storage_attrs(&self) -> bool { self.shared.use_dll_storage_attrs() } - /// Given the def-id of some item that has no type parameters, make - /// a suitable "empty substs" for it. - pub fn empty_substs_for_def_id(&self, item_def_id: DefId) -> &'tcx Substs<'tcx> { - self.tcx().empty_substs_for_def_id(item_def_id) - } - /// Generate a new symbol name with the given prefix. This symbol name must /// only be used for definitions with `internal` or `private` linkage. - pub fn generate_local_symbol_name(&self, prefix: &str) -> String { + pub(crate) fn generate_local_symbol_name(&self, prefix: &str) -> String { let idx = self.local().local_gen_sym_counter.get(); self.local().local_gen_sym_counter.set(idx + 1); // Include a '.' character, so there can be no accidental conflicts with @@ -651,7 +593,7 @@ impl<'b, 'tcx> CrateContext<'b, 'tcx> { name } - pub fn eh_personality(&self) -> ValueRef { + pub(crate) fn eh_personality(&self) -> ValueRef { // The exception handling personality function. // // If our compilation unit has the `eh_personality` lang item somewhere @@ -696,7 +638,7 @@ impl<'b, 'tcx> CrateContext<'b, 'tcx> { // Returns a ValueRef of the "eh_unwind_resume" lang item if one is defined, // otherwise declares it as an external function. - pub fn eh_unwind_resume(&self) -> ValueRef { + pub(crate) fn eh_unwind_resume(&self) -> ValueRef { use attributes; let unwresume = &self.local().eh_unwind_resume; if let Some(llfn) = unwresume.get() { @@ -776,14 +718,6 @@ impl<'a, 'tcx> LayoutTyper<'tcx> for &'a CrateContext<'a, 'tcx> { } } -pub struct TypeOfDepthLock<'a, 'tcx: 'a>(&'a LocalCrateContext<'a, 'tcx>); - -impl<'a, 'tcx> Drop for TypeOfDepthLock<'a, 'tcx> { - fn drop(&mut self) { - self.0.type_of_depth.set(self.0.type_of_depth.get() - 1); - } -} - /// Declare any llvm intrinsics that you might need fn declare_intrinsic(ccx: &CrateContext, key: &str) -> Option { macro_rules! ifn { diff --git a/src/librustc_trans/debuginfo/create_scope_map.rs b/src/librustc_trans/debuginfo/create_scope_map.rs index ae618c7e170df..35a04fcadff1a 100644 --- a/src/librustc_trans/debuginfo/create_scope_map.rs +++ b/src/librustc_trans/debuginfo/create_scope_map.rs @@ -28,23 +28,23 @@ use rustc_data_structures::indexed_vec::{Idx, IndexVec}; use syntax_pos::BytePos; #[derive(Clone, Copy, Debug)] -pub struct MirDebugScope { - pub scope_metadata: DIScope, +pub(crate) struct MirDebugScope { + pub(crate) scope_metadata: DIScope, // Start and end offsets of the file to which this DIScope belongs. // These are used to quickly determine whether some span refers to the same file. - pub file_start_pos: BytePos, - pub file_end_pos: BytePos, + pub(crate) file_start_pos: BytePos, + pub(crate) file_end_pos: BytePos, } impl MirDebugScope { - pub fn is_valid(&self) -> bool { + pub(crate) fn is_valid(&self) -> bool { !self.scope_metadata.is_null() } } /// Produce DIScope DIEs for each MIR Scope which has variables defined in it. /// If debuginfo is disabled, the returned vector is empty. -pub fn create_mir_scopes(ccx: &CrateContext, mir: &Mir, debug_context: &FunctionDebugContext) +pub(crate) fn create_mir_scopes(ccx: &CrateContext, mir: &Mir, debug_context: &FunctionDebugContext) -> IndexVec { let null_scope = MirDebugScope { scope_metadata: ptr::null_mut(), diff --git a/src/librustc_trans/debuginfo/gdb.rs b/src/librustc_trans/debuginfo/gdb.rs index 14d3fa4955307..913fc41299182 100644 --- a/src/librustc_trans/debuginfo/gdb.rs +++ b/src/librustc_trans/debuginfo/gdb.rs @@ -24,7 +24,8 @@ use syntax::attr; /// Inserts a side-effect free instruction sequence that makes sure that the /// .debug_gdb_scripts global is referenced, so it isn't removed by the linker. -pub fn insert_reference_to_gdb_debug_scripts_section_global(ccx: &CrateContext, builder: &Builder) { +pub(crate) fn insert_reference_to_gdb_debug_scripts_section_global(ccx: &CrateContext, + builder: &Builder) { if needs_gdb_debug_scripts_section(ccx) { let gdb_debug_scripts_section_global = get_or_insert_gdb_debug_scripts_section_global(ccx); // Load just the first byte as that's all that's necessary to force @@ -40,7 +41,7 @@ pub fn insert_reference_to_gdb_debug_scripts_section_global(ccx: &CrateContext, /// Allocates the global variable responsible for the .debug_gdb_scripts binary /// section. -pub fn get_or_insert_gdb_debug_scripts_section_global(ccx: &CrateContext) +pub(crate) fn get_or_insert_gdb_debug_scripts_section_global(ccx: &CrateContext) -> llvm::ValueRef { let c_section_var_name = "__rustc_debug_gdb_scripts_section__\0"; let section_var_name = &c_section_var_name[..c_section_var_name.len()-1]; @@ -77,7 +78,7 @@ pub fn get_or_insert_gdb_debug_scripts_section_global(ccx: &CrateContext) } } -pub fn needs_gdb_debug_scripts_section(ccx: &CrateContext) -> bool { +pub(crate) fn needs_gdb_debug_scripts_section(ccx: &CrateContext) -> bool { let omit_gdb_pretty_printer_section = attr::contains_name(&ccx.tcx().hir.krate_attrs(), "omit_gdb_pretty_printer_section"); diff --git a/src/librustc_trans/debuginfo/metadata.rs b/src/librustc_trans/debuginfo/metadata.rs index 61204b88e130e..41c5e61362c65 100644 --- a/src/librustc_trans/debuginfo/metadata.rs +++ b/src/librustc_trans/debuginfo/metadata.rs @@ -63,20 +63,20 @@ const DW_ATE_unsigned: c_uint = 0x07; #[allow(non_upper_case_globals)] const DW_ATE_unsigned_char: c_uint = 0x08; -pub const UNKNOWN_LINE_NUMBER: c_uint = 0; -pub const UNKNOWN_COLUMN_NUMBER: c_uint = 0; +pub(crate) const UNKNOWN_LINE_NUMBER: c_uint = 0; +pub(crate) const UNKNOWN_COLUMN_NUMBER: c_uint = 0; // ptr::null() doesn't work :( -pub const NO_SCOPE_METADATA: DIScope = (0 as DIScope); +pub(crate) const NO_SCOPE_METADATA: DIScope = (0 as DIScope); #[derive(Copy, Debug, Hash, Eq, PartialEq, Clone)] -pub struct UniqueTypeId(ast::Name); +pub(crate) struct UniqueTypeId(ast::Name); // The TypeMap is where the CrateDebugContext holds the type metadata nodes // created so far. The metadata nodes are indexed by UniqueTypeId, and, for // faster lookup, also by Ty. The TypeMap is responsible for creating // UniqueTypeIds. -pub struct TypeMap<'tcx> { +pub(crate) struct TypeMap<'tcx> { // The UniqueTypeIds created so far unique_id_interner: Interner, // A map from UniqueTypeId to debuginfo metadata for that type. This is a 1:1 mapping. @@ -88,7 +88,7 @@ pub struct TypeMap<'tcx> { } impl<'tcx> TypeMap<'tcx> { - pub fn new() -> TypeMap<'tcx> { + pub(crate) fn new() -> TypeMap<'tcx> { TypeMap { unique_id_interner: Interner::new(), type_to_metadata: FxHashMap(), @@ -449,10 +449,10 @@ fn trait_pointer_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, syntax_pos::DUMMY_SP) } -pub fn type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, - t: Ty<'tcx>, - usage_site_span: Span) - -> DIType { +pub(crate) fn type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, + t: Ty<'tcx>, + usage_site_span: Span) + -> DIType { // Get the unique type id of this type. let unique_type_id = { let mut type_map = debug_context(cx).type_map.borrow_mut(); @@ -656,9 +656,9 @@ pub fn type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, metadata } -pub fn file_metadata(cx: &CrateContext, - file_name: &str, - defining_crate: CrateNum) -> DIFile { +pub(crate) fn file_metadata(cx: &CrateContext, + file_name: &str, + defining_crate: CrateNum) -> DIFile { debug!("file_metadata: file_name: {}, defining_crate: {}", file_name, defining_crate); @@ -674,7 +674,7 @@ pub fn file_metadata(cx: &CrateContext, file_metadata_raw(cx, file_name, directory) } -pub fn unknown_file_metadata(cx: &CrateContext) -> DIFile { +pub(crate) fn unknown_file_metadata(cx: &CrateContext) -> DIFile { file_metadata_raw(cx, "", "") } @@ -761,11 +761,11 @@ fn pointer_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, return ptr_metadata; } -pub fn compile_unit_metadata(scc: &SharedCrateContext, - codegen_unit_name: &str, - debug_context: &CrateDebugContext, - sess: &Session) - -> DIDescriptor { +pub(crate) fn compile_unit_metadata(scc: &SharedCrateContext, + codegen_unit_name: &str, + debug_context: &CrateDebugContext, + sess: &Session) + -> DIDescriptor { let mut name_in_debuginfo = match sess.local_crate_source_file { Some(ref path) => path.clone(), None => scc.tcx().crate_name(LOCAL_CRATE).to_string(), @@ -1771,9 +1771,9 @@ fn create_union_stub(cx: &CrateContext, /// Creates debug information for the given global variable. /// /// Adds the created metadata nodes directly to the crate's IR. -pub fn create_global_var_metadata(cx: &CrateContext, - node_id: ast::NodeId, - global: ValueRef) { +pub(crate) fn create_global_var_metadata(cx: &CrateContext, + node_id: ast::NodeId, + global: ValueRef) { if cx.dbg_cx().is_none() { return; } @@ -1819,11 +1819,11 @@ pub fn create_global_var_metadata(cx: &CrateContext, } // Creates an "extension" of an existing DIScope into another file. -pub fn extend_scope_to_file(ccx: &CrateContext, - scope_metadata: DIScope, - file: &syntax_pos::FileMap, - defining_crate: CrateNum) - -> DILexicalBlock { +pub(crate) fn extend_scope_to_file(ccx: &CrateContext, + scope_metadata: DIScope, + file: &syntax_pos::FileMap, + defining_crate: CrateNum) + -> DILexicalBlock { let file_metadata = file_metadata(ccx, &file.name, defining_crate); unsafe { llvm::LLVMRustDIBuilderCreateLexicalBlockFile( diff --git a/src/librustc_trans/debuginfo/mod.rs b/src/librustc_trans/debuginfo/mod.rs index 68432c22f810c..761b1bc6fd355 100644 --- a/src/librustc_trans/debuginfo/mod.rs +++ b/src/librustc_trans/debuginfo/mod.rs @@ -45,19 +45,19 @@ use syntax::ast; use syntax::symbol::Symbol; use rustc::ty::layout::{self, LayoutTyper}; -pub mod gdb; +pub(crate) mod gdb; mod utils; mod namespace; mod type_names; -pub mod metadata; +pub(crate) mod metadata; mod create_scope_map; mod source_loc; -pub use self::create_scope_map::{create_mir_scopes, MirDebugScope}; -pub use self::source_loc::start_emitting_source_locations; -pub use self::metadata::create_global_var_metadata; -pub use self::metadata::extend_scope_to_file; -pub use self::source_loc::set_source_location; +pub(crate) use self::create_scope_map::{create_mir_scopes, MirDebugScope}; +pub(crate) use self::source_loc::start_emitting_source_locations; +pub(crate) use self::metadata::create_global_var_metadata; +pub(crate) use self::metadata::extend_scope_to_file; +pub(crate) use self::source_loc::set_source_location; #[allow(non_upper_case_globals)] const DW_TAG_auto_variable: c_uint = 0x100; @@ -65,7 +65,7 @@ const DW_TAG_auto_variable: c_uint = 0x100; const DW_TAG_arg_variable: c_uint = 0x101; /// A context object for maintaining all state needed by the debuginfo module. -pub struct CrateDebugContext<'tcx> { +pub(crate) struct CrateDebugContext<'tcx> { llcontext: ContextRef, llmod: ModuleRef, builder: DIBuilderRef, @@ -81,7 +81,7 @@ pub struct CrateDebugContext<'tcx> { } impl<'tcx> CrateDebugContext<'tcx> { - pub fn new(llmod: ModuleRef) -> CrateDebugContext<'tcx> { + pub(crate) fn new(llmod: ModuleRef) -> CrateDebugContext<'tcx> { debug!("CrateDebugContext::new"); let builder = unsafe { llvm::LLVMRustDIBuilderCreate(llmod) }; // DIBuilder inherits context from the module, so we'd better use the same one @@ -99,14 +99,14 @@ impl<'tcx> CrateDebugContext<'tcx> { } } -pub enum FunctionDebugContext { +pub(crate) enum FunctionDebugContext { RegularContext(FunctionDebugContextData), DebugInfoDisabled, FunctionWithoutDebugInfo, } impl FunctionDebugContext { - pub fn get_ref<'a>(&'a self, span: Span) -> &'a FunctionDebugContextData { + pub(crate) fn get_ref<'a>(&'a self, span: Span) -> &'a FunctionDebugContextData { match *self { FunctionDebugContext::RegularContext(ref data) => data, FunctionDebugContext::DebugInfoDisabled => { @@ -128,13 +128,13 @@ impl FunctionDebugContext { } } -pub struct FunctionDebugContextData { +pub(crate) struct FunctionDebugContextData { fn_metadata: DISubprogram, source_locations_enabled: Cell, - pub defining_crate: CrateNum, + pub(crate) defining_crate: CrateNum, } -pub enum VariableAccess<'a> { +pub(crate) enum VariableAccess<'a> { // The llptr given is an alloca containing the variable's value DirectVariable { alloca: ValueRef }, // The llptr given is an alloca containing the start of some pointer chain @@ -142,14 +142,14 @@ pub enum VariableAccess<'a> { IndirectVariable { alloca: ValueRef, address_operations: &'a [i64] } } -pub enum VariableKind { +pub(crate) enum VariableKind { ArgumentVariable(usize /*index*/), LocalVariable, CapturedVariable, } /// Create any deferred debug metadata nodes -pub fn finalize(cx: &CrateContext) { +pub(crate) fn finalize(cx: &CrateContext) { if cx.dbg_cx().is_none() { return; } @@ -200,11 +200,11 @@ pub fn finalize(cx: &CrateContext) { /// for debug info creation. The function may also return another variant of the /// FunctionDebugContext enum which indicates why no debuginfo should be created /// for the function. -pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, - instance: Instance<'tcx>, - sig: ty::FnSig<'tcx>, - llfn: ValueRef, - mir: &mir::Mir) -> FunctionDebugContext { +pub(crate) fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, + instance: Instance<'tcx>, + sig: ty::FnSig<'tcx>, + llfn: ValueRef, + mir: &mir::Mir) -> FunctionDebugContext { if cx.sess().opts.debuginfo == NoDebugInfo { return FunctionDebugContext::DebugInfoDisabled; } @@ -457,14 +457,14 @@ pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, } } -pub fn declare_local<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, - dbg_context: &FunctionDebugContext, - variable_name: ast::Name, - variable_type: Ty<'tcx>, - scope_metadata: DIScope, - variable_access: VariableAccess, - variable_kind: VariableKind, - span: Span) { +pub(crate) fn declare_local<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, + dbg_context: &FunctionDebugContext, + variable_name: ast::Name, + variable_type: Ty<'tcx>, + scope_metadata: DIScope, + variable_access: VariableAccess, + variable_kind: VariableKind, + span: Span) { let cx = bcx.ccx; let file = span_start(cx, span).file; diff --git a/src/librustc_trans/debuginfo/namespace.rs b/src/librustc_trans/debuginfo/namespace.rs index d4dd112f3027f..b28b91d75208b 100644 --- a/src/librustc_trans/debuginfo/namespace.rs +++ b/src/librustc_trans/debuginfo/namespace.rs @@ -22,7 +22,7 @@ use common::CrateContext; use std::ffi::CString; use std::ptr; -pub fn mangled_name_of_item(ccx: &CrateContext, def_id: DefId, extra: &str) -> String { +pub(crate) fn mangled_name_of_item(ccx: &CrateContext, def_id: DefId, extra: &str) -> String { fn fill_nested(ccx: &CrateContext, def_id: DefId, extra: &str, output: &mut String) { let def_key = ccx.tcx().def_key(def_id); if let Some(parent) = def_key.parent { @@ -48,7 +48,7 @@ pub fn mangled_name_of_item(ccx: &CrateContext, def_id: DefId, extra: &str) -> S name } -pub fn item_namespace(ccx: &CrateContext, def_id: DefId) -> DIScope { +pub(crate) fn item_namespace(ccx: &CrateContext, def_id: DefId) -> DIScope { if let Some(&scope) = debug_context(ccx).namespace_map.borrow().get(&def_id) { return scope; } diff --git a/src/librustc_trans/debuginfo/source_loc.rs b/src/librustc_trans/debuginfo/source_loc.rs index e99e26261a3a1..328feb37e7d3b 100644 --- a/src/librustc_trans/debuginfo/source_loc.rs +++ b/src/librustc_trans/debuginfo/source_loc.rs @@ -25,7 +25,7 @@ use syntax_pos::{Span, Pos}; /// Sets the current debug location at the beginning of the span. /// /// Maps to a call to llvm::LLVMSetCurrentDebugLocation(...). -pub fn set_source_location( +pub(crate) fn set_source_location( debug_context: &FunctionDebugContext, builder: &Builder, scope: DIScope, span: Span ) { let function_debug_context = match *debug_context { @@ -53,7 +53,7 @@ pub fn set_source_location( /// they are disabled when beginning to translate a new function. This functions /// switches source location emitting on and must therefore be called before the /// first real statement/expression of the function is translated. -pub fn start_emitting_source_locations(dbg_context: &FunctionDebugContext) { +pub(crate) fn start_emitting_source_locations(dbg_context: &FunctionDebugContext) { match *dbg_context { FunctionDebugContext::RegularContext(ref data) => { data.source_locations_enabled.set(true) @@ -64,13 +64,13 @@ pub fn start_emitting_source_locations(dbg_context: &FunctionDebugContext) { #[derive(Copy, Clone, PartialEq)] -pub enum InternalDebugLocation { +pub(crate) enum InternalDebugLocation { KnownLocation { scope: DIScope, line: usize, col: usize }, UnknownLocation } impl InternalDebugLocation { - pub fn new(scope: DIScope, line: usize, col: usize) -> InternalDebugLocation { + pub(crate) fn new(scope: DIScope, line: usize, col: usize) -> InternalDebugLocation { KnownLocation { scope: scope, line: line, @@ -79,7 +79,7 @@ impl InternalDebugLocation { } } -pub fn set_debug_location(builder: &Builder, debug_location: InternalDebugLocation) { +pub(crate) fn set_debug_location(builder: &Builder, debug_location: InternalDebugLocation) { let metadata_node = match debug_location { KnownLocation { scope, line, .. } => { // Always set the column to zero like Clang and GCC diff --git a/src/librustc_trans/debuginfo/type_names.rs b/src/librustc_trans/debuginfo/type_names.rs index bfca4fec706ed..46f467c4b6511 100644 --- a/src/librustc_trans/debuginfo/type_names.rs +++ b/src/librustc_trans/debuginfo/type_names.rs @@ -21,10 +21,10 @@ use rustc::hir; // any caching, i.e. calling the function twice with the same type will also do // the work twice. The `qualified` parameter only affects the first level of the // type name, further levels (i.e. type parameters) are always fully qualified. -pub fn compute_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, - t: Ty<'tcx>, - qualified: bool) - -> String { +pub(crate) fn compute_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, + t: Ty<'tcx>, + qualified: bool) + -> String { let mut result = String::with_capacity(64); push_debuginfo_type_name(cx, t, qualified, &mut result); result @@ -32,10 +32,10 @@ pub fn compute_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, // Pushes the name of the type as it should be stored in debuginfo on the // `output` String. See also compute_debuginfo_type_name(). -pub fn push_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, - t: Ty<'tcx>, - qualified: bool, - output: &mut String) { +pub(crate) fn push_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, + t: Ty<'tcx>, + qualified: bool, + output: &mut String) { match t.sty { ty::TyBool => output.push_str("bool"), ty::TyChar => output.push_str("char"), diff --git a/src/librustc_trans/debuginfo/utils.rs b/src/librustc_trans/debuginfo/utils.rs index 6df509f34a472..4aa8126dd66f8 100644 --- a/src/librustc_trans/debuginfo/utils.rs +++ b/src/librustc_trans/debuginfo/utils.rs @@ -27,7 +27,7 @@ use syntax::ast; use std::ops; -pub fn is_node_local_to_unit(cx: &CrateContext, node_id: ast::NodeId) -> bool +pub(crate) fn is_node_local_to_unit(cx: &CrateContext, node_id: ast::NodeId) -> bool { // The is_local_to_unit flag indicates whether a function is local to the // current compilation unit (i.e. if it is *static* in the C-sense). The @@ -41,39 +41,39 @@ pub fn is_node_local_to_unit(cx: &CrateContext, node_id: ast::NodeId) -> bool } #[allow(non_snake_case)] -pub fn create_DIArray(builder: DIBuilderRef, arr: &[DIDescriptor]) -> DIArray { +pub(crate) fn create_DIArray(builder: DIBuilderRef, arr: &[DIDescriptor]) -> DIArray { return unsafe { llvm::LLVMRustDIBuilderGetOrCreateArray(builder, arr.as_ptr(), arr.len() as u32) }; } /// Return syntax_pos::Loc corresponding to the beginning of the span -pub fn span_start(cx: &CrateContext, span: Span) -> syntax_pos::Loc { +pub(crate) fn span_start(cx: &CrateContext, span: Span) -> syntax_pos::Loc { cx.sess().codemap().lookup_char_pos(span.lo) } -pub fn size_and_align_of(cx: &CrateContext, llvm_type: Type) -> (u64, u32) { +pub(crate) fn size_and_align_of(cx: &CrateContext, llvm_type: Type) -> (u64, u32) { (machine::llsize_of_alloc(cx, llvm_type), machine::llalign_of_min(cx, llvm_type)) } -pub fn bytes_to_bits(bytes: T) -> T +pub(crate) fn bytes_to_bits(bytes: T) -> T where T: ops::Mul + From { bytes * 8u8.into() } #[inline] -pub fn debug_context<'a, 'tcx>(cx: &'a CrateContext<'a, 'tcx>) +pub(crate) fn debug_context<'a, 'tcx>(cx: &'a CrateContext<'a, 'tcx>) -> &'a CrateDebugContext<'tcx> { cx.dbg_cx().as_ref().unwrap() } #[inline] #[allow(non_snake_case)] -pub fn DIB(cx: &CrateContext) -> DIBuilderRef { +pub(crate) fn DIB(cx: &CrateContext) -> DIBuilderRef { cx.dbg_cx().as_ref().unwrap().builder } -pub fn get_namespace_for_item(cx: &CrateContext, def_id: DefId) -> DIScope { +pub(crate) fn get_namespace_for_item(cx: &CrateContext, def_id: DefId) -> DIScope { item_namespace(cx, cx.tcx().parent(def_id) .expect("get_namespace_for_item: missing parent?")) } diff --git a/src/librustc_trans/declare.rs b/src/librustc_trans/declare.rs index 8f9146283effe..c66630f4f963c 100644 --- a/src/librustc_trans/declare.rs +++ b/src/librustc_trans/declare.rs @@ -38,7 +38,7 @@ use std::ffi::CString; /// /// If there’s a value with the same name already declared, the function will /// return its ValueRef instead. -pub fn declare_global(ccx: &CrateContext, name: &str, ty: Type) -> llvm::ValueRef { +pub(crate) fn declare_global(ccx: &CrateContext, name: &str, ty: Type) -> llvm::ValueRef { debug!("declare_global(name={:?})", name); let namebuf = CString::new(name).unwrap_or_else(|_|{ bug!("name {:?} contains an interior null byte", name) @@ -109,7 +109,7 @@ fn declare_raw_fn(ccx: &CrateContext, name: &str, callconv: llvm::CallConv, ty: /// /// If there’s a value with the same name already declared, the function will /// update the declaration and return existing ValueRef instead. -pub fn declare_cfn(ccx: &CrateContext, name: &str, fn_type: Type) -> ValueRef { +pub(crate) fn declare_cfn(ccx: &CrateContext, name: &str, fn_type: Type) -> ValueRef { declare_raw_fn(ccx, name, llvm::CCallConv, fn_type) } @@ -118,8 +118,8 @@ pub fn declare_cfn(ccx: &CrateContext, name: &str, fn_type: Type) -> ValueRef { /// /// If there’s a value with the same name already declared, the function will /// update the declaration and return existing ValueRef instead. -pub fn declare_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, name: &str, - fn_type: ty::Ty<'tcx>) -> ValueRef { +pub(crate) fn declare_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, name: &str, + fn_type: ty::Ty<'tcx>) -> ValueRef { debug!("declare_rust_fn(name={:?}, fn_type={:?})", name, fn_type); let sig = common::ty_fn_sig(ccx, fn_type); let sig = ccx.tcx().erase_late_bound_regions_and_normalize(&sig); @@ -149,7 +149,7 @@ pub fn declare_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, name: &str, /// return None if the name already has a definition associated with it. In that /// case an error should be reported to the user, because it usually happens due /// to user’s fault (e.g. misuse of #[no_mangle] or #[export_name] attributes). -pub fn define_global(ccx: &CrateContext, name: &str, ty: Type) -> Option { +pub(crate) fn define_global(ccx: &CrateContext, name: &str, ty: Type) -> Option { if get_defined_value(ccx, name).is_some() { None } else { @@ -162,9 +162,9 @@ pub fn define_global(ccx: &CrateContext, name: &str, ty: Type) -> Option(ccx: &CrateContext<'a, 'tcx>, - name: &str, - fn_type: ty::Ty<'tcx>) -> ValueRef { +pub(crate) fn define_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, + name: &str, + fn_type: ty::Ty<'tcx>) -> ValueRef { if get_defined_value(ccx, name).is_some() { ccx.sess().fatal(&format!("symbol `{}` already defined", name)) } else { @@ -177,9 +177,9 @@ pub fn define_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, /// Use this function when you intend to define a function. This function will /// return panic if the name already has a definition associated with it. This /// can happen with #[no_mangle] or #[export_name], for example. -pub fn define_internal_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, - name: &str, - fn_type: ty::Ty<'tcx>) -> ValueRef { +pub(crate) fn define_internal_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, + name: &str, + fn_type: ty::Ty<'tcx>) -> ValueRef { let llfn = define_fn(ccx, name, fn_type); unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::InternalLinkage) }; llfn @@ -187,7 +187,7 @@ pub fn define_internal_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, /// Get declared value by name. -pub fn get_declared_value(ccx: &CrateContext, name: &str) -> Option { +pub(crate) fn get_declared_value(ccx: &CrateContext, name: &str) -> Option { debug!("get_declared_value(name={:?})", name); let namebuf = CString::new(name).unwrap_or_else(|_|{ bug!("name {:?} contains an interior null byte", name) @@ -204,7 +204,7 @@ pub fn get_declared_value(ccx: &CrateContext, name: &str) -> Option { /// Get defined or externally defined (AvailableExternally linkage) value by /// name. -pub fn get_defined_value(ccx: &CrateContext, name: &str) -> Option { +pub(crate) fn get_defined_value(ccx: &CrateContext, name: &str) -> Option { get_declared_value(ccx, name).and_then(|val|{ let declaration = unsafe { llvm::LLVMIsDeclaration(val) != 0 diff --git a/src/librustc_trans/glue.rs b/src/librustc_trans/glue.rs index c2f44c089a2d6..1d001a3ff6c06 100644 --- a/src/librustc_trans/glue.rs +++ b/src/librustc_trans/glue.rs @@ -25,7 +25,7 @@ use monomorphize; use value::Value; use builder::Builder; -pub fn needs_drop_glue<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>, t: Ty<'tcx>) -> bool { +pub(crate) fn needs_drop_glue<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>, t: Ty<'tcx>) -> bool { assert!(t.is_normalized_for_trans()); let t = scx.tcx().erase_regions(&t); @@ -61,7 +61,7 @@ pub fn needs_drop_glue<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>, t: Ty<'tcx> } } -pub fn size_and_align_of_dst<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, t: Ty<'tcx>, info: ValueRef) +pub(crate) fn size_and_align_of_dst<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, t: Ty<'tcx>, info: ValueRef) -> (ValueRef, ValueRef) { debug!("calculate size of DST: {}; with lost info: {:?}", t, Value(info)); diff --git a/src/librustc_trans/intrinsic.rs b/src/librustc_trans/intrinsic.rs index 9956c28e64121..845aad75ba84d 100644 --- a/src/librustc_trans/intrinsic.rs +++ b/src/librustc_trans/intrinsic.rs @@ -86,12 +86,12 @@ fn get_simple_intrinsic(ccx: &CrateContext, name: &str) -> Option { /// Remember to add all intrinsics here, in librustc_typeck/check/mod.rs, /// and in libcore/intrinsics.rs; if you need access to any llvm intrinsics, /// add them to librustc_trans/trans/context.rs -pub fn trans_intrinsic_call<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, - callee_ty: Ty<'tcx>, - fn_ty: &FnType, - llargs: &[ValueRef], - llresult: ValueRef, - span: Span) { +pub(crate) fn trans_intrinsic_call<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, + callee_ty: Ty<'tcx>, + fn_ty: &FnType, + llargs: &[ValueRef], + llresult: ValueRef, + span: Span) { let ccx = bcx.ccx; let tcx = ccx.tcx(); diff --git a/src/librustc_trans/lib.rs b/src/librustc_trans/lib.rs index 3038c7d6c782e..a3bfc0740d276 100644 --- a/src/librustc_trans/lib.rs +++ b/src/librustc_trans/lib.rs @@ -48,7 +48,7 @@ extern crate rustc_allocator; extern crate rustc_back; extern crate rustc_data_structures; extern crate rustc_incremental; -pub extern crate rustc_llvm as llvm; +extern crate rustc_llvm as llvm; extern crate rustc_platform_intrinsics as intrinsics; extern crate rustc_const_math; #[macro_use] @@ -79,7 +79,7 @@ pub mod back { pub(crate) mod symbol_export; pub(crate) mod symbol_names; pub mod write; - pub mod rpath; + pub(crate) mod rpath; } mod diagnostics; @@ -139,8 +139,8 @@ pub struct ModuleTranslation { /// unique amongst **all** crates. Therefore, it should contain /// something unique to this crate (e.g., a module path) as well /// as the crate name and disambiguator. - pub name: String, - pub symbol_name_hash: u64, + name: String, + symbol_name_hash: u64, pub source: ModuleSource, } @@ -155,7 +155,7 @@ pub enum ModuleSource { #[derive(Copy, Clone)] pub struct ModuleLlvm { - pub llcx: llvm::ContextRef, + llcx: llvm::ContextRef, pub llmod: llvm::ModuleRef, } @@ -165,14 +165,14 @@ unsafe impl Sync for ModuleTranslation { } pub struct CrateTranslation { pub crate_name: Symbol, pub modules: Vec, - pub metadata_module: ModuleTranslation, - pub allocator_module: Option, + metadata_module: ModuleTranslation, + allocator_module: Option, pub link: rustc::middle::cstore::LinkMeta, pub metadata: rustc::middle::cstore::EncodedMetadata, - pub exported_symbols: back::symbol_export::ExportedSymbols, - pub no_builtins: bool, - pub windows_subsystem: Option, - pub linker_info: back::linker::LinkerInfo + exported_symbols: back::symbol_export::ExportedSymbols, + no_builtins: bool, + windows_subsystem: Option, + linker_info: back::linker::LinkerInfo } __build_diagnostic_array! { librustc_trans, DIAGNOSTICS } diff --git a/src/librustc_trans/machine.rs b/src/librustc_trans/machine.rs index cd31f02842add..30abb634e438a 100644 --- a/src/librustc_trans/machine.rs +++ b/src/librustc_trans/machine.rs @@ -17,30 +17,30 @@ use common::*; use type_::Type; -pub type llbits = u64; -pub type llsize = u64; -pub type llalign = u32; +pub(crate) type llbits = u64; +pub(crate) type llsize = u64; +pub(crate) type llalign = u32; // ______________________________________________________________________ // compute sizeof / alignof // Returns the number of bytes between successive elements of type T in an // array of T. This is the "ABI" size. It includes any ABI-mandated padding. -pub fn llsize_of_alloc(cx: &CrateContext, ty: Type) -> llsize { +pub(crate) fn llsize_of_alloc(cx: &CrateContext, ty: Type) -> llsize { unsafe { return llvm::LLVMABISizeOfType(cx.td(), ty.to_ref()); } } /// Returns the "real" size of the type in bits. -pub fn llbitsize_of_real(cx: &CrateContext, ty: Type) -> llbits { +pub(crate) fn llbitsize_of_real(cx: &CrateContext, ty: Type) -> llbits { unsafe { llvm::LLVMSizeOfTypeInBits(cx.td(), ty.to_ref()) } } /// Returns the size of the type as an LLVM constant integer value. -pub fn llsize_of(cx: &CrateContext, ty: Type) -> ValueRef { +pub(crate) fn llsize_of(cx: &CrateContext, ty: Type) -> ValueRef { // Once upon a time, this called LLVMSizeOf, which does a // getelementptr(1) on a null pointer and casts to an int, in // order to obtain the type size as a value without requiring the @@ -55,7 +55,7 @@ pub fn llsize_of(cx: &CrateContext, ty: Type) -> ValueRef { // The preferred alignment may be larger than the alignment used when // packing the type into structs. This will be used for things like // allocations inside a stack frame, which LLVM has a free hand in. -pub fn llalign_of_pref(cx: &CrateContext, ty: Type) -> llalign { +pub(crate) fn llalign_of_pref(cx: &CrateContext, ty: Type) -> llalign { unsafe { return llvm::LLVMPreferredAlignmentOfType(cx.td(), ty.to_ref()); } @@ -64,13 +64,13 @@ pub fn llalign_of_pref(cx: &CrateContext, ty: Type) -> llalign { // Returns the minimum alignment of a type required by the platform. // This is the alignment that will be used for struct fields, arrays, // and similar ABI-mandated things. -pub fn llalign_of_min(cx: &CrateContext, ty: Type) -> llalign { +pub(crate) fn llalign_of_min(cx: &CrateContext, ty: Type) -> llalign { unsafe { return llvm::LLVMABIAlignmentOfType(cx.td(), ty.to_ref()); } } -pub fn llelement_offset(cx: &CrateContext, struct_ty: Type, element: usize) -> u64 { +pub(crate) fn llelement_offset(cx: &CrateContext, struct_ty: Type, element: usize) -> u64 { unsafe { return llvm::LLVMOffsetOfElement(cx.td(), struct_ty.to_ref(), diff --git a/src/librustc_trans/metadata.rs b/src/librustc_trans/metadata.rs index 2c0148dfbb371..4442bccbbfcd5 100644 --- a/src/librustc_trans/metadata.rs +++ b/src/librustc_trans/metadata.rs @@ -20,7 +20,7 @@ use std::path::Path; use std::ptr; use std::slice; -pub const METADATA_FILENAME: &str = "rust.metadata.bin"; +pub(crate) const METADATA_FILENAME: &str = "rust.metadata.bin"; pub struct LlvmMetadataLoader; @@ -95,7 +95,7 @@ fn search_meta_section<'a>(of: &'a ObjectFile, Err(format!("metadata not found: '{}'", filename.display())) } -pub fn metadata_section_name(target: &Target) -> &'static str { +pub(crate) fn metadata_section_name(target: &Target) -> &'static str { // Historical note: // // When using link.exe it was seen that the section name `.note.rustc` diff --git a/src/librustc_trans/meth.rs b/src/librustc_trans/meth.rs index f5f924178589a..1dd08d51e36c6 100644 --- a/src/librustc_trans/meth.rs +++ b/src/librustc_trans/meth.rs @@ -21,18 +21,18 @@ use value::Value; use rustc::ty; #[derive(Copy, Clone, Debug)] -pub struct VirtualIndex(usize); +pub(crate) struct VirtualIndex(usize); -pub const DESTRUCTOR: VirtualIndex = VirtualIndex(0); -pub const SIZE: VirtualIndex = VirtualIndex(1); -pub const ALIGN: VirtualIndex = VirtualIndex(2); +pub(crate) const DESTRUCTOR: VirtualIndex = VirtualIndex(0); +pub(crate) const SIZE: VirtualIndex = VirtualIndex(1); +pub(crate) const ALIGN: VirtualIndex = VirtualIndex(2); impl<'a, 'tcx> VirtualIndex { - pub fn from_index(index: usize) -> Self { + pub(crate) fn from_index(index: usize) -> Self { VirtualIndex(index + 3) } - pub fn get_fn(self, bcx: &Builder<'a, 'tcx>, llvtable: ValueRef) -> ValueRef { + pub(crate) fn get_fn(self, bcx: &Builder<'a, 'tcx>, llvtable: ValueRef) -> ValueRef { // Load the data pointer from the object. debug!("get_fn({:?}, {:?})", Value(llvtable), self); @@ -42,7 +42,7 @@ impl<'a, 'tcx> VirtualIndex { ptr } - pub fn get_usize(self, bcx: &Builder<'a, 'tcx>, llvtable: ValueRef) -> ValueRef { + pub(crate) fn get_usize(self, bcx: &Builder<'a, 'tcx>, llvtable: ValueRef) -> ValueRef { // Load the data pointer from the object. debug!("get_int({:?}, {:?})", Value(llvtable), self); @@ -62,10 +62,10 @@ impl<'a, 'tcx> VirtualIndex { /// The `trait_ref` encodes the erased self type. Hence if we are /// making an object `Foo` from a value of type `Foo`, then /// `trait_ref` would map `T:Trait`. -pub fn get_vtable<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, - ty: ty::Ty<'tcx>, - trait_ref: Option>) - -> ValueRef +pub(crate) fn get_vtable<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, + ty: ty::Ty<'tcx>, + trait_ref: Option>) + -> ValueRef { let tcx = ccx.tcx(); diff --git a/src/librustc_trans/mir/analyze.rs b/src/librustc_trans/mir/analyze.rs index 45afcf51b5203..ee6aef52a6508 100644 --- a/src/librustc_trans/mir/analyze.rs +++ b/src/librustc_trans/mir/analyze.rs @@ -20,7 +20,7 @@ use rustc::mir::traversal; use common; use super::MirContext; -pub fn lvalue_locals<'a, 'tcx>(mircx: &MirContext<'a, 'tcx>) -> BitVector { +pub(crate) fn lvalue_locals<'a, 'tcx>(mircx: &MirContext<'a, 'tcx>) -> BitVector { let mir = mircx.mir; let mut analyzer = LocalAnalyzer::new(mircx); @@ -191,14 +191,14 @@ impl<'mir, 'a, 'tcx> Visitor<'tcx> for LocalAnalyzer<'mir, 'a, 'tcx> { } #[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub enum CleanupKind { +pub(crate) enum CleanupKind { NotCleanup, Funclet, Internal { funclet: mir::BasicBlock } } impl CleanupKind { - pub fn funclet_bb(self, for_bb: mir::BasicBlock) -> Option { + pub(crate) fn funclet_bb(self, for_bb: mir::BasicBlock) -> Option { match self { CleanupKind::NotCleanup => None, CleanupKind::Funclet => Some(for_bb), @@ -207,7 +207,8 @@ impl CleanupKind { } } -pub fn cleanup_kinds<'a, 'tcx>(mir: &mir::Mir<'tcx>) -> IndexVec { +pub(crate) fn cleanup_kinds<'a, 'tcx>(mir: &mir::Mir<'tcx>) + -> IndexVec { fn discover_masters<'tcx>(result: &mut IndexVec, mir: &mir::Mir<'tcx>) { for (bb, data) in mir.basic_blocks().iter_enumerated() { diff --git a/src/librustc_trans/mir/block.rs b/src/librustc_trans/mir/block.rs index 9bb29c340d983..b790ae3004c40 100644 --- a/src/librustc_trans/mir/block.rs +++ b/src/librustc_trans/mir/block.rs @@ -39,7 +39,7 @@ use super::operand::OperandRef; use super::operand::OperandValue::{Pair, Ref, Immediate}; impl<'a, 'tcx> MirContext<'a, 'tcx> { - pub fn trans_block(&mut self, bb: mir::BasicBlock) { + pub(crate) fn trans_block(&mut self, bb: mir::BasicBlock) { let mut bcx = self.get_builder(bb); let data = &self.mir[bb]; @@ -776,11 +776,11 @@ impl<'a, 'tcx> MirContext<'a, 'tcx> { }) } - pub fn new_block(&self, name: &str) -> Builder<'a, 'tcx> { + pub(crate) fn new_block(&self, name: &str) -> Builder<'a, 'tcx> { Builder::new_block(self.ccx, self.llfn, name) } - pub fn get_builder(&self, bb: mir::BasicBlock) -> Builder<'a, 'tcx> { + pub(crate) fn get_builder(&self, bb: mir::BasicBlock) -> Builder<'a, 'tcx> { let builder = Builder::with_ccx(self.ccx); builder.position_at_end(self.blocks[bb]); builder diff --git a/src/librustc_trans/mir/constant.rs b/src/librustc_trans/mir/constant.rs index 98e774a29877d..8b85d08da14bc 100644 --- a/src/librustc_trans/mir/constant.rs +++ b/src/librustc_trans/mir/constant.rs @@ -49,20 +49,20 @@ use super::MirContext; /// The LLVM type might not be the same for a single Rust type, /// e.g. each enum variant would have its own LLVM struct type. #[derive(Copy, Clone)] -pub struct Const<'tcx> { - pub llval: ValueRef, - pub ty: Ty<'tcx> +pub(crate) struct Const<'tcx> { + pub(crate) llval: ValueRef, + pub(crate) ty: Ty<'tcx> } impl<'tcx> Const<'tcx> { - pub fn new(llval: ValueRef, ty: Ty<'tcx>) -> Const<'tcx> { + pub(crate) fn new(llval: ValueRef, ty: Ty<'tcx>) -> Const<'tcx> { Const { llval: llval, ty: ty } } - pub fn from_constint<'a>(ccx: &CrateContext<'a, 'tcx>, ci: &ConstInt) + pub(crate) fn from_constint<'a>(ccx: &CrateContext<'a, 'tcx>, ci: &ConstInt) -> Const<'tcx> { let tcx = ccx.tcx(); let (llval, ty) = match *ci { @@ -89,10 +89,10 @@ impl<'tcx> Const<'tcx> { } /// Translate ConstVal into a LLVM constant value. - pub fn from_constval<'a>(ccx: &CrateContext<'a, 'tcx>, - cv: ConstVal, - ty: Ty<'tcx>) - -> Const<'tcx> { + pub(crate) fn from_constval<'a>(ccx: &CrateContext<'a, 'tcx>, + cv: ConstVal, + ty: Ty<'tcx>) + -> Const<'tcx> { let llty = type_of::type_of(ccx, ty); let val = match cv { ConstVal::Float(F32(v)) => C_floating_f64(v as f64, llty), @@ -134,7 +134,7 @@ impl<'tcx> Const<'tcx> { } } - pub fn to_operand<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> OperandRef<'tcx> { + pub(crate) fn to_operand<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> OperandRef<'tcx> { let llty = type_of::immediate_type_of(ccx, self.ty); let llvalty = val_ty(self.llval); @@ -200,7 +200,7 @@ impl<'tcx> ConstLvalue<'tcx> { } } - pub fn len<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> ValueRef { + pub(crate) fn len<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> ValueRef { match self.ty.sty { ty::TyArray(_, n) => C_uint(ccx, n), ty::TySlice(_) | ty::TyStr => { @@ -844,10 +844,10 @@ fn to_const_int(value: ValueRef, t: Ty, tcx: TyCtxt) -> Option { } } -pub fn const_scalar_binop(op: mir::BinOp, - lhs: ValueRef, - rhs: ValueRef, - input_ty: Ty) -> ValueRef { +pub(crate) fn const_scalar_binop(op: mir::BinOp, + lhs: ValueRef, + rhs: ValueRef, + input_ty: Ty) -> ValueRef { assert!(!input_ty.is_simd()); let is_float = input_ty.is_fp(); let signed = input_ty.is_signed(); @@ -900,12 +900,12 @@ pub fn const_scalar_binop(op: mir::BinOp, } } -pub fn const_scalar_checked_binop<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - op: mir::BinOp, - lllhs: ValueRef, - llrhs: ValueRef, - input_ty: Ty<'tcx>) - -> Option<(ValueRef, bool)> { +pub(crate) fn const_scalar_checked_binop<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, + op: mir::BinOp, + lllhs: ValueRef, + llrhs: ValueRef, + input_ty: Ty<'tcx>) + -> Option<(ValueRef, bool)> { if let (Some(lhs), Some(rhs)) = (to_const_int(lllhs, input_ty, tcx), to_const_int(llrhs, input_ty, tcx)) { let result = match op { @@ -936,10 +936,10 @@ pub fn const_scalar_checked_binop<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } impl<'a, 'tcx> MirContext<'a, 'tcx> { - pub fn trans_constant(&mut self, - bcx: &Builder<'a, 'tcx>, - constant: &mir::Constant<'tcx>) - -> Const<'tcx> + pub(crate) fn trans_constant(&mut self, + bcx: &Builder<'a, 'tcx>, + constant: &mir::Constant<'tcx>) + -> Const<'tcx> { debug!("trans_constant({:?})", constant); let ty = self.monomorphize(&constant.ty); @@ -969,7 +969,7 @@ impl<'a, 'tcx> MirContext<'a, 'tcx> { } -pub fn trans_static_initializer<'a, 'tcx>( +pub(crate) fn trans_static_initializer<'a, 'tcx>( ccx: &CrateContext<'a, 'tcx>, def_id: DefId) -> Result> diff --git a/src/librustc_trans/mir/lvalue.rs b/src/librustc_trans/mir/lvalue.rs index af8976967a1e7..87cb027ca4375 100644 --- a/src/librustc_trans/mir/lvalue.rs +++ b/src/librustc_trans/mir/lvalue.rs @@ -30,7 +30,7 @@ use std::ops; use super::{MirContext, LocalRef}; #[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub enum Alignment { +pub(crate) enum Alignment { Packed, AbiAligned, } @@ -47,7 +47,7 @@ impl ops::BitOr for Alignment { } impl Alignment { - pub fn from_packed(packed: bool) -> Self { + pub(crate) fn from_packed(packed: bool) -> Self { if packed { Alignment::Packed } else { @@ -55,14 +55,14 @@ impl Alignment { } } - pub fn to_align(self) -> Option { + pub(crate) fn to_align(self) -> Option { match self { Alignment::Packed => Some(1), Alignment::AbiAligned => None, } } - pub fn min_with(self, align: u32) -> Option { + pub(crate) fn min_with(self, align: u32) -> Option { match self { Alignment::Packed => Some(1), Alignment::AbiAligned => Some(align), @@ -71,31 +71,32 @@ impl Alignment { } #[derive(Copy, Clone, Debug)] -pub struct LvalueRef<'tcx> { +pub(crate) struct LvalueRef<'tcx> { /// Pointer to the contents of the lvalue - pub llval: ValueRef, + pub(crate) llval: ValueRef, /// This lvalue's extra data if it is unsized, or null - pub llextra: ValueRef, + pub(crate) llextra: ValueRef, /// Monomorphized type of this lvalue, including variant information - pub ty: LvalueTy<'tcx>, + pub(crate) ty: LvalueTy<'tcx>, /// Whether this lvalue is known to be aligned according to its layout - pub alignment: Alignment, + pub(crate) alignment: Alignment, } impl<'a, 'tcx> LvalueRef<'tcx> { - pub fn new_sized(llval: ValueRef, lvalue_ty: LvalueTy<'tcx>, - alignment: Alignment) -> LvalueRef<'tcx> { + pub(crate) fn new_sized(llval: ValueRef, lvalue_ty: LvalueTy<'tcx>, + alignment: Alignment) -> LvalueRef<'tcx> { LvalueRef { llval: llval, llextra: ptr::null_mut(), ty: lvalue_ty, alignment: alignment } } - pub fn new_sized_ty(llval: ValueRef, ty: Ty<'tcx>, alignment: Alignment) -> LvalueRef<'tcx> { + pub(crate) fn new_sized_ty(llval: ValueRef, ty: Ty<'tcx>, alignment: Alignment) + -> LvalueRef<'tcx> { LvalueRef::new_sized(llval, LvalueTy::from_ty(ty), alignment) } - pub fn alloca(bcx: &Builder<'a, 'tcx>, ty: Ty<'tcx>, name: &str) -> LvalueRef<'tcx> { + pub(crate) fn alloca(bcx: &Builder<'a, 'tcx>, ty: Ty<'tcx>, name: &str) -> LvalueRef<'tcx> { debug!("alloca({:?}: {:?})", name, ty); let tmp = bcx.alloca( type_of::type_of(bcx.ccx, ty), name, bcx.ccx.over_align_of(ty)); @@ -103,7 +104,7 @@ impl<'a, 'tcx> LvalueRef<'tcx> { Self::new_sized_ty(tmp, ty, Alignment::AbiAligned) } - pub fn len(&self, ccx: &CrateContext<'a, 'tcx>) -> ValueRef { + pub(crate) fn len(&self, ccx: &CrateContext<'a, 'tcx>) -> ValueRef { let ty = self.ty.to_ty(ccx.tcx()); match ty.sty { ty::TyArray(_, n) => common::C_uint(ccx, n), @@ -115,7 +116,7 @@ impl<'a, 'tcx> LvalueRef<'tcx> { } } - pub fn has_extra(&self) -> bool { + pub(crate) fn has_extra(&self) -> bool { !self.llextra.is_null() } @@ -214,7 +215,8 @@ impl<'a, 'tcx> LvalueRef<'tcx> { } /// Access a field, at a point when the value's case is known. - pub fn trans_field_ptr(self, bcx: &Builder<'a, 'tcx>, ix: usize) -> (ValueRef, Alignment) { + pub(crate) fn trans_field_ptr(self, bcx: &Builder<'a, 'tcx>, ix: usize) + -> (ValueRef, Alignment) { let discr = match self.ty { LvalueTy::Ty { .. } => 0, LvalueTy::Downcast { variant_index, .. } => variant_index, @@ -271,7 +273,7 @@ impl<'a, 'tcx> LvalueRef<'tcx> { } } - pub fn project_index(&self, bcx: &Builder<'a, 'tcx>, llindex: ValueRef) -> ValueRef { + pub(crate) fn project_index(&self, bcx: &Builder<'a, 'tcx>, llindex: ValueRef) -> ValueRef { if let ty::TySlice(_) = self.ty.to_ty(bcx.tcx()).sty { // Slices already point to the array element type. bcx.inbounds_gep(self.llval, &[llindex]) @@ -283,10 +285,10 @@ impl<'a, 'tcx> LvalueRef<'tcx> { } impl<'a, 'tcx> MirContext<'a, 'tcx> { - pub fn trans_lvalue(&mut self, - bcx: &Builder<'a, 'tcx>, - lvalue: &mir::Lvalue<'tcx>) - -> LvalueRef<'tcx> { + pub(crate) fn trans_lvalue(&mut self, + bcx: &Builder<'a, 'tcx>, + lvalue: &mir::Lvalue<'tcx>) + -> LvalueRef<'tcx> { debug!("trans_lvalue(lvalue={:?})", lvalue); let ccx = bcx.ccx; @@ -406,7 +408,7 @@ impl<'a, 'tcx> MirContext<'a, 'tcx> { } } - pub fn monomorphized_lvalue_ty(&self, lvalue: &mir::Lvalue<'tcx>) -> Ty<'tcx> { + pub(crate) fn monomorphized_lvalue_ty(&self, lvalue: &mir::Lvalue<'tcx>) -> Ty<'tcx> { let tcx = self.ccx.tcx(); let lvalue_ty = lvalue.ty(self.mir, tcx); self.monomorphize(&lvalue_ty.to_ty(tcx)) diff --git a/src/librustc_trans/mir/mod.rs b/src/librustc_trans/mir/mod.rs index a7f12babb10f9..2b09e092f330a 100644 --- a/src/librustc_trans/mir/mod.rs +++ b/src/librustc_trans/mir/mod.rs @@ -34,7 +34,7 @@ use std::iter; use rustc_data_structures::bitvec::BitVector; use rustc_data_structures::indexed_vec::{IndexVec, Idx}; -pub use self::constant::trans_static_initializer; +pub(crate) use self::constant::trans_static_initializer; use self::analyze::CleanupKind; use self::lvalue::{Alignment, LvalueRef}; @@ -43,7 +43,7 @@ use rustc::mir::traversal; use self::operand::{OperandRef, OperandValue}; /// Master context for translating MIR. -pub struct MirContext<'a, 'tcx:'a> { +pub(crate) struct MirContext<'a, 'tcx:'a> { mir: &'a mir::Mir<'tcx>, debug_context: debuginfo::FunctionDebugContext, @@ -105,18 +105,18 @@ pub struct MirContext<'a, 'tcx:'a> { } impl<'a, 'tcx> MirContext<'a, 'tcx> { - pub fn monomorphize(&self, value: &T) -> T + pub(crate) fn monomorphize(&self, value: &T) -> T where T: TransNormalize<'tcx> { self.ccx.tcx().trans_apply_param_substs(self.param_substs, value) } - pub fn set_debug_loc(&mut self, bcx: &Builder, source_info: mir::SourceInfo) { + pub(crate) fn set_debug_loc(&mut self, bcx: &Builder, source_info: mir::SourceInfo) { let (scope, span) = self.debug_loc(source_info); debuginfo::set_source_location(&self.debug_context, bcx, scope, span); } - pub fn debug_loc(&mut self, source_info: mir::SourceInfo) -> (DIScope, Span) { + pub(crate) fn debug_loc(&mut self, source_info: mir::SourceInfo) -> (DIScope, Span) { // Bail out if debug info emission is not enabled. match self.debug_context { FunctionDebugContext::DebugInfoDisabled | @@ -193,7 +193,7 @@ impl<'tcx> LocalRef<'tcx> { /////////////////////////////////////////////////////////////////////////// -pub fn trans_mir<'a, 'tcx: 'a>( +pub(crate) fn trans_mir<'a, 'tcx: 'a>( ccx: &'a CrateContext<'a, 'tcx>, llfn: ValueRef, mir: &'a Mir<'tcx>, @@ -603,7 +603,7 @@ fn arg_local_refs<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, mod analyze; mod block; mod constant; -pub mod lvalue; +pub(crate) mod lvalue; mod operand; mod rvalue; mod statement; diff --git a/src/librustc_trans/mir/operand.rs b/src/librustc_trans/mir/operand.rs index 1b8a05b6f6c74..5ad840f902da6 100644 --- a/src/librustc_trans/mir/operand.rs +++ b/src/librustc_trans/mir/operand.rs @@ -33,7 +33,7 @@ use super::lvalue::{Alignment, LvalueRef}; /// uniquely determined by the value's type, but is kept as a /// safety check. #[derive(Copy, Clone)] -pub enum OperandValue { +pub(crate) enum OperandValue { /// A reference to the actual operand. The data is guaranteed /// to be valid for the operand's lifetime. Ref(ValueRef, Alignment), @@ -52,12 +52,12 @@ pub enum OperandValue { /// directly is sure to cause problems -- use `MirContext.store_operand` /// instead. #[derive(Copy, Clone)] -pub struct OperandRef<'tcx> { +pub(crate) struct OperandRef<'tcx> { // The value. - pub val: OperandValue, + pub(crate) val: OperandValue, // The type of value being returned. - pub ty: Ty<'tcx> + pub(crate) ty: Ty<'tcx> } impl<'tcx> fmt::Debug for OperandRef<'tcx> { @@ -80,8 +80,8 @@ impl<'tcx> fmt::Debug for OperandRef<'tcx> { } impl<'a, 'tcx> OperandRef<'tcx> { - pub fn new_zst(ccx: &CrateContext<'a, 'tcx>, - ty: Ty<'tcx>) -> OperandRef<'tcx> { + pub(crate) fn new_zst(ccx: &CrateContext<'a, 'tcx>, + ty: Ty<'tcx>) -> OperandRef<'tcx> { assert!(common::type_is_zero_size(ccx, ty)); let llty = type_of::type_of(ccx, ty); let val = if common::type_is_imm_pair(ccx, ty) { @@ -105,14 +105,14 @@ impl<'a, 'tcx> OperandRef<'tcx> { /// Asserts that this operand refers to a scalar and returns /// a reference to its value. - pub fn immediate(self) -> ValueRef { + pub(crate) fn immediate(self) -> ValueRef { match self.val { OperandValue::Immediate(s) => s, _ => bug!("not immediate: {:?}", self) } } - pub fn deref(self) -> LvalueRef<'tcx> { + pub(crate) fn deref(self) -> LvalueRef<'tcx> { let projected_ty = self.ty.builtin_deref(true, ty::NoPreference) .unwrap_or_else(|| bug!("deref of non-pointer {:?}", self)).ty; let (llptr, llextra) = match self.val { @@ -130,7 +130,7 @@ impl<'a, 'tcx> OperandRef<'tcx> { /// If this operand is a Pair, we return an /// Immediate aggregate with the two values. - pub fn pack_if_pair(mut self, bcx: &Builder<'a, 'tcx>) -> OperandRef<'tcx> { + pub(crate) fn pack_if_pair(mut self, bcx: &Builder<'a, 'tcx>) -> OperandRef<'tcx> { if let OperandValue::Pair(a, b) = self.val { // Reconstruct the immediate aggregate. let llty = type_of::type_of(bcx.ccx, self.ty); @@ -157,7 +157,7 @@ impl<'a, 'tcx> OperandRef<'tcx> { /// If this operand is a pair in an Immediate, /// we return a Pair with the two halves. - pub fn unpack_if_pair(mut self, bcx: &Builder<'a, 'tcx>) -> OperandRef<'tcx> { + pub(crate) fn unpack_if_pair(mut self, bcx: &Builder<'a, 'tcx>) -> OperandRef<'tcx> { if let OperandValue::Immediate(llval) = self.val { // Deconstruct the immediate aggregate. if common::type_is_imm_pair(bcx.ccx, self.ty) { @@ -192,12 +192,12 @@ impl<'a, 'tcx> OperandRef<'tcx> { } impl<'a, 'tcx> MirContext<'a, 'tcx> { - pub fn trans_load(&mut self, - bcx: &Builder<'a, 'tcx>, - llval: ValueRef, - align: Alignment, - ty: Ty<'tcx>) - -> OperandRef<'tcx> + pub(crate) fn trans_load(&mut self, + bcx: &Builder<'a, 'tcx>, + llval: ValueRef, + align: Alignment, + ty: Ty<'tcx>) + -> OperandRef<'tcx> { debug!("trans_load: {:?} @ {:?}", Value(llval), ty); @@ -230,10 +230,10 @@ impl<'a, 'tcx> MirContext<'a, 'tcx> { OperandRef { val: val, ty: ty } } - pub fn trans_consume(&mut self, - bcx: &Builder<'a, 'tcx>, - lvalue: &mir::Lvalue<'tcx>) - -> OperandRef<'tcx> + pub(crate) fn trans_consume(&mut self, + bcx: &Builder<'a, 'tcx>, + lvalue: &mir::Lvalue<'tcx>) + -> OperandRef<'tcx> { debug!("trans_consume(lvalue={:?})", lvalue); @@ -282,10 +282,10 @@ impl<'a, 'tcx> MirContext<'a, 'tcx> { self.trans_load(bcx, tr_lvalue.llval, tr_lvalue.alignment, ty) } - pub fn trans_operand(&mut self, - bcx: &Builder<'a, 'tcx>, - operand: &mir::Operand<'tcx>) - -> OperandRef<'tcx> + pub(crate) fn trans_operand(&mut self, + bcx: &Builder<'a, 'tcx>, + operand: &mir::Operand<'tcx>) + -> OperandRef<'tcx> { debug!("trans_operand(operand={:?})", operand); @@ -307,11 +307,11 @@ impl<'a, 'tcx> MirContext<'a, 'tcx> { } } - pub fn store_operand(&mut self, - bcx: &Builder<'a, 'tcx>, - lldest: ValueRef, - align: Option, - operand: OperandRef<'tcx>) { + pub(crate) fn store_operand(&mut self, + bcx: &Builder<'a, 'tcx>, + lldest: ValueRef, + align: Option, + operand: OperandRef<'tcx>) { debug!("store_operand: operand={:?}, align={:?}", operand, align); // Avoid generating stores of zero-sized values, because the only way to have a zero-sized // value is through `undef`, and store itself is useless. diff --git a/src/librustc_trans/mir/rvalue.rs b/src/librustc_trans/mir/rvalue.rs index 4bd5091a4f35f..cf77540ecbb96 100644 --- a/src/librustc_trans/mir/rvalue.rs +++ b/src/librustc_trans/mir/rvalue.rs @@ -35,11 +35,11 @@ use super::operand::{OperandRef, OperandValue}; use super::lvalue::LvalueRef; impl<'a, 'tcx> MirContext<'a, 'tcx> { - pub fn trans_rvalue(&mut self, - bcx: Builder<'a, 'tcx>, - dest: LvalueRef<'tcx>, - rvalue: &mir::Rvalue<'tcx>) - -> Builder<'a, 'tcx> + pub(crate) fn trans_rvalue(&mut self, + bcx: Builder<'a, 'tcx>, + dest: LvalueRef<'tcx>, + rvalue: &mir::Rvalue<'tcx>) + -> Builder<'a, 'tcx> { debug!("trans_rvalue(dest.llval={:?}, rvalue={:?})", Value(dest.llval), rvalue); @@ -164,10 +164,10 @@ impl<'a, 'tcx> MirContext<'a, 'tcx> { } } - pub fn trans_rvalue_operand(&mut self, - bcx: Builder<'a, 'tcx>, - rvalue: &mir::Rvalue<'tcx>) - -> (Builder<'a, 'tcx>, OperandRef<'tcx>) + pub(crate) fn trans_rvalue_operand(&mut self, + bcx: Builder<'a, 'tcx>, + rvalue: &mir::Rvalue<'tcx>) + -> (Builder<'a, 'tcx>, OperandRef<'tcx>) { assert!(self.rvalue_creates_operand(rvalue), "cannot trans {:?} to operand", rvalue); @@ -482,12 +482,12 @@ impl<'a, 'tcx> MirContext<'a, 'tcx> { } } - pub fn trans_scalar_binop(&mut self, - bcx: &Builder<'a, 'tcx>, - op: mir::BinOp, - lhs: ValueRef, - rhs: ValueRef, - input_ty: Ty<'tcx>) -> ValueRef { + pub(crate) fn trans_scalar_binop(&mut self, + bcx: &Builder<'a, 'tcx>, + op: mir::BinOp, + lhs: ValueRef, + rhs: ValueRef, + input_ty: Ty<'tcx>) -> ValueRef { let is_float = input_ty.is_fp(); let is_signed = input_ty.is_signed(); let is_nil = input_ty.is_nil(); @@ -558,15 +558,15 @@ impl<'a, 'tcx> MirContext<'a, 'tcx> { } } - pub fn trans_fat_ptr_binop(&mut self, - bcx: &Builder<'a, 'tcx>, - op: mir::BinOp, - lhs_addr: ValueRef, - lhs_extra: ValueRef, - rhs_addr: ValueRef, - rhs_extra: ValueRef, - _input_ty: Ty<'tcx>) - -> ValueRef { + pub(crate) fn trans_fat_ptr_binop(&mut self, + bcx: &Builder<'a, 'tcx>, + op: mir::BinOp, + lhs_addr: ValueRef, + lhs_extra: ValueRef, + rhs_addr: ValueRef, + rhs_extra: ValueRef, + _input_ty: Ty<'tcx>) + -> ValueRef { match op { mir::BinOp::Eq => { bcx.and( @@ -605,12 +605,12 @@ impl<'a, 'tcx> MirContext<'a, 'tcx> { } } - pub fn trans_scalar_checked_binop(&mut self, - bcx: &Builder<'a, 'tcx>, - op: mir::BinOp, - lhs: ValueRef, - rhs: ValueRef, - input_ty: Ty<'tcx>) -> OperandValue { + pub(crate) fn trans_scalar_checked_binop(&mut self, + bcx: &Builder<'a, 'tcx>, + op: mir::BinOp, + lhs: ValueRef, + rhs: ValueRef, + input_ty: Ty<'tcx>) -> OperandValue { // This case can currently arise only from functions marked // with #[rustc_inherit_overflow_checks] and inlined from // another crate (mostly core::num generic/#[inline] fns), @@ -662,7 +662,7 @@ impl<'a, 'tcx> MirContext<'a, 'tcx> { OperandValue::Pair(val, of) } - pub fn rvalue_creates_operand(&self, rvalue: &mir::Rvalue<'tcx>) -> bool { + pub(crate) fn rvalue_creates_operand(&self, rvalue: &mir::Rvalue<'tcx>) -> bool { match *rvalue { mir::Rvalue::Ref(..) | mir::Rvalue::Len(..) | diff --git a/src/librustc_trans/mir/statement.rs b/src/librustc_trans/mir/statement.rs index 170a76a49497b..111b2e7d6e834 100644 --- a/src/librustc_trans/mir/statement.rs +++ b/src/librustc_trans/mir/statement.rs @@ -20,10 +20,10 @@ use super::LocalRef; use super::super::adt; impl<'a, 'tcx> MirContext<'a, 'tcx> { - pub fn trans_statement(&mut self, - bcx: Builder<'a, 'tcx>, - statement: &mir::Statement<'tcx>) - -> Builder<'a, 'tcx> { + pub(crate) fn trans_statement(&mut self, + bcx: Builder<'a, 'tcx>, + statement: &mir::Statement<'tcx>) + -> Builder<'a, 'tcx> { debug!("trans_statement(statement={:?})", statement); self.set_debug_loc(&bcx, statement.source_info); diff --git a/src/librustc_trans/monomorphize.rs b/src/librustc_trans/monomorphize.rs index 1f6a262162d39..8251459c3730e 100644 --- a/src/librustc_trans/monomorphize.rs +++ b/src/librustc_trans/monomorphize.rs @@ -21,7 +21,7 @@ use rustc::ty::{self, Ty, TyCtxt}; use syntax::codemap::DUMMY_SP; -pub use rustc::ty::Instance; +pub(crate) use rustc::ty::Instance; fn fn_once_adapter_instance<'a, 'tcx>( tcx: TyCtxt<'a, 'tcx, 'tcx>, @@ -85,7 +85,7 @@ fn needs_fn_once_adapter_shim(actual_closure_kind: ty::ClosureKind, } } -pub fn resolve_closure<'a, 'tcx> ( +pub(crate) fn resolve_closure<'a, 'tcx> ( scx: &SharedCrateContext<'a, 'tcx>, def_id: DefId, substs: ty::ClosureSubsts<'tcx>, @@ -151,7 +151,7 @@ fn resolve_associated_item<'a, 'tcx>( /// The point where linking happens. Resolve a (def_id, substs) /// pair to an instance. -pub fn resolve<'a, 'tcx>( +pub(crate) fn resolve<'a, 'tcx>( scx: &SharedCrateContext<'a, 'tcx>, def_id: DefId, substs: &'tcx Substs<'tcx> @@ -197,7 +197,7 @@ pub fn resolve<'a, 'tcx>( result } -pub fn resolve_drop_in_place<'a, 'tcx>( +pub(crate) fn resolve_drop_in_place<'a, 'tcx>( scx: &SharedCrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> ty::Instance<'tcx> @@ -207,10 +207,10 @@ pub fn resolve_drop_in_place<'a, 'tcx>( resolve(scx, def_id, substs) } -pub fn custom_coerce_unsize_info<'scx, 'tcx>(scx: &SharedCrateContext<'scx, 'tcx>, - source_ty: Ty<'tcx>, - target_ty: Ty<'tcx>) - -> CustomCoerceUnsized { +pub(crate) fn custom_coerce_unsize_info<'scx, 'tcx>(scx: &SharedCrateContext<'scx, 'tcx>, + source_ty: Ty<'tcx>, + target_ty: Ty<'tcx>) + -> CustomCoerceUnsized { let trait_ref = ty::Binder(ty::TraitRef { def_id: scx.tcx().lang_items.coerce_unsized_trait().unwrap(), substs: scx.tcx().mk_substs_trait(source_ty, &[target_ty]) @@ -227,10 +227,10 @@ pub fn custom_coerce_unsize_info<'scx, 'tcx>(scx: &SharedCrateContext<'scx, 'tcx } /// Returns the normalized type of a struct field -pub fn field_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - param_substs: &Substs<'tcx>, - f: &'tcx ty::FieldDef) - -> Ty<'tcx> +pub(crate) fn field_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, + param_substs: &Substs<'tcx>, + f: &'tcx ty::FieldDef) + -> Ty<'tcx> { tcx.normalize_associated_type(&f.ty(tcx, param_substs)) } diff --git a/src/librustc_trans/partitioning.rs b/src/librustc_trans/partitioning.rs index 7518948323b8b..acb327efdb988 100644 --- a/src/librustc_trans/partitioning.rs +++ b/src/librustc_trans/partitioning.rs @@ -121,7 +121,7 @@ use syntax::ast::NodeId; use syntax::symbol::{Symbol, InternedString}; use trans_item::{TransItem, InstantiationMode}; -pub enum PartitioningStrategy { +pub(crate) enum PartitioningStrategy { /// Generate one codegen unit per source-level module. PerModule, @@ -129,7 +129,7 @@ pub enum PartitioningStrategy { FixedUnitCount(usize) } -pub struct CodegenUnit<'tcx> { +pub(crate) struct CodegenUnit<'tcx> { /// A name for this CGU. Incremental compilation requires that /// name be unique amongst **all** crates. Therefore, it should /// contain something unique to this crate (e.g., a module path) @@ -140,43 +140,43 @@ pub struct CodegenUnit<'tcx> { } impl<'tcx> CodegenUnit<'tcx> { - pub fn new(name: InternedString, - items: FxHashMap, (llvm::Linkage, llvm::Visibility)>) - -> Self { + pub(crate) fn new(name: InternedString, + items: FxHashMap, (llvm::Linkage, llvm::Visibility)>) + -> Self { CodegenUnit { name, items, } } - pub fn empty(name: InternedString) -> Self { + pub(crate) fn empty(name: InternedString) -> Self { Self::new(name, FxHashMap()) } - pub fn contains_item(&self, item: &TransItem<'tcx>) -> bool { + pub(crate) fn contains_item(&self, item: &TransItem<'tcx>) -> bool { self.items.contains_key(item) } - pub fn name(&self) -> &str { + pub(crate) fn name(&self) -> &str { &self.name } - pub fn items(&self) -> &FxHashMap, (llvm::Linkage, llvm::Visibility)> { + pub(crate) fn items(&self) -> &FxHashMap, (llvm::Linkage, llvm::Visibility)> { &self.items } - pub fn work_product_id(&self) -> WorkProductId { + pub(crate) fn work_product_id(&self) -> WorkProductId { WorkProductId::from_cgu_name(self.name()) } - pub fn work_product_dep_node(&self) -> DepNode { + pub(crate) fn work_product_dep_node(&self) -> DepNode { self.work_product_id().to_dep_node() } - pub fn compute_symbol_name_hash<'a>(&self, - scx: &SharedCrateContext<'a, 'tcx>, - exported_symbols: &ExportedSymbols) - -> u64 { + pub(crate) fn compute_symbol_name_hash<'a>(&self, + scx: &SharedCrateContext<'a, 'tcx>, + exported_symbols: &ExportedSymbols) + -> u64 { let mut state = IchHasher::new(); let exported_symbols = exported_symbols.local_exports(); let all_items = self.items_in_deterministic_order(scx.tcx()); @@ -201,14 +201,14 @@ impl<'tcx> CodegenUnit<'tcx> { state.finish().to_smaller_hash() } - pub fn items_in_deterministic_order<'a>(&self, - tcx: TyCtxt<'a, 'tcx, 'tcx>) - -> Vec<(TransItem<'tcx>, - (llvm::Linkage, llvm::Visibility))> { + pub(crate) fn items_in_deterministic_order<'a>(&self, + tcx: TyCtxt<'a, 'tcx, 'tcx>) + -> Vec<(TransItem<'tcx>, + (llvm::Linkage, llvm::Visibility))> { // The codegen tests rely on items being process in the same order as // they appear in the file, so for local items, we sort by node_id first #[derive(PartialEq, Eq, PartialOrd, Ord)] - pub struct ItemSortKey(Option, ty::SymbolName); + pub(crate) struct ItemSortKey(Option, ty::SymbolName); fn item_sort_key<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item: TransItem<'tcx>) -> ItemSortKey { @@ -234,12 +234,12 @@ impl<'tcx> CodegenUnit<'tcx> { // Anything we can't find a proper codegen unit for goes into this. const FALLBACK_CODEGEN_UNIT: &'static str = "__rustc_fallback_codegen_unit"; -pub fn partition<'a, 'tcx, I>(scx: &SharedCrateContext<'a, 'tcx>, - trans_items: I, - strategy: PartitioningStrategy, - inlining_map: &InliningMap<'tcx>, - exported_symbols: &ExportedSymbols) - -> Vec> +pub(crate) fn partition<'a, 'tcx, I>(scx: &SharedCrateContext<'a, 'tcx>, + trans_items: I, + strategy: PartitioningStrategy, + inlining_map: &InliningMap<'tcx>, + exported_symbols: &ExportedSymbols) + -> Vec> where I: Iterator> { let tcx = scx.tcx(); diff --git a/src/librustc_trans/symbol_names_test.rs b/src/librustc_trans/symbol_names_test.rs index d96757be9f3a5..cfa3e3ceeec18 100644 --- a/src/librustc_trans/symbol_names_test.rs +++ b/src/librustc_trans/symbol_names_test.rs @@ -24,7 +24,7 @@ use monomorphize::Instance; const SYMBOL_NAME: &'static str = "rustc_symbol_name"; const ITEM_PATH: &'static str = "rustc_item_path"; -pub fn report_symbol_names<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { +pub(crate) fn report_symbol_names<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { // if the `rustc_attrs` feature is not enabled, then the // attributes we are interested in cannot be present anyway, so // skip the walk. diff --git a/src/librustc_trans/trans_item.rs b/src/librustc_trans/trans_item.rs index b94fd13c3a4a2..ea4561e06ff3d 100644 --- a/src/librustc_trans/trans_item.rs +++ b/src/librustc_trans/trans_item.rs @@ -37,7 +37,7 @@ use std::fmt::Write; use std::iter; #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)] -pub enum TransItem<'tcx> { +pub(crate) enum TransItem<'tcx> { Fn(Instance<'tcx>), Static(NodeId), GlobalAsm(NodeId), @@ -45,7 +45,7 @@ pub enum TransItem<'tcx> { /// Describes how a translation item will be instantiated in object files. #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)] -pub enum InstantiationMode { +pub(crate) enum InstantiationMode { /// There will be exactly one instance of the given TransItem. It will have /// external linkage so that it can be linked to from other codegen units. GloballyShared, @@ -57,7 +57,7 @@ pub enum InstantiationMode { impl<'a, 'tcx> TransItem<'tcx> { - pub fn define(&self, ccx: &CrateContext<'a, 'tcx>) { + pub(crate) fn define(&self, ccx: &CrateContext<'a, 'tcx>) { debug!("BEGIN IMPLEMENTING '{} ({})' in cgu {}", self.to_string(ccx.tcx()), self.to_raw_string(), @@ -97,10 +97,10 @@ impl<'a, 'tcx> TransItem<'tcx> { ccx.codegen_unit().name()); } - pub fn predefine(&self, - ccx: &CrateContext<'a, 'tcx>, - linkage: llvm::Linkage, - visibility: llvm::Visibility) { + pub(crate) fn predefine(&self, + ccx: &CrateContext<'a, 'tcx>, + linkage: llvm::Linkage, + visibility: llvm::Visibility) { debug!("BEGIN PREDEFINING '{} ({})' in cgu {}", self.to_string(ccx.tcx()), self.to_raw_string(), @@ -193,7 +193,7 @@ impl<'a, 'tcx> TransItem<'tcx> { ccx.instances().borrow_mut().insert(instance, lldecl); } - pub fn symbol_name(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> ty::SymbolName { + pub(crate) fn symbol_name(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> ty::SymbolName { match *self { TransItem::Fn(instance) => tcx.symbol_name(instance), TransItem::Static(node_id) => { @@ -209,7 +209,7 @@ impl<'a, 'tcx> TransItem<'tcx> { } } - pub fn local_span(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option { + pub(crate) fn local_span(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option { match *self { TransItem::Fn(Instance { def, .. }) => { tcx.hir.as_local_node_id(def.def_id()) @@ -221,9 +221,9 @@ impl<'a, 'tcx> TransItem<'tcx> { }.map(|node_id| tcx.hir.span(node_id)) } - pub fn instantiation_mode(&self, - tcx: TyCtxt<'a, 'tcx, 'tcx>) - -> InstantiationMode { + pub(crate) fn instantiation_mode(&self, + tcx: TyCtxt<'a, 'tcx, 'tcx>) + -> InstantiationMode { match *self { TransItem::Fn(ref instance) => { if self.explicit_linkage(tcx).is_none() && @@ -239,7 +239,7 @@ impl<'a, 'tcx> TransItem<'tcx> { } } - pub fn is_generic_fn(&self) -> bool { + pub(crate) fn is_generic_fn(&self) -> bool { match *self { TransItem::Fn(ref instance) => { instance.substs.types().next().is_some() @@ -249,7 +249,7 @@ impl<'a, 'tcx> TransItem<'tcx> { } } - pub fn explicit_linkage(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option { + pub(crate) fn explicit_linkage(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option { let def_id = match *self { TransItem::Fn(ref instance) => instance.def_id(), TransItem::Static(node_id) => tcx.hir.local_def_id(node_id), @@ -298,7 +298,7 @@ impl<'a, 'tcx> TransItem<'tcx> { /// Similarly, if a vtable method has such a signature, and therefore can't /// be used, we can just not emit it and have a placeholder (a null pointer, /// which will never be accessed) in its place. - pub fn is_instantiable(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> bool { + pub(crate) fn is_instantiable(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> bool { debug!("is_instantiable({:?})", self); let (def_id, substs) = match *self { TransItem::Fn(ref instance) => (instance.def_id(), instance.substs), @@ -311,7 +311,7 @@ impl<'a, 'tcx> TransItem<'tcx> { traits::normalize_and_test_predicates(tcx, predicates) } - pub fn to_string(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> String { + pub(crate) fn to_string(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> String { let hir_map = &tcx.hir; return match *self { @@ -340,7 +340,7 @@ impl<'a, 'tcx> TransItem<'tcx> { } } - pub fn to_raw_string(&self) -> String { + pub(crate) fn to_raw_string(&self) -> String { match *self { TransItem::Fn(instance) => { format!("Fn({:?}, {})", @@ -372,17 +372,17 @@ impl<'a, 'tcx> TransItem<'tcx> { /// Same as `unique_type_name()` but with the result pushed onto the given /// `output` parameter. -pub struct DefPathBasedNames<'a, 'tcx: 'a> { +pub(crate) struct DefPathBasedNames<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx>, omit_disambiguators: bool, omit_local_crate_name: bool, } impl<'a, 'tcx> DefPathBasedNames<'a, 'tcx> { - pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, - omit_disambiguators: bool, - omit_local_crate_name: bool) - -> Self { + pub(crate) fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, + omit_disambiguators: bool, + omit_local_crate_name: bool) + -> Self { DefPathBasedNames { tcx: tcx, omit_disambiguators: omit_disambiguators, @@ -390,7 +390,7 @@ impl<'a, 'tcx> DefPathBasedNames<'a, 'tcx> { } } - pub fn push_type_name(&self, t: Ty<'tcx>, output: &mut String) { + pub(crate) fn push_type_name(&self, t: Ty<'tcx>, output: &mut String) { match t.sty { ty::TyBool => output.push_str("bool"), ty::TyChar => output.push_str("char"), @@ -521,9 +521,9 @@ impl<'a, 'tcx> DefPathBasedNames<'a, 'tcx> { } } - pub fn push_def_path(&self, - def_id: DefId, - output: &mut String) { + pub(crate) fn push_def_path(&self, + def_id: DefId, + output: &mut String) { let def_path = self.tcx.def_path(def_id); // some_crate:: @@ -581,9 +581,9 @@ impl<'a, 'tcx> DefPathBasedNames<'a, 'tcx> { output.push('>'); } - pub fn push_instance_as_string(&self, - instance: Instance<'tcx>, - output: &mut String) { + pub(crate) fn push_instance_as_string(&self, + instance: Instance<'tcx>, + output: &mut String) { self.push_def_path(instance.def_id(), output); self.push_type_params(instance.substs, iter::empty(), output); } diff --git a/src/librustc_trans/tvec.rs b/src/librustc_trans/tvec.rs index 4216a73a8dd85..dcfbe5f2e3df8 100644 --- a/src/librustc_trans/tvec.rs +++ b/src/librustc_trans/tvec.rs @@ -14,7 +14,7 @@ use llvm::{BasicBlockRef, ValueRef}; use common::*; use rustc::ty::Ty; -pub fn slice_for_each<'a, 'tcx, F>( +pub(crate) fn slice_for_each<'a, 'tcx, F>( bcx: &Builder<'a, 'tcx>, data_ptr: ValueRef, unit_ty: Ty<'tcx>, diff --git a/src/librustc_trans/type_.rs b/src/librustc_trans/type_.rs index d70afc0cce5a3..d80afcbeb0d42 100644 --- a/src/librustc_trans/type_.rs +++ b/src/librustc_trans/type_.rs @@ -28,7 +28,7 @@ use libc::c_uint; #[derive(Clone, Copy, PartialEq)] #[repr(C)] -pub struct Type { +pub(crate) struct Type { rf: TypeRef } @@ -47,91 +47,91 @@ macro_rules! ty { /// Wrapper for LLVM TypeRef impl Type { #[inline(always)] - pub fn from_ref(r: TypeRef) -> Type { + pub(crate) fn from_ref(r: TypeRef) -> Type { Type { rf: r } } #[inline(always)] // So it doesn't kill --opt-level=0 builds of the compiler - pub fn to_ref(&self) -> TypeRef { + pub(crate) fn to_ref(&self) -> TypeRef { self.rf } - pub fn to_ref_slice(slice: &[Type]) -> &[TypeRef] { + pub(crate) fn to_ref_slice(slice: &[Type]) -> &[TypeRef] { unsafe { mem::transmute(slice) } } - pub fn void(ccx: &CrateContext) -> Type { + pub(crate) fn void(ccx: &CrateContext) -> Type { ty!(llvm::LLVMVoidTypeInContext(ccx.llcx())) } - pub fn nil(ccx: &CrateContext) -> Type { + pub(crate) fn nil(ccx: &CrateContext) -> Type { Type::empty_struct(ccx) } - pub fn metadata(ccx: &CrateContext) -> Type { + pub(crate) fn metadata(ccx: &CrateContext) -> Type { ty!(llvm::LLVMRustMetadataTypeInContext(ccx.llcx())) } - pub fn i1(ccx: &CrateContext) -> Type { + pub(crate) fn i1(ccx: &CrateContext) -> Type { ty!(llvm::LLVMInt1TypeInContext(ccx.llcx())) } - pub fn i8(ccx: &CrateContext) -> Type { + pub(crate) fn i8(ccx: &CrateContext) -> Type { ty!(llvm::LLVMInt8TypeInContext(ccx.llcx())) } - pub fn i8_llcx(llcx: ContextRef) -> Type { + pub(crate) fn i8_llcx(llcx: ContextRef) -> Type { ty!(llvm::LLVMInt8TypeInContext(llcx)) } - pub fn i16(ccx: &CrateContext) -> Type { + pub(crate) fn i16(ccx: &CrateContext) -> Type { ty!(llvm::LLVMInt16TypeInContext(ccx.llcx())) } - pub fn i32(ccx: &CrateContext) -> Type { + pub(crate) fn i32(ccx: &CrateContext) -> Type { ty!(llvm::LLVMInt32TypeInContext(ccx.llcx())) } - pub fn i64(ccx: &CrateContext) -> Type { + pub(crate) fn i64(ccx: &CrateContext) -> Type { ty!(llvm::LLVMInt64TypeInContext(ccx.llcx())) } - pub fn i128(ccx: &CrateContext) -> Type { + pub(crate) fn i128(ccx: &CrateContext) -> Type { ty!(llvm::LLVMIntTypeInContext(ccx.llcx(), 128)) } // Creates an integer type with the given number of bits, e.g. i24 - pub fn ix(ccx: &CrateContext, num_bits: u64) -> Type { + pub(crate) fn ix(ccx: &CrateContext, num_bits: u64) -> Type { ty!(llvm::LLVMIntTypeInContext(ccx.llcx(), num_bits as c_uint)) } - pub fn f32(ccx: &CrateContext) -> Type { + pub(crate) fn f32(ccx: &CrateContext) -> Type { ty!(llvm::LLVMFloatTypeInContext(ccx.llcx())) } - pub fn f64(ccx: &CrateContext) -> Type { + pub(crate) fn f64(ccx: &CrateContext) -> Type { ty!(llvm::LLVMDoubleTypeInContext(ccx.llcx())) } - pub fn bool(ccx: &CrateContext) -> Type { + pub(crate) fn bool(ccx: &CrateContext) -> Type { Type::i8(ccx) } - pub fn char(ccx: &CrateContext) -> Type { + pub(crate) fn char(ccx: &CrateContext) -> Type { Type::i32(ccx) } - pub fn i8p(ccx: &CrateContext) -> Type { + pub(crate) fn i8p(ccx: &CrateContext) -> Type { Type::i8(ccx).ptr_to() } - pub fn i8p_llcx(llcx: ContextRef) -> Type { + pub(crate) fn i8p_llcx(llcx: ContextRef) -> Type { Type::i8_llcx(llcx).ptr_to() } - pub fn int(ccx: &CrateContext) -> Type { + pub(crate) fn int(ccx: &CrateContext) -> Type { match &ccx.tcx().sess.target.target.target_pointer_width[..] { "16" => Type::i16(ccx), "32" => Type::i32(ccx), @@ -140,7 +140,7 @@ impl Type { } } - pub fn int_from_ty(ccx: &CrateContext, t: ast::IntTy) -> Type { + pub(crate) fn int_from_ty(ccx: &CrateContext, t: ast::IntTy) -> Type { match t { ast::IntTy::Is => ccx.int_type(), ast::IntTy::I8 => Type::i8(ccx), @@ -151,7 +151,7 @@ impl Type { } } - pub fn uint_from_ty(ccx: &CrateContext, t: ast::UintTy) -> Type { + pub(crate) fn uint_from_ty(ccx: &CrateContext, t: ast::UintTy) -> Type { match t { ast::UintTy::Us => ccx.int_type(), ast::UintTy::U8 => Type::i8(ccx), @@ -162,70 +162,70 @@ impl Type { } } - pub fn float_from_ty(ccx: &CrateContext, t: ast::FloatTy) -> Type { + pub(crate) fn float_from_ty(ccx: &CrateContext, t: ast::FloatTy) -> Type { match t { ast::FloatTy::F32 => Type::f32(ccx), ast::FloatTy::F64 => Type::f64(ccx), } } - pub fn func(args: &[Type], ret: &Type) -> Type { + pub(crate) fn func(args: &[Type], ret: &Type) -> Type { let slice: &[TypeRef] = Type::to_ref_slice(args); ty!(llvm::LLVMFunctionType(ret.to_ref(), slice.as_ptr(), args.len() as c_uint, False)) } - pub fn variadic_func(args: &[Type], ret: &Type) -> Type { + pub(crate) fn variadic_func(args: &[Type], ret: &Type) -> Type { let slice: &[TypeRef] = Type::to_ref_slice(args); ty!(llvm::LLVMFunctionType(ret.to_ref(), slice.as_ptr(), args.len() as c_uint, True)) } - pub fn struct_(ccx: &CrateContext, els: &[Type], packed: bool) -> Type { + pub(crate) fn struct_(ccx: &CrateContext, els: &[Type], packed: bool) -> Type { let els: &[TypeRef] = Type::to_ref_slice(els); ty!(llvm::LLVMStructTypeInContext(ccx.llcx(), els.as_ptr(), els.len() as c_uint, packed as Bool)) } - pub fn named_struct(ccx: &CrateContext, name: &str) -> Type { + pub(crate) fn named_struct(ccx: &CrateContext, name: &str) -> Type { let name = CString::new(name).unwrap(); ty!(llvm::LLVMStructCreateNamed(ccx.llcx(), name.as_ptr())) } - pub fn empty_struct(ccx: &CrateContext) -> Type { + pub(crate) fn empty_struct(ccx: &CrateContext) -> Type { Type::struct_(ccx, &[], false) } - pub fn array(ty: &Type, len: u64) -> Type { + pub(crate) fn array(ty: &Type, len: u64) -> Type { ty!(llvm::LLVMRustArrayType(ty.to_ref(), len)) } - pub fn vector(ty: &Type, len: u64) -> Type { + pub(crate) fn vector(ty: &Type, len: u64) -> Type { ty!(llvm::LLVMVectorType(ty.to_ref(), len as c_uint)) } - pub fn vec(ccx: &CrateContext, ty: &Type) -> Type { + pub(crate) fn vec(ccx: &CrateContext, ty: &Type) -> Type { Type::struct_(ccx, &[Type::array(ty, 0), Type::int(ccx)], false) } - pub fn opaque_vec(ccx: &CrateContext) -> Type { + pub(crate) fn opaque_vec(ccx: &CrateContext) -> Type { Type::vec(ccx, &Type::i8(ccx)) } - pub fn vtable_ptr(ccx: &CrateContext) -> Type { + pub(crate) fn vtable_ptr(ccx: &CrateContext) -> Type { Type::func(&[Type::i8p(ccx)], &Type::void(ccx)).ptr_to().ptr_to() } - pub fn kind(&self) -> TypeKind { + pub(crate) fn kind(&self) -> TypeKind { unsafe { llvm::LLVMRustGetTypeKind(self.to_ref()) } } - pub fn set_struct_body(&mut self, els: &[Type], packed: bool) { + pub(crate) fn set_struct_body(&mut self, els: &[Type], packed: bool) { let slice: &[TypeRef] = Type::to_ref_slice(els); unsafe { llvm::LLVMStructSetBody(self.to_ref(), slice.as_ptr(), @@ -233,43 +233,24 @@ impl Type { } } - pub fn ptr_to(&self) -> Type { + pub(crate) fn ptr_to(&self) -> Type { ty!(llvm::LLVMPointerType(self.to_ref(), 0)) } - pub fn is_aggregate(&self) -> bool { - match self.kind() { - TypeKind::Struct | TypeKind::Array => true, - _ => false - } - } - - pub fn is_packed(&self) -> bool { - unsafe { - llvm::LLVMIsPackedStruct(self.to_ref()) == True - } - } - - pub fn element_type(&self) -> Type { + pub(crate) fn element_type(&self) -> Type { unsafe { Type::from_ref(llvm::LLVMGetElementType(self.to_ref())) } } /// Return the number of elements in `self` if it is a LLVM vector type. - pub fn vector_length(&self) -> usize { + pub(crate) fn vector_length(&self) -> usize { unsafe { llvm::LLVMGetVectorSize(self.to_ref()) as usize } } - pub fn array_length(&self) -> usize { - unsafe { - llvm::LLVMGetArrayLength(self.to_ref()) as usize - } - } - - pub fn field_types(&self) -> Vec { + pub(crate) fn field_types(&self) -> Vec { unsafe { let n_elts = llvm::LLVMCountStructElementTypes(self.to_ref()) as usize; if n_elts == 0 { @@ -282,11 +263,7 @@ impl Type { } } - pub fn return_type(&self) -> Type { - ty!(llvm::LLVMGetReturnType(self.to_ref())) - } - - pub fn func_params(&self) -> Vec { + pub(crate) fn func_params(&self) -> Vec { unsafe { let n_args = llvm::LLVMCountParamTypes(self.to_ref()) as usize; let mut args = vec![Type { rf: ptr::null_mut() }; n_args]; @@ -296,7 +273,7 @@ impl Type { } } - pub fn float_width(&self) -> usize { + pub(crate) fn float_width(&self) -> usize { match self.kind() { Float => 32, Double => 64, @@ -307,13 +284,13 @@ impl Type { } /// Retrieve the bit width of the integer type `self`. - pub fn int_width(&self) -> u64 { + pub(crate) fn int_width(&self) -> u64 { unsafe { llvm::LLVMGetIntTypeWidth(self.to_ref()) as u64 } } - pub fn from_integer(cx: &CrateContext, i: layout::Integer) -> Type { + pub(crate) fn from_integer(cx: &CrateContext, i: layout::Integer) -> Type { use rustc::ty::layout::Integer::*; match i { I1 => Type::i1(cx), @@ -324,13 +301,4 @@ impl Type { I128 => Type::i128(cx), } } - - pub fn from_primitive(ccx: &CrateContext, p: layout::Primitive) -> Type { - match p { - layout::Int(i) => Type::from_integer(ccx, i), - layout::F32 => Type::f32(ccx), - layout::F64 => Type::f64(ccx), - layout::Pointer => bug!("It is not possible to convert Pointer directly to Type.") - } - } } diff --git a/src/librustc_trans/type_of.rs b/src/librustc_trans/type_of.rs index 9f9126ba83a8f..3c689f9b71cea 100644 --- a/src/librustc_trans/type_of.rs +++ b/src/librustc_trans/type_of.rs @@ -19,7 +19,7 @@ use type_::Type; use syntax::ast; -pub fn fat_ptr_base_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> Type { +pub(crate) fn fat_ptr_base_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> Type { match ty.sty { ty::TyRef(_, ty::TypeAndMut { ty: t, .. }) | ty::TyRawPtr(ty::TypeAndMut { ty: t, .. }) if !ccx.shared().type_is_sized(t) => { @@ -32,7 +32,7 @@ pub fn fat_ptr_base_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> } } -pub fn unsized_info_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> Type { +pub(crate) fn unsized_info_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> Type { let unsized_part = ccx.tcx().struct_tail(ty); match unsized_part.sty { ty::TyStr | ty::TyArray(..) | ty::TySlice(_) => { @@ -44,7 +44,7 @@ pub fn unsized_info_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> } } -pub fn immediate_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { +pub(crate) fn immediate_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { if t.is_bool() { Type::i1(cx) } else { @@ -61,7 +61,7 @@ pub fn immediate_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> /// This is needed due to the treatment of immediate values, as a fat pointer /// is too large for it to be placed in SSA value (by our rules). /// For the raw type without far pointer indirection, see `in_memory_type_of`. -pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> Type { +pub(crate) fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> Type { let ty = if !cx.shared().type_is_sized(ty) { cx.tcx().mk_imm_ptr(ty) } else { @@ -81,7 +81,7 @@ pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> Type { /// of that field's type - this is useful for taking the address of /// that field and ensuring the struct has the right alignment. /// For the LLVM type of a value as a whole, see `type_of`. -pub fn in_memory_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { +pub(crate) fn in_memory_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { // Check the cache. if let Some(&llty) = cx.lltypes().borrow().get(&t) { return llty; @@ -207,15 +207,15 @@ pub fn in_memory_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> } impl<'a, 'tcx> CrateContext<'a, 'tcx> { - pub fn align_of(&self, ty: Ty<'tcx>) -> machine::llalign { + pub(crate) fn align_of(&self, ty: Ty<'tcx>) -> machine::llalign { self.layout_of(ty).align(self).abi() as machine::llalign } - pub fn size_of(&self, ty: Ty<'tcx>) -> machine::llsize { + pub(crate) fn size_of(&self, ty: Ty<'tcx>) -> machine::llsize { self.layout_of(ty).size(self).bytes() as machine::llsize } - pub fn over_align_of(&self, t: Ty<'tcx>) + pub(crate) fn over_align_of(&self, t: Ty<'tcx>) -> Option { let layout = self.layout_of(t); if let Some(align) = layout.over_align(&self.tcx().data_layout) { diff --git a/src/librustc_trans/value.rs b/src/librustc_trans/value.rs index 287ad87caacf9..203d103268f12 100644 --- a/src/librustc_trans/value.rs +++ b/src/librustc_trans/value.rs @@ -13,7 +13,7 @@ use llvm; use std::fmt; #[derive(Copy, Clone, PartialEq)] -pub struct Value(pub llvm::ValueRef); +pub(crate) struct Value(pub(crate) llvm::ValueRef); impl fmt::Debug for Value { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index bb6e478738aa2..1c9c45460fb95 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -34,7 +34,7 @@ use syntax::feature_gate::{GateIssue, emit_feature_err}; use syntax::symbol::Symbol; use syntax_pos::Span; -pub trait AstConv<'gcx, 'tcx> { +pub(crate) trait AstConv<'gcx, 'tcx> { fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>; /// Returns the set of bounds in scope for the type parameter with @@ -92,7 +92,7 @@ struct ConvertedBinding<'tcx> { const TRAIT_OBJECT_DUMMY_SELF: ty::TypeVariants<'static> = ty::TyInfer(ty::FreshTy(0)); impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { - pub fn ast_region_to_region(&self, + pub(crate) fn ast_region_to_region(&self, lifetime: &hir::Lifetime, def: Option<&ty::RegionParameterDef>) -> ty::Region<'tcx> @@ -146,7 +146,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`, /// returns an appropriate set of substitutions for this particular reference to `I`. - pub fn ast_path_substs_for_ty(&self, + pub(crate) fn ast_path_substs_for_ty(&self, span: Span, def_id: DefId, item_segment: &hir::PathSegment) @@ -363,7 +363,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { /// /// If the `projections` argument is `None`, then assoc type bindings like `Foo` /// are disallowed. Otherwise, they are pushed onto the vector given. - pub fn instantiate_mono_trait_ref(&self, + pub(crate) fn instantiate_mono_trait_ref(&self, trait_ref: &hir::TraitRef, self_ty: Ty<'tcx>) -> ty::TraitRef<'tcx> @@ -391,7 +391,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { } } - pub fn instantiate_poly_trait_ref(&self, + pub(crate) fn instantiate_poly_trait_ref(&self, ast_trait_ref: &hir::PolyTraitRef, self_ty: Ty<'tcx>, poly_projections: &mut Vec>) @@ -834,13 +834,13 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { // the whole path. // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type // parameter or Self. - pub fn associated_path_def_to_ty(&self, - ref_id: ast::NodeId, - span: Span, - ty: Ty<'tcx>, - ty_path_def: Def, - item_segment: &hir::PathSegment) - -> (Ty<'tcx>, Def) + pub(crate) fn associated_path_def_to_ty(&self, + ref_id: ast::NodeId, + span: Span, + ty: Ty<'tcx>, + ty_path_def: Def, + item_segment: &hir::PathSegment) + -> (Ty<'tcx>, Def) { let tcx = self.tcx(); let assoc_name = item_segment.name; @@ -949,7 +949,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { self.normalize_ty(span, tcx.mk_projection(item_def_id, trait_ref.substs)) } - pub fn prohibit_type_params(&self, segments: &[hir::PathSegment]) { + pub(crate) fn prohibit_type_params(&self, segments: &[hir::PathSegment]) { for segment in segments { if let hir::ParenthesizedParameters(_) = segment.parameters { self.prohibit_parenthesized_params(segment, false); @@ -977,7 +977,9 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { } } - pub fn prohibit_parenthesized_params(&self, segment: &hir::PathSegment, emit_error: bool) { + pub(crate) fn prohibit_parenthesized_params(&self, + segment: &hir::PathSegment, + emit_error: bool) { if let hir::ParenthesizedParameters(ref data) = segment.parameters { if emit_error { struct_span_err!(self.tcx().sess, data.span, E0214, @@ -992,18 +994,18 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { } } - pub fn prohibit_projection(&self, span: Span) { + pub(crate) fn prohibit_projection(&self, span: Span) { let mut err = struct_span_err!(self.tcx().sess, span, E0229, "associated type bindings are not allowed here"); err.span_label(span, "associated type not allowed here").emit(); } // Check a type Path and convert it to a Ty. - pub fn def_to_ty(&self, - opt_self_ty: Option>, - path: &hir::Path, - permit_variants: bool) - -> Ty<'tcx> { + pub(crate) fn def_to_ty(&self, + opt_self_ty: Option>, + path: &hir::Path, + permit_variants: bool) + -> Ty<'tcx> { let tcx = self.tcx(); debug!("base_def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})", @@ -1080,7 +1082,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { /// Parses the programmer's textual representation of a type into our /// internal notion of a type. - pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> { + pub(crate) fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> { debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})", ast_ty.id, ast_ty); @@ -1250,10 +1252,10 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { result_ty } - pub fn ty_of_arg(&self, - ty: &hir::Ty, - expected_ty: Option>) - -> Ty<'tcx> + pub(crate) fn ty_of_arg(&self, + ty: &hir::Ty, + expected_ty: Option>) + -> Ty<'tcx> { match ty.node { hir::TyInfer if expected_ty.is_some() => expected_ty.unwrap(), @@ -1262,11 +1264,11 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { } } - pub fn ty_of_fn(&self, - unsafety: hir::Unsafety, - abi: abi::Abi, - decl: &hir::FnDecl) - -> ty::PolyFnSig<'tcx> { + pub(crate) fn ty_of_fn(&self, + unsafety: hir::Unsafety, + abi: abi::Abi, + decl: &hir::FnDecl) + -> ty::PolyFnSig<'tcx> { debug!("ty_of_fn"); let input_tys: Vec = @@ -1288,7 +1290,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o { )) } - pub fn ty_of_closure(&self, + pub(crate) fn ty_of_closure(&self, unsafety: hir::Unsafety, decl: &hir::FnDecl, abi: abi::Abi, @@ -1493,15 +1495,15 @@ fn report_lifetime_number_error(tcx: TyCtxt, span: Span, number: usize, expected // A helper struct for conveniently grouping a set of bounds which we pass to // and return from functions in multiple places. #[derive(PartialEq, Eq, Clone, Debug)] -pub struct Bounds<'tcx> { - pub region_bounds: Vec>, - pub implicitly_sized: bool, - pub trait_bounds: Vec>, - pub projection_bounds: Vec>, +pub(crate) struct Bounds<'tcx> { + pub(crate) region_bounds: Vec>, + pub(crate) implicitly_sized: bool, + pub(crate) trait_bounds: Vec>, + pub(crate) projection_bounds: Vec>, } impl<'a, 'gcx, 'tcx> Bounds<'tcx> { - pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>) + pub(crate) fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>) -> Vec> { let mut vec = Vec::new(); @@ -1536,7 +1538,7 @@ impl<'a, 'gcx, 'tcx> Bounds<'tcx> { } } -pub enum ExplicitSelf<'tcx> { +pub(crate) enum ExplicitSelf<'tcx> { ByValue, ByReference(ty::Region<'tcx>, hir::Mutability), ByBox @@ -1571,9 +1573,9 @@ impl<'tcx> ExplicitSelf<'tcx> { /// example, the impl type has one modifier, but the method /// type has two, so we end up with /// ExplicitSelf::ByReference. - pub fn determine(untransformed_self_ty: Ty<'tcx>, - self_arg_ty: Ty<'tcx>) - -> ExplicitSelf<'tcx> { + pub(crate) fn determine(untransformed_self_ty: Ty<'tcx>, + self_arg_ty: Ty<'tcx>) + -> ExplicitSelf<'tcx> { fn count_modifiers(ty: Ty) -> usize { match ty.sty { ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1, diff --git a/src/librustc_typeck/check/_match.rs b/src/librustc_typeck/check/_match.rs index 68726a7b1c4eb..8049fd73d6725 100644 --- a/src/librustc_typeck/check/_match.rs +++ b/src/librustc_typeck/check/_match.rs @@ -27,7 +27,7 @@ use syntax::ptr::P; use syntax_pos::Span; impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { - pub fn check_pat(&self, pat: &'gcx hir::Pat, expected: Ty<'tcx>) { + pub(crate) fn check_pat(&self, pat: &'gcx hir::Pat, expected: Ty<'tcx>) { self.check_pat_arg(pat, expected, false); } @@ -35,7 +35,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { /// *outermost* pattern in an argument (e.g., in `fn foo(&x: /// &u32)`, it is true for the `&x` pattern but not `x`). This is /// used to tailor error reporting. - pub fn check_pat_arg(&self, pat: &'gcx hir::Pat, expected: Ty<'tcx>, is_arg: bool) { + pub(crate) fn check_pat_arg(&self, pat: &'gcx hir::Pat, expected: Ty<'tcx>, is_arg: bool) { let tcx = self.tcx; debug!("check_pat(pat={:?},expected={:?},is_arg={})", pat, expected, is_arg); @@ -370,7 +370,8 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // subtyping. } - pub fn check_dereferencable(&self, span: Span, expected: Ty<'tcx>, inner: &hir::Pat) -> bool { + pub(crate) fn check_dereferencable(&self, span: Span, expected: Ty<'tcx>, inner: &hir::Pat) + -> bool { if let PatKind::Binding(..) = inner.node { if let Some(mt) = self.shallow_resolve(expected).builtin_deref(true, ty::NoPreference) { if let ty::TyDynamic(..) = mt.ty.sty { @@ -388,12 +389,12 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { true } - pub fn check_match(&self, - expr: &'gcx hir::Expr, - discrim: &'gcx hir::Expr, - arms: &'gcx [hir::Arm], - expected: Expectation<'tcx>, - match_src: hir::MatchSource) -> Ty<'tcx> { + pub(crate) fn check_match(&self, + expr: &'gcx hir::Expr, + discrim: &'gcx hir::Expr, + arms: &'gcx [hir::Arm], + expected: Expectation<'tcx>, + match_src: hir::MatchSource) -> Ty<'tcx> { let tcx = self.tcx; // Not entirely obvious: if matches may create ref bindings, we diff --git a/src/librustc_typeck/check/autoderef.rs b/src/librustc_typeck/check/autoderef.rs index 6aac9dc42ee02..119f06cb61187 100644 --- a/src/librustc_typeck/check/autoderef.rs +++ b/src/librustc_typeck/check/autoderef.rs @@ -31,7 +31,7 @@ enum AutoderefKind { Overloaded, } -pub struct Autoderef<'a, 'gcx: 'tcx, 'tcx: 'a> { +pub(crate) struct Autoderef<'a, 'gcx: 'tcx, 'tcx: 'a> { fcx: &'a FnCtxt<'a, 'gcx, 'tcx>, steps: Vec<(Ty<'tcx>, AutoderefKind)>, cur_ty: Ty<'tcx>, @@ -144,27 +144,27 @@ impl<'a, 'gcx, 'tcx> Autoderef<'a, 'gcx, 'tcx> { /// Returns the final type, generating an error if it is an /// unresolved inference variable. - pub fn unambiguous_final_ty(&self) -> Ty<'tcx> { + pub(crate) fn unambiguous_final_ty(&self) -> Ty<'tcx> { self.fcx.structurally_resolved_type(self.span, self.cur_ty) } /// Returns the final type we ended up with, which may well be an /// inference variable (we will resolve it first, if possible). - pub fn maybe_ambiguous_final_ty(&self) -> Ty<'tcx> { + pub(crate) fn maybe_ambiguous_final_ty(&self) -> Ty<'tcx> { self.fcx.resolve_type_vars_if_possible(&self.cur_ty) } - pub fn step_count(&self) -> usize { + pub(crate) fn step_count(&self) -> usize { self.steps.len() } /// Returns the adjustment steps. - pub fn adjust_steps(&self, pref: LvaluePreference) + pub(crate) fn adjust_steps(&self, pref: LvaluePreference) -> Vec> { self.fcx.register_infer_ok_obligations(self.adjust_steps_as_infer_ok(pref)) } - pub fn adjust_steps_as_infer_ok(&self, pref: LvaluePreference) + pub(crate) fn adjust_steps_as_infer_ok(&self, pref: LvaluePreference) -> InferOk<'tcx, Vec>> { let mut obligations = vec![]; let targets = self.steps.iter().skip(1).map(|&(ty, _)| ty) @@ -199,18 +199,18 @@ impl<'a, 'gcx, 'tcx> Autoderef<'a, 'gcx, 'tcx> { } } - pub fn finalize(self) { + pub(crate) fn finalize(self) { let fcx = self.fcx; fcx.register_predicates(self.into_obligations()); } - pub fn into_obligations(self) -> Vec> { + pub(crate) fn into_obligations(self) -> Vec> { self.obligations } } impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { - pub fn autoderef(&'a self, span: Span, base_ty: Ty<'tcx>) -> Autoderef<'a, 'gcx, 'tcx> { + pub(crate) fn autoderef(&'a self, span: Span, base_ty: Ty<'tcx>) -> Autoderef<'a, 'gcx, 'tcx> { Autoderef { fcx: self, steps: vec![], @@ -221,11 +221,11 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } } - pub fn try_overloaded_deref(&self, - span: Span, - base_ty: Ty<'tcx>, - pref: LvaluePreference) - -> Option>> { + pub(crate) fn try_overloaded_deref(&self, + span: Span, + base_ty: Ty<'tcx>, + pref: LvaluePreference) + -> Option>> { self.try_overloaded_lvalue_op(span, base_ty, &[], pref, LvalueOp::Deref) } } diff --git a/src/librustc_typeck/check/callee.rs b/src/librustc_typeck/check/callee.rs index a0801a7486654..e699c8c71666d 100644 --- a/src/librustc_typeck/check/callee.rs +++ b/src/librustc_typeck/check/callee.rs @@ -27,7 +27,7 @@ use rustc::hir; /// Check that it is legal to call methods of the trait corresponding /// to `trait_id` (this only cares about the trait, not the specific /// method that is called) -pub fn check_legal_trait_for_method_call(tcx: TyCtxt, span: Span, trait_id: DefId) { +pub(crate) fn check_legal_trait_for_method_call(tcx: TyCtxt, span: Span, trait_id: DefId) { if tcx.lang_items.drop_trait() == Some(trait_id) { struct_span_err!(tcx.sess, span, E0040, "explicit use of destructor method") .span_label(span, "explicit destructor calls not allowed") @@ -42,12 +42,12 @@ enum CallStep<'tcx> { } impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { - pub fn check_call(&self, - call_expr: &'gcx hir::Expr, - callee_expr: &'gcx hir::Expr, - arg_exprs: &'gcx [hir::Expr], - expected: Expectation<'tcx>) - -> Ty<'tcx> { + pub(crate) fn check_call(&self, + call_expr: &'gcx hir::Expr, + callee_expr: &'gcx hir::Expr, + arg_exprs: &'gcx [hir::Expr], + expected: Expectation<'tcx>) + -> Ty<'tcx> { let original_callee_ty = self.check_expr(callee_expr); let expr_ty = self.structurally_resolved_type(call_expr.span, original_callee_ty); @@ -320,7 +320,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } #[derive(Debug)] -pub struct DeferredCallResolution<'gcx: 'tcx, 'tcx> { +pub(crate) struct DeferredCallResolution<'gcx: 'tcx, 'tcx> { call_expr: &'gcx hir::Expr, callee_expr: &'gcx hir::Expr, adjusted_ty: Ty<'tcx>, @@ -330,7 +330,7 @@ pub struct DeferredCallResolution<'gcx: 'tcx, 'tcx> { } impl<'a, 'gcx, 'tcx> DeferredCallResolution<'gcx, 'tcx> { - pub fn resolve(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) { + pub(crate) fn resolve(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) { debug!("DeferredCallResolution::resolve() {:?}", self); // we should not be invoked until the closure kind has been diff --git a/src/librustc_typeck/check/cast.rs b/src/librustc_typeck/check/cast.rs index b3f62de5b570b..95b03a631d360 100644 --- a/src/librustc_typeck/check/cast.rs +++ b/src/librustc_typeck/check/cast.rs @@ -55,7 +55,7 @@ use util::common::ErrorReported; /// Reifies a cast check to be checked once we have full type information for /// a function context. -pub struct CastCheck<'tcx> { +pub(crate) struct CastCheck<'tcx> { expr: &'tcx hir::Expr, expr_ty: Ty<'tcx>, expr_diverges: Diverges, @@ -127,14 +127,14 @@ fn make_invalid_casting_error<'a, 'gcx, 'tcx>(sess: &'a Session, } impl<'a, 'gcx, 'tcx> CastCheck<'tcx> { - pub fn new(fcx: &FnCtxt<'a, 'gcx, 'tcx>, - expr: &'tcx hir::Expr, - expr_ty: Ty<'tcx>, - expr_diverges: Diverges, - cast_ty: Ty<'tcx>, - cast_span: Span, - span: Span) - -> Result, ErrorReported> { + pub(crate) fn new(fcx: &FnCtxt<'a, 'gcx, 'tcx>, + expr: &'tcx hir::Expr, + expr_ty: Ty<'tcx>, + expr_diverges: Diverges, + cast_ty: Ty<'tcx>, + cast_span: Span, + span: Span) + -> Result, ErrorReported> { let check = CastCheck { expr: expr, expr_ty: expr_ty, @@ -314,7 +314,7 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> { } - pub fn check(mut self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) { + pub(crate) fn check(mut self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) { self.expr_ty = fcx.structurally_resolved_type(self.span, self.expr_ty); self.cast_ty = fcx.structurally_resolved_type(self.span, self.cast_ty); diff --git a/src/librustc_typeck/check/closure.rs b/src/librustc_typeck/check/closure.rs index 802eee91efcf3..72ce1dd2e7afd 100644 --- a/src/librustc_typeck/check/closure.rs +++ b/src/librustc_typeck/check/closure.rs @@ -22,13 +22,13 @@ use syntax::abi::Abi; use rustc::hir; impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { - pub fn check_expr_closure(&self, - expr: &hir::Expr, - _capture: hir::CaptureClause, - decl: &'gcx hir::FnDecl, - body_id: hir::BodyId, - expected: Expectation<'tcx>) - -> Ty<'tcx> { + pub(crate) fn check_expr_closure(&self, + expr: &hir::Expr, + _capture: hir::CaptureClause, + decl: &'gcx hir::FnDecl, + body_id: hir::BodyId, + expected: Expectation<'tcx>) + -> Ty<'tcx> { debug!("check_expr_closure(expr={:?},expected={:?})", expr, expected); diff --git a/src/librustc_typeck/check/coercion.rs b/src/librustc_typeck/check/coercion.rs index 968e893b9a00b..119d87cab105a 100644 --- a/src/librustc_typeck/check/coercion.rs +++ b/src/librustc_typeck/check/coercion.rs @@ -737,12 +737,12 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { /// adjusted type of the expression, if successful. /// Adjustments are only recorded if the coercion succeeded. /// The expressions *must not* have any pre-existing adjustments. - pub fn try_coerce(&self, - expr: &hir::Expr, - expr_ty: Ty<'tcx>, - expr_diverges: Diverges, - target: Ty<'tcx>) - -> RelateResult<'tcx, Ty<'tcx>> { + pub(crate) fn try_coerce(&self, + expr: &hir::Expr, + expr_ty: Ty<'tcx>, + expr_diverges: Diverges, + target: Ty<'tcx>) + -> RelateResult<'tcx, Ty<'tcx>> { let source = self.resolve_type_vars_with_obligations(expr_ty); debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target); @@ -763,7 +763,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } /// Same as `try_coerce()`, but without side-effects. - pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool { + pub(crate) fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool { let source = self.resolve_type_vars_with_obligations(expr_ty); debug!("coercion::can({:?} -> {:?})", source, target); @@ -955,7 +955,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { /// } /// let final_ty = coerce.complete(fcx); /// ``` -pub struct CoerceMany<'gcx, 'tcx, 'exprs, E> +pub(crate) struct CoerceMany<'gcx, 'tcx, 'exprs, E> where 'gcx: 'tcx, E: 'exprs + AsCoercionSite, { expected_ty: Ty<'tcx>, @@ -966,7 +966,7 @@ pub struct CoerceMany<'gcx, 'tcx, 'exprs, E> /// The type of a `CoerceMany` that is storing up the expressions into /// a buffer. We use this in `check/mod.rs` for things like `break`. -pub type DynamicCoerceMany<'gcx, 'tcx> = CoerceMany<'gcx, 'tcx, 'gcx, P>; +pub(crate) type DynamicCoerceMany<'gcx, 'tcx> = CoerceMany<'gcx, 'tcx, 'gcx, P>; enum Expressions<'gcx, 'exprs, E> where E: 'exprs + AsCoercionSite, @@ -981,7 +981,7 @@ impl<'gcx, 'tcx, 'exprs, E> CoerceMany<'gcx, 'tcx, 'exprs, E> /// The usual case; collect the set of expressions dynamically. /// If the full set of coercion sites is known before hand, /// consider `with_coercion_sites()` instead to avoid allocation. - pub fn new(expected_ty: Ty<'tcx>) -> Self { + pub(crate) fn new(expected_ty: Ty<'tcx>) -> Self { Self::make(expected_ty, Expressions::Dynamic(vec![])) } @@ -990,8 +990,8 @@ impl<'gcx, 'tcx, 'exprs, E> CoerceMany<'gcx, 'tcx, 'exprs, E> /// expected to pass each element in the slice to `coerce(...)` in /// order. This is used with arrays in particular to avoid /// needlessly cloning the slice. - pub fn with_coercion_sites(expected_ty: Ty<'tcx>, - coercion_sites: &'exprs [E]) + pub(crate) fn with_coercion_sites(expected_ty: Ty<'tcx>, + coercion_sites: &'exprs [E]) -> Self { Self::make(expected_ty, Expressions::UpFront(coercion_sites)) } @@ -1013,7 +1013,7 @@ impl<'gcx, 'tcx, 'exprs, E> CoerceMany<'gcx, 'tcx, 'exprs, E> /// Typically, this is used as the expected type when /// type-checking each of the alternative expressions whose types /// we are trying to merge. - pub fn expected_ty(&self) -> Ty<'tcx> { + pub(crate) fn expected_ty(&self) -> Ty<'tcx> { self.expected_ty } @@ -1021,7 +1021,7 @@ impl<'gcx, 'tcx, 'exprs, E> CoerceMany<'gcx, 'tcx, 'exprs, E> /// at the LUB of the expressions we've seen so far (if any). This /// isn't *final* until you call `self.final()`, which will return /// the merged type. - pub fn merged_ty(&self) -> Ty<'tcx> { + pub(crate) fn merged_ty(&self) -> Ty<'tcx> { self.final_ty.unwrap_or(self.expected_ty) } @@ -1030,12 +1030,12 @@ impl<'gcx, 'tcx, 'exprs, E> CoerceMany<'gcx, 'tcx, 'exprs, E> /// could coerce from. This will record `expression` and later /// calls to `coerce` may come back and add adjustments and things /// if necessary. - pub fn coerce<'a>(&mut self, - fcx: &FnCtxt<'a, 'gcx, 'tcx>, - cause: &ObligationCause<'tcx>, - expression: &'gcx hir::Expr, - expression_ty: Ty<'tcx>, - expression_diverges: Diverges) + pub(crate) fn coerce<'a>(&mut self, + fcx: &FnCtxt<'a, 'gcx, 'tcx>, + cause: &ObligationCause<'tcx>, + expression: &'gcx hir::Expr, + expression_ty: Ty<'tcx>, + expression_diverges: Diverges) { self.coerce_inner(fcx, cause, @@ -1057,11 +1057,11 @@ impl<'gcx, 'tcx, 'exprs, E> CoerceMany<'gcx, 'tcx, 'exprs, E> /// The `augment_error` gives you a chance to extend the error /// message, in case any results (e.g., we use this to suggest /// removing a `;`). - pub fn coerce_forced_unit<'a>(&mut self, - fcx: &FnCtxt<'a, 'gcx, 'tcx>, - cause: &ObligationCause<'tcx>, - augment_error: &mut FnMut(&mut DiagnosticBuilder), - label_unit_as_expected: bool) + pub(crate) fn coerce_forced_unit<'a>(&mut self, + fcx: &FnCtxt<'a, 'gcx, 'tcx>, + cause: &ObligationCause<'tcx>, + augment_error: &mut FnMut(&mut DiagnosticBuilder), + label_unit_as_expected: bool) { self.coerce_inner(fcx, cause, @@ -1215,7 +1215,7 @@ impl<'gcx, 'tcx, 'exprs, E> CoerceMany<'gcx, 'tcx, 'exprs, E> } } - pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> { + pub(crate) fn complete<'a>(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> { if let Some(final_ty) = self.final_ty { final_ty } else { @@ -1229,7 +1229,7 @@ impl<'gcx, 'tcx, 'exprs, E> CoerceMany<'gcx, 'tcx, 'exprs, E> /// Something that can be converted into an expression to which we can /// apply a coercion. -pub trait AsCoercionSite { +pub(crate) trait AsCoercionSite { fn as_coercion_site(&self) -> &hir::Expr; } diff --git a/src/librustc_typeck/check/compare_method.rs b/src/librustc_typeck/check/compare_method.rs index bf134f9547d38..e2ad13a19b53b 100644 --- a/src/librustc_typeck/check/compare_method.rs +++ b/src/librustc_typeck/check/compare_method.rs @@ -33,13 +33,13 @@ use astconv::ExplicitSelf; /// - trait_m: the method in the trait /// - impl_trait_ref: the TraitRef corresponding to the trait implementation -pub fn compare_impl_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - impl_m: &ty::AssociatedItem, - impl_m_span: Span, - trait_m: &ty::AssociatedItem, - impl_trait_ref: ty::TraitRef<'tcx>, - trait_item_span: Option, - old_broken_mode: bool) { +pub(crate) fn compare_impl_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, + impl_m: &ty::AssociatedItem, + impl_m_span: Span, + trait_m: &ty::AssociatedItem, + impl_trait_ref: ty::TraitRef<'tcx>, + trait_item_span: Option, + old_broken_mode: bool) { debug!("compare_impl_method(impl_trait_ref={:?})", impl_trait_ref); @@ -705,11 +705,11 @@ fn compare_number_of_method_arguments<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, Ok(()) } -pub fn compare_const_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - impl_c: &ty::AssociatedItem, - impl_c_span: Span, - trait_c: &ty::AssociatedItem, - impl_trait_ref: ty::TraitRef<'tcx>) { +pub(crate) fn compare_const_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, + impl_c: &ty::AssociatedItem, + impl_c_span: Span, + trait_c: &ty::AssociatedItem, + impl_trait_ref: ty::TraitRef<'tcx>) { debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref); tcx.infer_ctxt().enter(|infcx| { diff --git a/src/librustc_typeck/check/demand.rs b/src/librustc_typeck/check/demand.rs index 828106df7821b..72360837537ae 100644 --- a/src/librustc_typeck/check/demand.rs +++ b/src/librustc_typeck/check/demand.rs @@ -26,14 +26,14 @@ use super::method::probe; impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // Requires that the two types unify, and prints an error message if // they don't. - pub fn demand_suptype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) { + pub(crate) fn demand_suptype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) { self.demand_suptype_diag(sp, expected, actual).map(|mut e| e.emit()); } - pub fn demand_suptype_diag(&self, - sp: Span, - expected: Ty<'tcx>, - actual: Ty<'tcx>) -> Option> { + pub(crate) fn demand_suptype_diag(&self, + sp: Span, + expected: Ty<'tcx>, + actual: Ty<'tcx>) -> Option> { let cause = &self.misc(sp); match self.at(cause, self.param_env).sup(expected, actual) { Ok(InferOk { obligations, value: () }) => { @@ -46,23 +46,23 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } } - pub fn demand_eqtype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) { + pub(crate) fn demand_eqtype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) { if let Some(mut err) = self.demand_eqtype_diag(sp, expected, actual) { err.emit(); } } - pub fn demand_eqtype_diag(&self, - sp: Span, - expected: Ty<'tcx>, - actual: Ty<'tcx>) -> Option> { + pub(crate) fn demand_eqtype_diag(&self, + sp: Span, + expected: Ty<'tcx>, + actual: Ty<'tcx>) -> Option> { self.demand_eqtype_with_origin(&self.misc(sp), expected, actual) } - pub fn demand_eqtype_with_origin(&self, - cause: &ObligationCause<'tcx>, - expected: Ty<'tcx>, - actual: Ty<'tcx>) -> Option> { + pub(crate) fn demand_eqtype_with_origin(&self, + cause: &ObligationCause<'tcx>, + expected: Ty<'tcx>, + actual: Ty<'tcx>) -> Option> { match self.at(cause, self.param_env).eq(expected, actual) { Ok(InferOk { obligations, value: () }) => { self.register_predicates(obligations); @@ -74,7 +74,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } } - pub fn demand_coerce(&self, expr: &hir::Expr, checked_ty: Ty<'tcx>, expected: Ty<'tcx>) { + pub(crate) fn demand_coerce(&self, expr: &hir::Expr, checked_ty: Ty<'tcx>, expected: Ty<'tcx>) { if let Some(mut err) = self.demand_coerce_diag(expr, checked_ty, expected) { err.emit(); } @@ -85,10 +85,10 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // NB: This code relies on `self.diverges` to be accurate. In // particular, assignments to `!` will be permitted if the // diverges flag is currently "always". - pub fn demand_coerce_diag(&self, - expr: &hir::Expr, - checked_ty: Ty<'tcx>, - expected: Ty<'tcx>) -> Option> { + pub(crate) fn demand_coerce_diag(&self, + expr: &hir::Expr, + checked_ty: Ty<'tcx>, + expected: Ty<'tcx>) -> Option> { let expected = self.resolve_type_vars_with_obligations(expected); if let Err(e) = self.try_coerce(expr, checked_ty, self.diverges.get(), expected) { diff --git a/src/librustc_typeck/check/dropck.rs b/src/librustc_typeck/check/dropck.rs index ed22cd1333e9c..49bfc3a0c2425 100644 --- a/src/librustc_typeck/check/dropck.rs +++ b/src/librustc_typeck/check/dropck.rs @@ -39,9 +39,9 @@ use syntax_pos::Span; /// struct/enum definition for the nominal type itself (i.e. /// cannot do `struct S; impl Drop for S { ... }`). /// -pub fn check_drop_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - drop_impl_did: DefId) - -> Result<(), ErrorReported> { +pub(crate) fn check_drop_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, + drop_impl_did: DefId) + -> Result<(), ErrorReported> { let dtor_self_type = tcx.type_of(drop_impl_did); let dtor_predicates = tcx.predicates_of(drop_impl_did); match dtor_self_type.sty { @@ -266,7 +266,7 @@ fn ensure_drop_predicates_are_implied_by_item_defn<'a, 'tcx>( /// ensuring that they do not access data nor invoke methods of /// values that have been previously dropped). /// -pub fn check_safety_of_destructor_if_necessary<'a, 'gcx, 'tcx>( +pub(crate) fn check_safety_of_destructor_if_necessary<'a, 'gcx, 'tcx>( rcx: &mut RegionCtxt<'a, 'gcx, 'tcx>, ty: ty::Ty<'tcx>, span: Span, diff --git a/src/librustc_typeck/check/intrinsic.rs b/src/librustc_typeck/check/intrinsic.rs index 96643ae72abad..496b13a0fcf45 100644 --- a/src/librustc_typeck/check/intrinsic.rs +++ b/src/librustc_typeck/check/intrinsic.rs @@ -74,8 +74,8 @@ fn equate_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, /// Remember to add all intrinsics here, in librustc_trans/trans/intrinsic.rs, /// and in libcore/intrinsics.rs -pub fn check_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - it: &hir::ForeignItem) { +pub(crate) fn check_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, + it: &hir::ForeignItem) { let param = |n| tcx.mk_param(n, Symbol::intern(&format!("P{}", n))); let name = it.name.as_str(); let (n_tps, inputs, output) = if name.starts_with("atomic_") { @@ -328,8 +328,8 @@ pub fn check_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } /// Type-check `extern "platform-intrinsic" { ... }` functions. -pub fn check_platform_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - it: &hir::ForeignItem) { +pub(crate) fn check_platform_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, + it: &hir::ForeignItem) { let param = |n| { let name = Symbol::intern(&format!("P{}", n)); tcx.mk_param(n, name) diff --git a/src/librustc_typeck/check/method/confirm.rs b/src/librustc_typeck/check/method/confirm.rs index ad4ee5a9d6dcf..960ce1c4c9ca5 100644 --- a/src/librustc_typeck/check/method/confirm.rs +++ b/src/librustc_typeck/check/method/confirm.rs @@ -39,14 +39,14 @@ impl<'a, 'gcx, 'tcx> Deref for ConfirmContext<'a, 'gcx, 'tcx> { } impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { - pub fn confirm_method(&self, - span: Span, - self_expr: &'gcx hir::Expr, - call_expr: &'gcx hir::Expr, - unadjusted_self_ty: Ty<'tcx>, - pick: probe::Pick<'tcx>, - segment: &hir::PathSegment) - -> MethodCallee<'tcx> { + pub(crate) fn confirm_method(&self, + span: Span, + self_expr: &'gcx hir::Expr, + call_expr: &'gcx hir::Expr, + unadjusted_self_ty: Ty<'tcx>, + pick: probe::Pick<'tcx>, + segment: &hir::PathSegment) + -> MethodCallee<'tcx> { debug!("confirm(unadjusted_self_ty={:?}, pick={:?}, generic_args={:?})", unadjusted_self_ty, pick, diff --git a/src/librustc_typeck/check/method/mod.rs b/src/librustc_typeck/check/method/mod.rs index c842e47aaf51c..7364407e3af6d 100644 --- a/src/librustc_typeck/check/method/mod.rs +++ b/src/librustc_typeck/check/method/mod.rs @@ -24,30 +24,28 @@ use syntax_pos::Span; use rustc::hir; -pub use self::MethodError::*; -pub use self::CandidateSource::*; - -pub use self::suggest::AllTraitsVec; +pub(crate) use self::MethodError::*; +pub(crate) use self::CandidateSource::*; mod confirm; -pub mod probe; +pub(crate) mod probe; mod suggest; use self::probe::IsSuggestion; #[derive(Clone, Copy, Debug)] -pub struct MethodCallee<'tcx> { +pub(crate) struct MethodCallee<'tcx> { /// Impl method ID, for inherent methods, or trait method ID, otherwise. - pub def_id: DefId, - pub substs: &'tcx Substs<'tcx>, + pub(crate) def_id: DefId, + pub(crate) substs: &'tcx Substs<'tcx>, /// Instantiated method signature, i.e. it has been /// substituted, normalized, and has had late-bound /// lifetimes replaced with inference variables. - pub sig: ty::FnSig<'tcx>, + pub(crate) sig: ty::FnSig<'tcx>, } -pub enum MethodError<'tcx> { +pub(crate) enum MethodError<'tcx> { // Did not find an applicable method, but we did find various near-misses that may work. NoMatch(NoMatchData<'tcx>), @@ -64,19 +62,19 @@ pub enum MethodError<'tcx> { // Contains a list of static methods that may apply, a list of unsatisfied trait predicates which // could lead to matches if satisfied, and a list of not-in-scope traits which may work. -pub struct NoMatchData<'tcx> { - pub static_candidates: Vec, - pub unsatisfied_predicates: Vec>, - pub out_of_scope_traits: Vec, - pub mode: probe::Mode, +pub(crate) struct NoMatchData<'tcx> { + pub(crate) static_candidates: Vec, + pub(crate) unsatisfied_predicates: Vec>, + pub(crate) out_of_scope_traits: Vec, + pub(crate) mode: probe::Mode, } impl<'tcx> NoMatchData<'tcx> { - pub fn new(static_candidates: Vec, - unsatisfied_predicates: Vec>, - out_of_scope_traits: Vec, - mode: probe::Mode) - -> Self { + pub(crate) fn new(static_candidates: Vec, + unsatisfied_predicates: Vec>, + out_of_scope_traits: Vec, + mode: probe::Mode) + -> Self { NoMatchData { static_candidates: static_candidates, unsatisfied_predicates: unsatisfied_predicates, @@ -89,7 +87,7 @@ impl<'tcx> NoMatchData<'tcx> { // A pared down enum describing just the places from which a method // candidate can arise. Used for error reporting only. #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] -pub enum CandidateSource { +pub(crate) enum CandidateSource { ImplSource(DefId), TraitSource(// trait id DefId), @@ -97,13 +95,13 @@ pub enum CandidateSource { impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { /// Determines whether the type `self_ty` supports a method name `method_name` or not. - pub fn method_exists(&self, - span: Span, - method_name: ast::Name, - self_ty: ty::Ty<'tcx>, - call_expr_id: ast::NodeId, - allow_private: bool) - -> bool { + pub(crate) fn method_exists(&self, + span: Span, + method_name: ast::Name, + self_ty: ty::Ty<'tcx>, + call_expr_id: ast::NodeId, + allow_private: bool) + -> bool { let mode = probe::Mode::MethodCall; match self.probe_for_name(span, mode, method_name, IsSuggestion(false), self_ty, call_expr_id) { @@ -129,13 +127,13 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { /// * `self_ty`: the (unadjusted) type of the self expression (`foo`) /// * `supplied_method_types`: the explicit method type parameters, if any (`T1..Tn`) /// * `self_expr`: the self expression (`foo`) - pub fn lookup_method(&self, - self_ty: ty::Ty<'tcx>, - segment: &hir::PathSegment, - span: Span, - call_expr: &'gcx hir::Expr, - self_expr: &'gcx hir::Expr) - -> Result, MethodError<'tcx>> { + pub(crate) fn lookup_method(&self, + self_ty: ty::Ty<'tcx>, + segment: &hir::PathSegment, + span: Span, + call_expr: &'gcx hir::Expr, + self_expr: &'gcx hir::Expr) + -> Result, MethodError<'tcx>> { debug!("lookup(method_name={}, self_ty={:?}, call_expr={:?}, self_expr={:?})", segment.name, self_ty, @@ -172,13 +170,13 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { /// FIXME(#18741) -- It seems likely that we can consolidate some of this /// code with the other method-lookup code. In particular, the second half /// of this method is basically the same as confirmation. - pub fn lookup_method_in_trait(&self, - span: Span, - m_name: ast::Name, - trait_def_id: DefId, - self_ty: ty::Ty<'tcx>, - opt_input_types: Option<&[ty::Ty<'tcx>]>) - -> Option>> { + pub(crate) fn lookup_method_in_trait(&self, + span: Span, + m_name: ast::Name, + trait_def_id: DefId, + self_ty: ty::Ty<'tcx>, + opt_input_types: Option<&[ty::Ty<'tcx>]>) + -> Option>> { debug!("lookup_in_trait_adjusted(self_ty={:?}, \ m_name={}, trait_def_id={:?})", self_ty, @@ -291,12 +289,12 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { }) } - pub fn resolve_ufcs(&self, - span: Span, - method_name: ast::Name, - self_ty: ty::Ty<'tcx>, - expr_id: ast::NodeId) - -> Result> { + pub(crate) fn resolve_ufcs(&self, + span: Span, + method_name: ast::Name, + self_ty: ty::Ty<'tcx>, + expr_id: ast::NodeId) + -> Result> { let mode = probe::Mode::Path; let pick = self.probe_for_name(span, mode, method_name, IsSuggestion(false), self_ty, expr_id)?; @@ -315,7 +313,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { /// Find item with name `item_name` defined in impl/trait `def_id` /// and return it, or `None`, if no such item was defined there. - pub fn associated_item(&self, def_id: DefId, item_name: ast::Name) + pub(crate) fn associated_item(&self, def_id: DefId, item_name: ast::Name) -> Option { let ident = self.tcx.adjust(item_name, def_id, self.body_id).0; self.tcx.associated_items(def_id).find(|item| item.name.to_ident() == ident) diff --git a/src/librustc_typeck/check/method/probe.rs b/src/librustc_typeck/check/method/probe.rs index dfc5cd00b6eab..b0cbc13fb04c8 100644 --- a/src/librustc_typeck/check/method/probe.rs +++ b/src/librustc_typeck/check/method/probe.rs @@ -30,9 +30,9 @@ use std::ops::Deref; use std::rc::Rc; use self::CandidateKind::*; -pub use self::PickKind::*; +pub(crate) use self::PickKind::*; -pub enum LookingFor<'tcx> { +pub(crate) enum LookingFor<'tcx> { /// looking for methods with the given name; this is the normal case MethodName(ast::Name), @@ -43,7 +43,7 @@ pub enum LookingFor<'tcx> { /// Boolean flag used to indicate if this search is for a suggestion /// or not. If true, we can allow ambiguity and so forth. -pub struct IsSuggestion(pub bool); +pub(crate) struct IsSuggestion(pub(crate) bool); struct ProbeContext<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> { fcx: &'a FnCtxt<'a, 'gcx, 'tcx>, @@ -107,31 +107,31 @@ enum CandidateKind<'tcx> { } #[derive(Debug)] -pub struct Pick<'tcx> { - pub item: ty::AssociatedItem, - pub kind: PickKind<'tcx>, - pub import_id: Option, +pub(crate) struct Pick<'tcx> { + pub(crate) item: ty::AssociatedItem, + pub(crate) kind: PickKind<'tcx>, + pub(crate) import_id: Option, // Indicates that the source expression should be autoderef'd N times // // A = expr | *expr | **expr | ... - pub autoderefs: usize, + pub(crate) autoderefs: usize, // Indicates that an autoref is applied after the optional autoderefs // // B = A | &A | &mut A - pub autoref: Option, + pub(crate) autoref: Option, // Indicates that the source expression should be "unsized" to a // target type. This should probably eventually go away in favor // of just coercing method receivers. // // C = B | unsize(B) - pub unsize: Option>, + pub(crate) unsize: Option>, } #[derive(Clone,Debug)] -pub enum PickKind<'tcx> { +pub(crate) enum PickKind<'tcx> { InherentImplPick, ExtensionImplPick(// Impl DefId), @@ -141,10 +141,10 @@ pub enum PickKind<'tcx> { ty::PolyTraitRef<'tcx>), } -pub type PickResult<'tcx> = Result, MethodError<'tcx>>; +pub(crate) type PickResult<'tcx> = Result, MethodError<'tcx>>; #[derive(PartialEq, Eq, Copy, Clone, Debug)] -pub enum Mode { +pub(crate) enum Mode { // An expression of the form `receiver.method_name(...)`. // Autoderefs are performed on `receiver`, lookup is done based on the // `self` argument of the method, and static methods aren't considered. @@ -162,13 +162,13 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { /// would result in an error (basically, the same criteria we /// would use to decide if a method is a plausible fit for /// ambiguity purposes). - pub fn probe_for_return_type(&self, - span: Span, - mode: Mode, - return_type: Ty<'tcx>, - self_ty: Ty<'tcx>, - scope_expr_id: ast::NodeId) - -> Vec { + pub(crate) fn probe_for_return_type(&self, + span: Span, + mode: Mode, + return_type: Ty<'tcx>, + self_ty: Ty<'tcx>, + scope_expr_id: ast::NodeId) + -> Vec { debug!("probe(self_ty={:?}, return_type={}, scope_expr_id={})", self_ty, return_type, @@ -190,14 +190,14 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { .collect() } - pub fn probe_for_name(&self, - span: Span, - mode: Mode, - item_name: ast::Name, - is_suggestion: IsSuggestion, - self_ty: Ty<'tcx>, - scope_expr_id: ast::NodeId) - -> PickResult<'tcx> { + pub(crate) fn probe_for_name(&self, + span: Span, + mode: Mode, + item_name: ast::Name, + is_suggestion: IsSuggestion, + self_ty: Ty<'tcx>, + scope_expr_id: ast::NodeId) + -> PickResult<'tcx> { debug!("probe(self_ty={:?}, item_name={}, scope_expr_id={})", self_ty, item_name, @@ -669,8 +669,8 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> { Ok(()) } - pub fn matches_return_type(&self, method: &ty::AssociatedItem, - expected: ty::Ty<'tcx>) -> bool { + pub(crate) fn matches_return_type(&self, method: &ty::AssociatedItem, + expected: ty::Ty<'tcx>) -> bool { match method.def() { Def::Method(def_id) => { let fty = self.tcx.fn_sig(def_id); diff --git a/src/librustc_typeck/check/method/suggest.rs b/src/librustc_typeck/check/method/suggest.rs index 4faf71e0cc945..8ad483b185c22 100644 --- a/src/librustc_typeck/check/method/suggest.rs +++ b/src/librustc_typeck/check/method/suggest.rs @@ -68,13 +68,13 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } } - pub fn report_method_error(&self, - span: Span, - rcvr_ty: Ty<'tcx>, - item_name: ast::Name, - rcvr_expr: Option<&hir::Expr>, - error: MethodError<'tcx>, - args: Option<&'gcx [hir::Expr]>) { + pub(crate) fn report_method_error(&self, + span: Span, + rcvr_ty: Ty<'tcx>, + item_name: ast::Name, + rcvr_expr: Option<&hir::Expr>, + error: MethodError<'tcx>, + args: Option<&'gcx [hir::Expr]>) { // avoid suggestions when we don't know what's going on. if rcvr_ty.references_error() { return; @@ -441,11 +441,11 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } } -pub type AllTraitsVec = Vec; +pub(crate) type AllTraitsVec = Vec; #[derive(Copy, Clone)] -pub struct TraitInfo { - pub def_id: DefId, +pub(crate) struct TraitInfo { + pub(crate) def_id: DefId, } impl TraitInfo { @@ -476,7 +476,7 @@ impl Ord for TraitInfo { } /// Retrieve all traits in this crate and any dependent crates. -pub fn all_traits<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> AllTraits<'a> { +pub(crate) fn all_traits<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> AllTraits<'a> { if tcx.all_traits.borrow().is_none() { use rustc::hir::itemlikevisit; @@ -552,7 +552,7 @@ pub fn all_traits<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> AllTraits<'a> } } -pub struct AllTraits<'a> { +pub(crate) struct AllTraits<'a> { borrow: cell::Ref<'a, Option>, idx: usize, } diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index af11cacb247b6..5c5e625207b0a 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -76,11 +76,11 @@ type parameter). */ -pub use self::Expectation::*; +pub(crate) use self::Expectation::*; use self::autoderef::Autoderef; use self::callee::DeferredCallResolution; use self::coercion::{CoerceMany, DynamicCoerceMany}; -pub use self::compare_method::{compare_impl_method, compare_const_impl}; +pub(crate) use self::compare_method::{compare_impl_method, compare_const_impl}; use self::method::MethodCallee; use self::TupleArgumentsFlag::*; @@ -133,13 +133,13 @@ use rustc::middle::const_val::eval_length; use rustc_const_math::ConstInt; mod autoderef; -pub mod dropck; -pub mod _match; -pub mod writeback; -pub mod regionck; -pub mod coercion; -pub mod demand; -pub mod method; +pub(crate) mod dropck; +pub(crate) mod _match; +pub(crate) mod writeback; +pub(crate) mod regionck; +pub(crate) mod coercion; +pub(crate) mod demand; +pub(crate) mod method; mod upvar; mod wfcheck; mod cast; @@ -185,7 +185,7 @@ impl<'a, 'tcx> MaybeInProgressTables<'a, 'tcx> { /// Here, the function `foo()` and the closure passed to /// `bar()` will each have their own `FnCtxt`, but they will /// share the inherited fields. -pub struct Inherited<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { +pub(crate) struct Inherited<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { infcx: InferCtxt<'a, 'gcx, 'tcx>, tables: MaybeInProgressTables<'a, 'tcx>, @@ -232,7 +232,7 @@ impl<'a, 'gcx, 'tcx> Deref for Inherited<'a, 'gcx, 'tcx> { /// When type-checking an expression, we propagate downward /// whatever type hint we are able in the form of an `Expectation`. #[derive(Copy, Clone, Debug)] -pub enum Expectation<'tcx> { +pub(crate) enum Expectation<'tcx> { /// We know nothing about what type this expression should have. NoExpectation, @@ -362,19 +362,19 @@ impl<'a, 'gcx, 'tcx> Expectation<'tcx> { } #[derive(Copy, Clone)] -pub struct UnsafetyState { - pub def: ast::NodeId, - pub unsafety: hir::Unsafety, - pub unsafe_push_count: u32, +pub(crate) struct UnsafetyState { + pub(crate) def: ast::NodeId, + pub(crate) unsafety: hir::Unsafety, + pub(crate) unsafe_push_count: u32, from_fn: bool } impl UnsafetyState { - pub fn function(unsafety: hir::Unsafety, def: ast::NodeId) -> UnsafetyState { + pub(crate) fn function(unsafety: hir::Unsafety, def: ast::NodeId) -> UnsafetyState { UnsafetyState { def: def, unsafety: unsafety, unsafe_push_count: 0, from_fn: true } } - pub fn recurse(&mut self, blk: &hir::Block) -> UnsafetyState { + pub(crate) fn recurse(&mut self, blk: &hir::Block) -> UnsafetyState { match self.unsafety { // If this unsafe, then if the outer function was already marked as // unsafe we shouldn't attribute the unsafe'ness to the block. This @@ -403,7 +403,7 @@ impl UnsafetyState { } #[derive(Debug, Copy, Clone)] -pub enum LvalueOp { +pub(crate) enum LvalueOp { Deref, Index } @@ -414,7 +414,7 @@ pub enum LvalueOp { /// as diverging), with some manual adjustments for control-flow /// primitives (approximating a CFG). #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub enum Diverges { +pub(crate) enum Diverges { /// Potentially unknown, some cases converge, /// others require a CFG to determine them. Maybe, @@ -462,7 +462,7 @@ impl Diverges { } } -pub struct BreakableCtxt<'gcx: 'tcx, 'tcx> { +pub(crate) struct BreakableCtxt<'gcx: 'tcx, 'tcx> { may_break: bool, // this is `null` for loops where break with a value is illegal, @@ -470,7 +470,7 @@ pub struct BreakableCtxt<'gcx: 'tcx, 'tcx> { coerce: Option>, } -pub struct EnclosingBreakables<'gcx: 'tcx, 'tcx> { +pub(crate) struct EnclosingBreakables<'gcx: 'tcx, 'tcx> { stack: Vec>, by_id: NodeMap, } @@ -484,7 +484,7 @@ impl<'gcx, 'tcx> EnclosingBreakables<'gcx, 'tcx> { } } -pub struct FnCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { +pub(crate) struct FnCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { body_id: ast::NodeId, /// The parameter environment used for proving trait obligations @@ -564,13 +564,13 @@ impl<'a, 'gcx, 'tcx> Deref for FnCtxt<'a, 'gcx, 'tcx> { /// Helper type of a temporary returned by Inherited::build(...). /// Necessary because we can't write the following bound: /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(Inherited<'b, 'gcx, 'tcx>). -pub struct InheritedBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { +pub(crate) struct InheritedBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { infcx: infer::InferCtxtBuilder<'a, 'gcx, 'tcx>, def_id: DefId, } impl<'a, 'gcx, 'tcx> Inherited<'a, 'gcx, 'tcx> { - pub fn build(tcx: TyCtxt<'a, 'gcx, 'gcx>, def_id: DefId) + pub(crate) fn build(tcx: TyCtxt<'a, 'gcx, 'gcx>, def_id: DefId) -> InheritedBuilder<'a, 'gcx, 'tcx> { InheritedBuilder { infcx: tcx.infer_ctxt().with_fresh_in_progress_tables(), @@ -692,20 +692,21 @@ impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CheckItemTypesVisitor<'a, 'tcx> { fn visit_impl_item(&mut self, _: &'tcx hir::ImplItem) { } } -pub fn check_wf_new<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Result<(), ErrorReported> { +pub(crate) fn check_wf_new<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Result<(), ErrorReported> { tcx.sess.track_errors(|| { let mut visit = wfcheck::CheckTypeWellFormedVisitor::new(tcx); tcx.hir.krate().visit_all_item_likes(&mut visit.as_deep_visitor()); }) } -pub fn check_item_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Result<(), ErrorReported> { +pub(crate) fn check_item_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Result<(), ErrorReported> { tcx.sess.track_errors(|| { tcx.hir.krate().visit_all_item_likes(&mut CheckItemTypesVisitor { tcx }); }) } -pub fn check_item_bodies<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Result<(), CompileIncomplete> { +pub(crate) fn check_item_bodies<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) + -> Result<(), CompileIncomplete> { tcx.typeck_item_bodies(LOCAL_CRATE) } @@ -720,7 +721,7 @@ fn typeck_item_bodies<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, crate_num: CrateNum })?) } -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { *providers = Providers { typeck_item_bodies, typeck_tables_of, @@ -1079,7 +1080,7 @@ fn check_union<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, check_representable(tcx, span, def_id); } -pub fn check_item_type<'a,'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, it: &'tcx hir::Item) { +pub(crate) fn check_item_type<'a,'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, it: &'tcx hir::Item) { debug!("check_item_type(it.id={}, it.name={})", it.id, tcx.item_path_str(tcx.hir.local_def_id(it.id))); @@ -1447,7 +1448,7 @@ fn check_representable<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, return true } -pub fn check_simd<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span, def_id: DefId) { +pub(crate) fn check_simd<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span, def_id: DefId) { let t = tcx.type_of(def_id); match t.sty { ty::TyAdt(def, substs) if def.is_struct() => { @@ -1519,10 +1520,10 @@ fn check_packed_inner<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } #[allow(trivial_numeric_casts)] -pub fn check_enum<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - sp: Span, - vs: &'tcx [hir::Variant], - id: ast::NodeId) { +pub(crate) fn check_enum<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, + sp: Span, + vs: &'tcx [hir::Variant], + id: ast::NodeId) { let def_id = tcx.hir.local_def_id(id); let def = tcx.adt_def(def_id); def.destructor(tcx); // force the destructor to be evaluated @@ -1672,10 +1673,10 @@ enum TupleArgumentsFlag { } impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { - pub fn new(inh: &'a Inherited<'a, 'gcx, 'tcx>, - param_env: ty::ParamEnv<'tcx>, - body_id: ast::NodeId) - -> FnCtxt<'a, 'gcx, 'tcx> { + pub(crate) fn new(inh: &'a Inherited<'a, 'gcx, 'tcx>, + param_env: ty::ParamEnv<'tcx>, + body_id: ast::NodeId) + -> FnCtxt<'a, 'gcx, 'tcx> { FnCtxt { body_id: body_id, param_env, @@ -1693,11 +1694,11 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } } - pub fn sess(&self) -> &Session { + pub(crate) fn sess(&self) -> &Session { &self.tcx.sess } - pub fn err_count_since_creation(&self) -> usize { + pub(crate) fn err_count_since_creation(&self) -> usize { self.tcx.sess.err_count() - self.err_count_on_creation } @@ -1716,14 +1717,14 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } } - pub fn cause(&self, - span: Span, - code: ObligationCauseCode<'tcx>) - -> ObligationCause<'tcx> { + pub(crate) fn cause(&self, + span: Span, + code: ObligationCauseCode<'tcx>) + -> ObligationCause<'tcx> { ObligationCause::new(span, self.body_id, code) } - pub fn misc(&self, span: Span) -> ObligationCause<'tcx> { + pub(crate) fn misc(&self, span: Span) -> ObligationCause<'tcx> { self.cause(span, ObligationCauseCode::MiscObligation) } @@ -1773,12 +1774,12 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { deferred_call_resolutions.remove(&closure_def_id).unwrap_or(vec![]) } - pub fn tag(&self) -> String { + pub(crate) fn tag(&self) -> String { let self_ptr: *const FnCtxt = self; format!("{:?}", self_ptr) } - pub fn local_ty(&self, span: Span, nid: ast::NodeId) -> Ty<'tcx> { + pub(crate) fn local_ty(&self, span: Span, nid: ast::NodeId) -> Ty<'tcx> { match self.locals.borrow().get(&nid) { Some(&t) => t, None => { @@ -1789,7 +1790,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } #[inline] - pub fn write_ty(&self, node_id: ast::NodeId, ty: Ty<'tcx>) { + pub(crate) fn write_ty(&self, node_id: ast::NodeId, ty: Ty<'tcx>) { debug!("write_ty({}, {:?}) in fcx {}", node_id, self.resolve_type_vars_if_possible(&ty), self.tag()); self.tables.borrow_mut().node_types.insert(node_id, ty); @@ -1800,12 +1801,12 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } } - pub fn write_method_call(&self, node_id: ast::NodeId, method: MethodCallee<'tcx>) { + pub(crate) fn write_method_call(&self, node_id: ast::NodeId, method: MethodCallee<'tcx>) { self.tables.borrow_mut().type_dependent_defs.insert(node_id, Def::Method(method.def_id)); self.write_substs(node_id, method.substs); } - pub fn write_substs(&self, node_id: ast::NodeId, substs: &'tcx Substs<'tcx>) { + pub(crate) fn write_substs(&self, node_id: ast::NodeId, substs: &'tcx Substs<'tcx>) { if !substs.is_noop() { debug!("write_substs({}, {:?}) in fcx {}", node_id, @@ -1816,7 +1817,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } } - pub fn apply_adjustments(&self, expr: &hir::Expr, adj: Vec>) { + pub(crate) fn apply_adjustments(&self, expr: &hir::Expr, adj: Vec>) { debug!("apply_adjustments(expr={:?}, adj={:?})", expr, adj); if adj.is_empty() { @@ -1940,11 +1941,11 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { value) } - pub fn require_type_meets(&self, - ty: Ty<'tcx>, - span: Span, - code: traits::ObligationCauseCode<'tcx>, - def_id: DefId) + pub(crate) fn require_type_meets(&self, + ty: Ty<'tcx>, + span: Span, + code: traits::ObligationCauseCode<'tcx>, + def_id: DefId) { self.register_bound( ty, @@ -1952,31 +1953,31 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { traits::ObligationCause::new(span, self.body_id, code)); } - pub fn require_type_is_sized(&self, - ty: Ty<'tcx>, - span: Span, - code: traits::ObligationCauseCode<'tcx>) + pub(crate) fn require_type_is_sized(&self, + ty: Ty<'tcx>, + span: Span, + code: traits::ObligationCauseCode<'tcx>) { let lang_item = self.tcx.require_lang_item(lang_items::SizedTraitLangItem); self.require_type_meets(ty, span, code, lang_item); } - pub fn register_bound(&self, - ty: Ty<'tcx>, - def_id: DefId, - cause: traits::ObligationCause<'tcx>) + pub(crate) fn register_bound(&self, + ty: Ty<'tcx>, + def_id: DefId, + cause: traits::ObligationCause<'tcx>) { self.fulfillment_cx.borrow_mut() .register_bound(self, self.param_env, ty, def_id, cause); } - pub fn to_ty(&self, ast_t: &hir::Ty) -> Ty<'tcx> { + pub(crate) fn to_ty(&self, ast_t: &hir::Ty) -> Ty<'tcx> { let t = AstConv::ast_ty_to_ty(self, ast_t); self.register_wf_obligation(t, ast_t.span, traits::MiscObligation); t } - pub fn node_ty(&self, id: ast::NodeId) -> Ty<'tcx> { + pub(crate) fn node_ty(&self, id: ast::NodeId) -> Ty<'tcx> { match self.tables.borrow().node_types.get(&id) { Some(&t) => t, None if self.err_count_since_creation() != 0 => self.tcx.types.err, @@ -1990,10 +1991,10 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { /// Registers an obligation for checking later, during regionck, that the type `ty` must /// outlive the region `r`. - pub fn register_wf_obligation(&self, - ty: Ty<'tcx>, - span: Span, - code: traits::ObligationCauseCode<'tcx>) + pub(crate) fn register_wf_obligation(&self, + ty: Ty<'tcx>, + span: Span, + code: traits::ObligationCauseCode<'tcx>) { // WF obligations never themselves fail, so no real need to give a detailed cause: let cause = traits::ObligationCause::new(span, self.body_id, code); @@ -2003,7 +2004,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } /// Registers obligations that all types appearing in `substs` are well-formed. - pub fn add_wf_bounds(&self, substs: &Substs<'tcx>, expr: &hir::Expr) + pub(crate) fn add_wf_bounds(&self, substs: &Substs<'tcx>, expr: &hir::Expr) { for ty in substs.types() { self.register_wf_obligation(ty, expr.span, traits::MiscObligation); @@ -2028,9 +2029,9 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { /// /// Then we will create a fresh region variable `'$0` and a fresh type variable `$1` for `'a` /// and `T`. This routine will add a region obligation `$1:'$0` and register it locally. - pub fn add_obligations_for_parameters(&self, - cause: traits::ObligationCause<'tcx>, - predicates: &ty::InstantiatedPredicates<'tcx>) + pub(crate) fn add_obligations_for_parameters(&self, + cause: traits::ObligationCause<'tcx>, + predicates: &ty::InstantiatedPredicates<'tcx>) { assert!(!predicates.has_escaping_regions()); @@ -2045,11 +2046,11 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // FIXME(arielb1): use this instead of field.ty everywhere // Only for fields! Returns for methods> // Indifferent to privacy flags - pub fn field_ty(&self, - span: Span, - field: &'tcx ty::FieldDef, - substs: &Substs<'tcx>) - -> Ty<'tcx> + pub(crate) fn field_ty(&self, + span: Span, + field: &'tcx ty::FieldDef, + substs: &Substs<'tcx>) + -> Ty<'tcx> { self.normalize_associated_types_in(span, &field.ty(self.tcx, substs)) @@ -2624,9 +2625,9 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { self.demand_eqtype(expr.span, expected, ty); } - pub fn check_expr_has_type_or_error(&self, - expr: &'gcx hir::Expr, - expected: Ty<'tcx>) -> Ty<'tcx> { + pub(crate) fn check_expr_has_type_or_error(&self, + expr: &'gcx hir::Expr, + expected: Ty<'tcx>) -> Ty<'tcx> { self.check_expr_meets_expectation_or_error(expr, ExpectHasType(expected)) } @@ -2703,10 +2704,10 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // declared on the impl declaration e.g., `impl for Vec<(A,B)>` // would return ($0, $1) where $0 and $1 are freshly instantiated type // variables. - pub fn impl_self_ty(&self, - span: Span, // (potential) receiver for this impl - did: DefId) - -> TypeAndSubsts<'tcx> { + pub(crate) fn impl_self_ty(&self, + span: Span, // (potential) receiver for this impl + did: DefId) + -> TypeAndSubsts<'tcx> { let ity = self.tcx.type_of(did); debug!("impl_self_ty: ity={:?}", ity); @@ -3246,10 +3247,10 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } } - pub fn check_struct_path(&self, - qpath: &hir::QPath, - node_id: ast::NodeId) - -> Option<(&'tcx ty::VariantDef, Ty<'tcx>)> { + pub(crate) fn check_struct_path(&self, + qpath: &hir::QPath, + node_id: ast::NodeId) + -> Option<(&'tcx ty::VariantDef, Ty<'tcx>)> { let path_span = match *qpath { hir::QPath::Resolved(_, ref path) => path.span, hir::QPath::TypeRelative(ref qself, _) => qself.span @@ -3955,11 +3956,11 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // Resolve associated value path into a base type and associated constant or method definition. // The newly resolved definition is written into `type_dependent_defs`. - pub fn resolve_ty_and_def_ufcs<'b>(&self, - qpath: &'b hir::QPath, - node_id: ast::NodeId, - span: Span) - -> (Def, Option>, &'b [hir::PathSegment]) + pub(crate) fn resolve_ty_and_def_ufcs<'b>(&self, + qpath: &'b hir::QPath, + node_id: ast::NodeId, + span: Span) + -> (Def, Option>, &'b [hir::PathSegment]) { let (ty, item_segment) = match *qpath { hir::QPath::Resolved(ref opt_qself, ref path) => { @@ -3991,9 +3992,9 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { (def, Some(ty), slice::ref_slice(&**item_segment)) } - pub fn check_decl_initializer(&self, - local: &'gcx hir::Local, - init: &'gcx hir::Expr) -> Ty<'tcx> + pub(crate) fn check_decl_initializer(&self, + local: &'gcx hir::Local, + init: &'gcx hir::Expr) -> Ty<'tcx> { let ref_bindings = local.pat.contains_ref_binding(); @@ -4015,7 +4016,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } } - pub fn check_decl_local(&self, local: &'gcx hir::Local) { + pub(crate) fn check_decl_local(&self, local: &'gcx hir::Local) { let t = self.local_ty(local.span, local.id); self.write_ty(local.id, t); @@ -4033,7 +4034,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } } - pub fn check_stmt(&self, stmt: &'gcx hir::Stmt) { + pub(crate) fn check_stmt(&self, stmt: &'gcx hir::Stmt) { // Don't do all the complex logic below for DeclItem. match stmt.node { hir::StmtDecl(ref decl, _) => { @@ -4078,7 +4079,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { self.has_errors.set(self.has_errors.get() | old_has_errors); } - pub fn check_block_no_value(&self, blk: &'gcx hir::Block) { + pub(crate) fn check_block_no_value(&self, blk: &'gcx hir::Block) { let unit = self.tcx.mk_nil(); let ty = self.check_block_with_expected(blk, ExpectHasType(unit)); @@ -4189,7 +4190,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { /// Given a `NodeId`, return the `FnDecl` of the method it is enclosed by and whether it is /// `fn main` if it is a method, `None` otherwise. - pub fn get_fn_decl(&self, blk_id: ast::NodeId) -> Option<(hir::FnDecl, bool)> { + pub(crate) fn get_fn_decl(&self, blk_id: ast::NodeId) -> Option<(hir::FnDecl, bool)> { // Get enclosing Fn, if it is a function or a trait method, unless there's a `loop` or // `while` before reaching it, as block tail returns are not available in them. if let Some(fn_id) = self.tcx.hir.get_return_block(blk_id) { @@ -4224,13 +4225,13 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { /// - Point out the method's return type as the reason for the expected type /// - Possible missing semicolon /// - Possible missing return type if the return type is the default, and not `fn main()` - pub fn suggest_mismatched_types_on_tail(&self, - err: &mut DiagnosticBuilder<'tcx>, - expression: &'gcx hir::Expr, - expected: Ty<'tcx>, - found: Ty<'tcx>, - cause_span: Span, - blk_id: ast::NodeId) { + pub(crate) fn suggest_mismatched_types_on_tail(&self, + err: &mut DiagnosticBuilder<'tcx>, + expression: &'gcx hir::Expr, + expected: Ty<'tcx>, + found: Ty<'tcx>, + cause_span: Span, + blk_id: ast::NodeId) { self.suggest_missing_semicolon(err, expression, expected, cause_span); if let Some((fn_decl, is_main)) = self.get_fn_decl(blk_id) { @@ -4351,13 +4352,13 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // Instantiates the given path, which must refer to an item with the given // number of type parameters and type. - pub fn instantiate_value_path(&self, - segments: &[hir::PathSegment], - opt_self_ty: Option>, - def: Def, - span: Span, - node_id: ast::NodeId) - -> Ty<'tcx> { + pub(crate) fn instantiate_value_path(&self, + segments: &[hir::PathSegment], + opt_self_ty: Option>, + def: Def, + span: Span, + node_id: ast::NodeId) + -> Ty<'tcx> { debug!("instantiate_value_path(path={:?}, def={:?}, node_id={})", segments, def, @@ -4758,7 +4759,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // Resolves `typ` by a single level if `typ` is a type variable. If no // resolution is possible, then an error is reported. - pub fn structurally_resolved_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> { + pub(crate) fn structurally_resolved_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> { self.structurally_resolve_type_or_else(sp, ty, || { self.tcx.types.err }) @@ -4785,9 +4786,9 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } } -pub fn check_bounds_are_used<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - generics: &hir::Generics, - ty: Ty<'tcx>) { +pub(crate) fn check_bounds_are_used<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, + generics: &hir::Generics, + ty: Ty<'tcx>) { debug!("check_bounds_are_used(n_tps={}, ty={:?})", generics.ty_params.len(), ty); diff --git a/src/librustc_typeck/check/op.rs b/src/librustc_typeck/check/op.rs index 032e37a34a887..5db6250e07057 100644 --- a/src/librustc_typeck/check/op.rs +++ b/src/librustc_typeck/check/op.rs @@ -23,11 +23,11 @@ use rustc::hir; impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { /// Check a `a = b` - pub fn check_binop_assign(&self, - expr: &'gcx hir::Expr, - op: hir::BinOp, - lhs_expr: &'gcx hir::Expr, - rhs_expr: &'gcx hir::Expr) -> Ty<'tcx> + pub(crate) fn check_binop_assign(&self, + expr: &'gcx hir::Expr, + op: hir::BinOp, + lhs_expr: &'gcx hir::Expr, + rhs_expr: &'gcx hir::Expr) -> Ty<'tcx> { let lhs_ty = self.check_expr_with_lvalue_pref(lhs_expr, PreferMutLvalue); @@ -58,11 +58,11 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } /// Check a potentially overloaded binary operator. - pub fn check_binop(&self, - expr: &'gcx hir::Expr, - op: hir::BinOp, - lhs_expr: &'gcx hir::Expr, - rhs_expr: &'gcx hir::Expr) -> Ty<'tcx> + pub(crate) fn check_binop(&self, + expr: &'gcx hir::Expr, + op: hir::BinOp, + lhs_expr: &'gcx hir::Expr, + rhs_expr: &'gcx hir::Expr) -> Ty<'tcx> { let tcx = self.tcx; @@ -331,11 +331,11 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { is_string_addition } - pub fn check_user_unop(&self, - ex: &'gcx hir::Expr, - operand_ty: Ty<'tcx>, - op: hir::UnOp) - -> Ty<'tcx> + pub(crate) fn check_user_unop(&self, + ex: &'gcx hir::Expr, + operand_ty: Ty<'tcx>, + op: hir::UnOp) + -> Ty<'tcx> { assert!(op.is_by_value()); match self.lookup_op_method(operand_ty, &[], Op::Unary(op, ex.span)) { diff --git a/src/librustc_typeck/check/regionck.rs b/src/librustc_typeck/check/regionck.rs index 82207428efc4f..c552f4b13ea0a 100644 --- a/src/librustc_typeck/check/regionck.rs +++ b/src/librustc_typeck/check/regionck.rs @@ -114,7 +114,7 @@ macro_rules! ignore_err { // PUBLIC ENTRY POINTS impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { - pub fn regionck_expr(&self, body: &'gcx hir::Body) { + pub(crate) fn regionck_expr(&self, body: &'gcx hir::Body) { let subject = self.tcx.hir.body_owner_def_id(body.id()); let id = body.value.id; let mut rcx = RegionCtxt::new(self, RepeatingScope(id), id, Subject(subject)); @@ -131,10 +131,10 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { /// Region checking during the WF phase for items. `wf_tys` are the /// types from which we should derive implied bounds, if any. - pub fn regionck_item(&self, - item_id: ast::NodeId, - span: Span, - wf_tys: &[Ty<'tcx>]) { + pub(crate) fn regionck_item(&self, + item_id: ast::NodeId, + span: Span, + wf_tys: &[Ty<'tcx>]) { debug!("regionck_item(item.id={:?}, wf_tys={:?}", item_id, wf_tys); let subject = self.tcx.hir.local_def_id(item_id); let mut rcx = RegionCtxt::new(self, RepeatingScope(item_id), item_id, Subject(subject)); @@ -145,9 +145,9 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { rcx.resolve_regions_and_report_errors(); } - pub fn regionck_fn(&self, - fn_id: ast::NodeId, - body: &'gcx hir::Body) { + pub(crate) fn regionck_fn(&self, + fn_id: ast::NodeId, + body: &'gcx hir::Body) { debug!("regionck_fn(id={})", fn_id); let subject = self.tcx.hir.body_owner_def_id(body.id()); let node_id = body.value.id; @@ -174,12 +174,12 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { /////////////////////////////////////////////////////////////////////////// // INTERNALS -pub struct RegionCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { - pub fcx: &'a FnCtxt<'a, 'gcx, 'tcx>, +pub(crate) struct RegionCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { + pub(crate) fcx: &'a FnCtxt<'a, 'gcx, 'tcx>, region_bound_pairs: Vec<(ty::Region<'tcx>, GenericKind<'tcx>)>, - pub region_maps: Rc, + pub(crate) region_maps: Rc, free_region_map: FreeRegionMap<'tcx>, @@ -222,14 +222,14 @@ impl<'a, 'gcx, 'tcx> Deref for RegionCtxt<'a, 'gcx, 'tcx> { } } -pub struct RepeatingScope(ast::NodeId); -pub struct Subject(DefId); +pub(crate) struct RepeatingScope(ast::NodeId); +pub(crate) struct Subject(DefId); impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { - pub fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>, - RepeatingScope(initial_repeating_scope): RepeatingScope, - initial_body_id: ast::NodeId, - Subject(subject): Subject) -> RegionCtxt<'a, 'gcx, 'tcx> { + pub(crate) fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>, + RepeatingScope(initial_repeating_scope): RepeatingScope, + initial_body_id: ast::NodeId, + Subject(subject): Subject) -> RegionCtxt<'a, 'gcx, 'tcx> { let region_maps = fcx.tcx.region_maps(subject); RegionCtxt { fcx: fcx, @@ -279,7 +279,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { /// region (the call). But that would make the *b illegal. Since we don't resolve, the type /// of b will be `&.i32` and then `*b` will require that `` be bigger than the let and /// the `*b` expression, so we will effectively resolve `` to be the block B. - pub fn resolve_type(&self, unresolved_ty: Ty<'tcx>) -> Ty<'tcx> { + pub(crate) fn resolve_type(&self, unresolved_ty: Ty<'tcx>) -> Ty<'tcx> { self.resolve_type_vars_if_possible(&unresolved_ty) } @@ -290,7 +290,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { } /// Try to resolve the type for the given node. - pub fn resolve_expr_type_adjusted(&mut self, expr: &hir::Expr) -> Ty<'tcx> { + pub(crate) fn resolve_expr_type_adjusted(&mut self, expr: &hir::Expr) -> Ty<'tcx> { let ty = self.tables.borrow().expr_ty_adjusted(expr); self.resolve_type(ty) } @@ -1052,10 +1052,10 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { Ok(cmt) } - pub fn mk_subregion_due_to_dereference(&mut self, - deref_span: Span, - minimum_lifetime: ty::Region<'tcx>, - maximum_lifetime: ty::Region<'tcx>) { + pub(crate) fn mk_subregion_due_to_dereference(&mut self, + deref_span: Span, + minimum_lifetime: ty::Region<'tcx>, + maximum_lifetime: ty::Region<'tcx>) { self.sub_regions(infer::DerefPointer(deref_span), minimum_lifetime, maximum_lifetime) } @@ -1482,10 +1482,10 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { /// Ensures that type is well-formed in `region`, which implies (among /// other things) that all borrowed data reachable via `ty` outlives /// `region`. - pub fn type_must_outlive(&self, - origin: infer::SubregionOrigin<'tcx>, - ty: Ty<'tcx>, - region: ty::Region<'tcx>) + pub(crate) fn type_must_outlive(&self, + origin: infer::SubregionOrigin<'tcx>, + ty: Ty<'tcx>, + region: ty::Region<'tcx>) { let ty = self.resolve_type(ty); diff --git a/src/librustc_typeck/check/upvar.rs b/src/librustc_typeck/check/upvar.rs index 59ca896b347f1..52ead380e9723 100644 --- a/src/librustc_typeck/check/upvar.rs +++ b/src/librustc_typeck/check/upvar.rs @@ -56,7 +56,7 @@ use rustc::util::nodemap::NodeMap; use std::collections::hash_map::Entry; impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { - pub fn closure_analyze(&self, body: &'gcx hir::Body) { + pub(crate) fn closure_analyze(&self, body: &'gcx hir::Body) { InferBorrowKindVisitor { fcx: self }.visit_body(body); // it's our job to process these. diff --git a/src/librustc_typeck/check/wfcheck.rs b/src/librustc_typeck/check/wfcheck.rs index 69cd141462875..16083a95277fa 100644 --- a/src/librustc_typeck/check/wfcheck.rs +++ b/src/librustc_typeck/check/wfcheck.rs @@ -25,7 +25,7 @@ use errors::DiagnosticBuilder; use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap}; use rustc::hir; -pub struct CheckTypeWellFormedVisitor<'a, 'tcx:'a> { +pub(crate) struct CheckTypeWellFormedVisitor<'a, 'tcx:'a> { tcx: TyCtxt<'a, 'tcx, 'tcx>, code: ObligationCauseCode<'tcx>, } @@ -63,7 +63,7 @@ impl<'a, 'gcx, 'tcx> CheckWfFcxBuilder<'a, 'gcx, 'tcx> { } impl<'a, 'gcx> CheckTypeWellFormedVisitor<'a, 'gcx> { - pub fn new(tcx: TyCtxt<'a, 'gcx, 'gcx>) + pub(crate) fn new(tcx: TyCtxt<'a, 'gcx, 'gcx>) -> CheckTypeWellFormedVisitor<'a, 'gcx> { CheckTypeWellFormedVisitor { tcx: tcx, diff --git a/src/librustc_typeck/check/writeback.rs b/src/librustc_typeck/check/writeback.rs index 81e5dae5477eb..6ace854478410 100644 --- a/src/librustc_typeck/check/writeback.rs +++ b/src/librustc_typeck/check/writeback.rs @@ -27,7 +27,7 @@ use std::mem; // Entry point impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { - pub fn resolve_type_vars_in_body(&self, body: &'gcx hir::Body) + pub(crate) fn resolve_type_vars_in_body(&self, body: &'gcx hir::Body) -> &'gcx ty::TypeckTables<'gcx> { let item_id = self.tcx.hir.body_owner(body.id()); let item_def_id = self.tcx.hir.local_def_id(item_id); diff --git a/src/librustc_typeck/check_unused.rs b/src/librustc_typeck/check_unused.rs index 1af55d4d840d9..d1f082fa409f5 100644 --- a/src/librustc_typeck/check_unused.rs +++ b/src/librustc_typeck/check_unused.rs @@ -60,7 +60,7 @@ impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for CheckVisitor<'a, 'tcx> { } } -pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { +pub(crate) fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { let mut used_trait_imports = DefIdSet(); for &body_id in tcx.hir.krate().bodies.keys() { let item_def_id = tcx.hir.body_owner_def_id(body_id); diff --git a/src/librustc_typeck/coherence/builtin.rs b/src/librustc_typeck/coherence/builtin.rs index 9305eff143652..0cedaf7ab7662 100644 --- a/src/librustc_typeck/coherence/builtin.rs +++ b/src/librustc_typeck/coherence/builtin.rs @@ -26,7 +26,7 @@ use rustc::hir::def_id::DefId; use rustc::hir::map as hir_map; use rustc::hir::{self, ItemImpl}; -pub fn check_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trait_def_id: DefId) { +pub(crate) fn check_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trait_def_id: DefId) { Checker { tcx, trait_def_id } .check(tcx.lang_items.drop_trait(), visit_implementation_of_drop) .check(tcx.lang_items.copy_trait(), visit_implementation_of_copy) @@ -172,9 +172,9 @@ fn visit_implementation_of_coerce_unsized<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } } -pub fn coerce_unsized_info<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - impl_did: DefId) - -> CoerceUnsizedInfo { +pub(crate) fn coerce_unsized_info<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, + impl_did: DefId) + -> CoerceUnsizedInfo { debug!("compute_coerce_unsized_info(impl_did={:?})", impl_did); let coerce_unsized_trait = tcx.lang_items.coerce_unsized_trait().unwrap(); diff --git a/src/librustc_typeck/coherence/inherent_impls.rs b/src/librustc_typeck/coherence/inherent_impls.rs index e24d766002187..3a308b2880289 100644 --- a/src/librustc_typeck/coherence/inherent_impls.rs +++ b/src/librustc_typeck/coherence/inherent_impls.rs @@ -29,9 +29,9 @@ use syntax::ast; use syntax_pos::Span; /// On-demand query: yields a map containing all types mapped to their inherent impls. -pub fn crate_inherent_impls<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - crate_num: CrateNum) - -> CrateInherentImpls { +pub(crate) fn crate_inherent_impls<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, + crate_num: CrateNum) + -> CrateInherentImpls { assert_eq!(crate_num, LOCAL_CRATE); let krate = tcx.hir.krate(); @@ -46,9 +46,9 @@ pub fn crate_inherent_impls<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } /// On-demand query: yields a vector of the inherent impls for a specific type. -pub fn inherent_impls<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - ty_def_id: DefId) - -> Rc> { +pub(crate) fn inherent_impls<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, + ty_def_id: DefId) + -> Rc> { assert!(ty_def_id.is_local()); // NB. Until we adopt the red-green dep-tracking algorithm (see diff --git a/src/librustc_typeck/coherence/inherent_impls_overlap.rs b/src/librustc_typeck/coherence/inherent_impls_overlap.rs index 078ae34bc524c..dfe781228b455 100644 --- a/src/librustc_typeck/coherence/inherent_impls_overlap.rs +++ b/src/librustc_typeck/coherence/inherent_impls_overlap.rs @@ -14,8 +14,8 @@ use rustc::hir::itemlikevisit::ItemLikeVisitor; use rustc::traits; use rustc::ty::{self, TyCtxt}; -pub fn crate_inherent_impls_overlap_check<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - crate_num: CrateNum) { +pub(crate) fn crate_inherent_impls_overlap_check<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, + crate_num: CrateNum) { assert_eq!(crate_num, LOCAL_CRATE); let krate = tcx.hir.krate(); krate.visit_all_item_likes(&mut InherentOverlapChecker { tcx }); diff --git a/src/librustc_typeck/coherence/mod.rs b/src/librustc_typeck/coherence/mod.rs index 165be49f7603d..35cbbad35e811 100644 --- a/src/librustc_typeck/coherence/mod.rs +++ b/src/librustc_typeck/coherence/mod.rs @@ -98,7 +98,7 @@ fn enforce_trait_manually_implementable(tcx: TyCtxt, impl_def_id: DefId, trait_d err.emit(); } -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { use self::builtin::coerce_unsized_info; use self::inherent_impls::{crate_inherent_impls, inherent_impls}; use self::inherent_impls_overlap::crate_inherent_impls_overlap_check; @@ -125,7 +125,7 @@ fn coherent_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, builtin::check_trait(tcx, def_id); } -pub fn check_coherence<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { +pub(crate) fn check_coherence<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { for &trait_def_id in tcx.hir.krate().trait_impls.keys() { tcx.coherent_trait((LOCAL_CRATE, trait_def_id)); } diff --git a/src/librustc_typeck/coherence/orphan.rs b/src/librustc_typeck/coherence/orphan.rs index 097720adad447..dc0bb5dfd1a5c 100644 --- a/src/librustc_typeck/coherence/orphan.rs +++ b/src/librustc_typeck/coherence/orphan.rs @@ -16,7 +16,7 @@ use rustc::ty::{self, TyCtxt}; use rustc::hir::itemlikevisit::ItemLikeVisitor; use rustc::hir; -pub fn check<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { +pub(crate) fn check<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { let mut orphan = OrphanChecker { tcx: tcx }; tcx.hir.krate().visit_all_item_likes(&mut orphan); } diff --git a/src/librustc_typeck/coherence/overlap.rs b/src/librustc_typeck/coherence/overlap.rs index 59ebae16d08ca..5ff2dadbd85d8 100644 --- a/src/librustc_typeck/coherence/overlap.rs +++ b/src/librustc_typeck/coherence/overlap.rs @@ -18,7 +18,7 @@ use syntax::ast; use rustc::hir; use rustc::hir::itemlikevisit::ItemLikeVisitor; -pub fn check_default_impls<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { +pub(crate) fn check_default_impls<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { let mut overlap = OverlapChecker { tcx }; // this secondary walk specifically checks for some other cases, @@ -26,7 +26,7 @@ pub fn check_default_impls<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { tcx.hir.krate().visit_all_item_likes(&mut overlap); } -pub fn check_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, node_id: ast::NodeId) { +pub(crate) fn check_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, node_id: ast::NodeId) { let impl_def_id = tcx.hir.local_def_id(node_id); let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap(); let trait_def_id = trait_ref.def_id; diff --git a/src/librustc_typeck/coherence/unsafety.rs b/src/librustc_typeck/coherence/unsafety.rs index 4672975d056b8..6c42bfdaebb39 100644 --- a/src/librustc_typeck/coherence/unsafety.rs +++ b/src/librustc_typeck/coherence/unsafety.rs @@ -15,7 +15,7 @@ use rustc::ty::TyCtxt; use rustc::hir::itemlikevisit::ItemLikeVisitor; use rustc::hir::{self, Unsafety}; -pub fn check<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { +pub(crate) fn check<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { let mut unsafety = UnsafetyChecker { tcx: tcx }; tcx.hir.krate().visit_all_item_likes(&mut unsafety); } diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 72bd084330dd3..76ffd361795c5 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -83,12 +83,12 @@ use rustc::hir::def_id::DefId; /////////////////////////////////////////////////////////////////////////// // Main entry point -pub fn collect_item_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { +pub(crate) fn collect_item_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { let mut visitor = CollectItemTypesVisitor { tcx: tcx }; tcx.hir.krate().visit_all_item_likes(&mut visitor.as_deep_visitor()); } -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { *providers = Providers { type_of, generics_of, @@ -117,7 +117,7 @@ pub fn provide(providers: &mut Providers) { /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy /// `get_type_parameter_bounds` requests, drawing the information from /// the AST (`hir::Generics`), recursively. -pub struct ItemCtxt<'a,'tcx:'a> { +pub(crate) struct ItemCtxt<'a,'tcx:'a> { tcx: TyCtxt<'a, 'tcx, 'tcx>, item_def_id: DefId, } @@ -181,7 +181,7 @@ impl<'a, 'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'a, 'tcx> { // Utility types and common code for the above passes. impl<'a, 'tcx> ItemCtxt<'a, 'tcx> { - pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_def_id: DefId) + pub(crate) fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_def_id: DefId) -> ItemCtxt<'a,'tcx> { ItemCtxt { tcx: tcx, @@ -191,7 +191,7 @@ impl<'a, 'tcx> ItemCtxt<'a, 'tcx> { } impl<'a,'tcx> ItemCtxt<'a,'tcx> { - pub fn to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> { + pub(crate) fn to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> { AstConv::ast_ty_to_ty(self, ast_ty) } } @@ -1563,17 +1563,17 @@ fn predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } } -pub enum SizedByDefault { Yes, No, } +pub(crate) enum SizedByDefault { Yes, No, } /// Translate the AST's notion of ty param bounds (which are an enum consisting of a newtyped Ty or /// a region) to ty's notion of ty param bounds, which can either be user-defined traits, or the /// built-in trait (formerly known as kind): Send. -pub fn compute_bounds<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>, - param_ty: ty::Ty<'tcx>, - ast_bounds: &[hir::TyParamBound], - sized_by_default: SizedByDefault, - span: Span) - -> Bounds<'tcx> +pub(crate) fn compute_bounds<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>, + param_ty: ty::Ty<'tcx>, + ast_bounds: &[hir::TyParamBound], + sized_by_default: SizedByDefault, + span: Span) + -> Bounds<'tcx> { let mut region_bounds = vec![]; let mut trait_bounds = vec![]; diff --git a/src/librustc_typeck/constrained_type_params.rs b/src/librustc_typeck/constrained_type_params.rs index 7742194dfe6e0..dc3dd2d0f0132 100644 --- a/src/librustc_typeck/constrained_type_params.rs +++ b/src/librustc_typeck/constrained_type_params.rs @@ -13,7 +13,7 @@ use rustc::ty::fold::{TypeFoldable, TypeVisitor}; use rustc::util::nodemap::FxHashSet; #[derive(Clone, PartialEq, Eq, Hash, Debug)] -pub struct Parameter(pub u32); +pub(crate) struct Parameter(pub(crate) u32); impl From for Parameter { fn from(param: ty::ParamTy) -> Self { Parameter(param.idx) } @@ -24,9 +24,9 @@ impl From for Parameter { } /// Return the set of parameters constrained by the impl header. -pub fn parameters_for_impl<'tcx>(impl_self_ty: Ty<'tcx>, - impl_trait_ref: Option>) - -> FxHashSet +pub(crate) fn parameters_for_impl<'tcx>(impl_self_ty: Ty<'tcx>, + impl_trait_ref: Option>) + -> FxHashSet { let vec = match impl_trait_ref { Some(tr) => parameters_for(&tr, false), @@ -40,9 +40,9 @@ pub fn parameters_for_impl<'tcx>(impl_self_ty: Ty<'tcx>, /// uniquely determined by `t` (see RFC 447). If it is true, return the list /// of parameters whose values are needed in order to constrain `ty` - these /// differ, with the latter being a superset, in the presence of projections. -pub fn parameters_for<'tcx, T>(t: &T, - include_nonconstraining: bool) - -> Vec +pub(crate) fn parameters_for<'tcx, T>(t: &T, + include_nonconstraining: bool) + -> Vec where T: TypeFoldable<'tcx> { @@ -86,10 +86,10 @@ impl<'tcx> TypeVisitor<'tcx> for ParameterCollector { } } -pub fn identify_constrained_type_params<'tcx>(tcx: ty::TyCtxt, - predicates: &[ty::Predicate<'tcx>], - impl_trait_ref: Option>, - input_parameters: &mut FxHashSet) +pub(crate) fn identify_constrained_type_params<'tcx>(tcx: ty::TyCtxt, + predicates: &[ty::Predicate<'tcx>], + impl_trait_ref: Option>, + input_parameters: &mut FxHashSet) { let mut predicates = predicates.to_owned(); setup_constraining_predicates(tcx, &mut predicates, impl_trait_ref, input_parameters); @@ -136,10 +136,10 @@ pub fn identify_constrained_type_params<'tcx>(tcx: ty::TyCtxt, /// which is determined by 1, which requires `U`, that is determined /// by 0. I should probably pick a less tangled example, but I can't /// think of any. -pub fn setup_constraining_predicates<'tcx>(tcx: ty::TyCtxt, - predicates: &mut [ty::Predicate<'tcx>], - impl_trait_ref: Option>, - input_parameters: &mut FxHashSet) +pub(crate) fn setup_constraining_predicates<'tcx>(tcx: ty::TyCtxt, + predicates: &mut [ty::Predicate<'tcx>], + impl_trait_ref: Option>, + input_parameters: &mut FxHashSet) { // The canonical way of doing the needed topological sort // would be a DFS, but getting the graph and its ownership diff --git a/src/librustc_typeck/impl_wf_check.rs b/src/librustc_typeck/impl_wf_check.rs index 14e48b9302964..6547b186a51b3 100644 --- a/src/librustc_typeck/impl_wf_check.rs +++ b/src/librustc_typeck/impl_wf_check.rs @@ -58,7 +58,7 @@ use syntax_pos::Span; /// impl<'a> Trait for Bar { type X = &'a i32; } /// ^ 'a is unused and appears in assoc type, error /// ``` -pub fn impl_wf_check<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { +pub(crate) fn impl_wf_check<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { // We will tag this as part of the WF check -- logically, it is, // but it's one that we must perform earlier than the rest of // WfCheck. diff --git a/src/librustc_typeck/lib.rs b/src/librustc_typeck/lib.rs index 9b829e6e3ff2e..2466257785bca 100644 --- a/src/librustc_typeck/lib.rs +++ b/src/librustc_typeck/lib.rs @@ -95,12 +95,11 @@ extern crate rustc_const_math; extern crate rustc_data_structures; extern crate rustc_errors as errors; -pub use rustc::dep_graph; -pub use rustc::hir; -pub use rustc::lint; -pub use rustc::middle; -pub use rustc::session; -pub use rustc::util; +use rustc::hir; +use rustc::lint; +use rustc::middle; +use rustc::session; +use rustc::util; use hir::map as hir_map; use rustc::infer::InferOk; @@ -118,7 +117,7 @@ use syntax_pos::Span; use std::iter; // NB: This module needs to be declared first so diagnostics are // registered before they are used. -pub mod diagnostics; +mod diagnostics; mod check; mod check_unused; @@ -129,9 +128,9 @@ mod impl_wf_check; mod coherence; mod variance; -pub struct TypeAndSubsts<'tcx> { - pub substs: &'tcx Substs<'tcx>, - pub ty: Ty<'tcx>, +struct TypeAndSubsts<'tcx> { + substs: &'tcx Substs<'tcx>, + ty: Ty<'tcx>, } fn require_c_abi_if_variadic(tcx: TyCtxt, diff --git a/src/librustc_typeck/variance/constraints.rs b/src/librustc_typeck/variance/constraints.rs index 284c9c5cfc398..fdaeb2ce32f57 100644 --- a/src/librustc_typeck/variance/constraints.rs +++ b/src/librustc_typeck/variance/constraints.rs @@ -26,8 +26,8 @@ use rustc_data_structures::transitive_relation::TransitiveRelation; use super::terms::*; use super::terms::VarianceTerm::*; -pub struct ConstraintContext<'a, 'tcx: 'a> { - pub terms_cx: TermsContext<'a, 'tcx>, +pub(crate) struct ConstraintContext<'a, 'tcx: 'a> { + pub(crate) terms_cx: TermsContext<'a, 'tcx>, // These are pointers to common `ConstantTerm` instances covariant: VarianceTermPtr<'a>, @@ -35,20 +35,20 @@ pub struct ConstraintContext<'a, 'tcx: 'a> { invariant: VarianceTermPtr<'a>, bivariant: VarianceTermPtr<'a>, - pub constraints: Vec>, + pub(crate) constraints: Vec>, /// This relation tracks the dependencies between the variance of /// various items. In particular, if `a < b`, then the variance of /// `a` depends on the sources of `b`. - pub dependencies: TransitiveRelation, + pub(crate) dependencies: TransitiveRelation, } /// Declares that the variable `decl_id` appears in a location with /// variance `variance`. #[derive(Copy, Clone)] -pub struct Constraint<'a> { - pub inferred: InferredIndex, - pub variance: &'a VarianceTerm<'a>, +pub(crate) struct Constraint<'a> { + pub(crate) inferred: InferredIndex, + pub(crate) variance: &'a VarianceTerm<'a>, } /// To build constriants, we visit one item (type, trait) at a time @@ -60,12 +60,12 @@ pub struct Constraint<'a> { /// /// then while we are visiting `Bar`, the `CurrentItem` would have /// the def-id and the start of `Foo`'s inferreds. -pub struct CurrentItem { +pub(crate) struct CurrentItem { def_id: DefId, inferred_start: InferredIndex, } -pub fn add_constraints_from_crate<'a, 'tcx>(terms_cx: TermsContext<'a, 'tcx>) +pub(crate) fn add_constraints_from_crate<'a, 'tcx>(terms_cx: TermsContext<'a, 'tcx>) -> ConstraintContext<'a, 'tcx> { let tcx = terms_cx.tcx; let covariant = terms_cx.arena.alloc(ConstantTerm(ty::Covariant)); diff --git a/src/librustc_typeck/variance/mod.rs b/src/librustc_typeck/variance/mod.rs index 7a9f35545e2f3..8322e8ca38c70 100644 --- a/src/librustc_typeck/variance/mod.rs +++ b/src/librustc_typeck/variance/mod.rs @@ -30,12 +30,12 @@ mod constraints; mod solve; /// Code to write unit tests of variance. -pub mod test; +pub(crate) mod test; /// Code for transforming variances. mod xform; -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { *providers = Providers { variances_of, crate_variances, diff --git a/src/librustc_typeck/variance/solve.rs b/src/librustc_typeck/variance/solve.rs index 495eb95419a90..dec9a23bcec4e 100644 --- a/src/librustc_typeck/variance/solve.rs +++ b/src/librustc_typeck/variance/solve.rs @@ -33,7 +33,7 @@ struct SolveContext<'a, 'tcx: 'a> { solutions: Vec, } -pub fn solve_constraints(constraints_cx: ConstraintContext) -> ty::CrateVariancesMap { +pub(crate) fn solve_constraints(constraints_cx: ConstraintContext) -> ty::CrateVariancesMap { let ConstraintContext { terms_cx, dependencies, constraints, .. } = constraints_cx; let mut solutions = vec![ty::Bivariant; terms_cx.inferred_terms.len()]; diff --git a/src/librustc_typeck/variance/terms.rs b/src/librustc_typeck/variance/terms.rs index 38457146a9714..3b715675aa94d 100644 --- a/src/librustc_typeck/variance/terms.rs +++ b/src/librustc_typeck/variance/terms.rs @@ -29,13 +29,13 @@ use util::nodemap::NodeMap; use self::VarianceTerm::*; -pub type VarianceTermPtr<'a> = &'a VarianceTerm<'a>; +pub(crate) type VarianceTermPtr<'a> = &'a VarianceTerm<'a>; #[derive(Copy, Clone, Debug)] -pub struct InferredIndex(pub usize); +pub(crate) struct InferredIndex(pub(crate) usize); #[derive(Copy, Clone)] -pub enum VarianceTerm<'a> { +pub(crate) enum VarianceTerm<'a> { ConstantTerm(ty::Variance), TransformTerm(VarianceTermPtr<'a>, VarianceTermPtr<'a>), InferredTerm(InferredIndex), @@ -58,26 +58,28 @@ impl<'a> fmt::Debug for VarianceTerm<'a> { // The first pass over the crate simply builds up the set of inferreds. -pub struct TermsContext<'a, 'tcx: 'a> { - pub tcx: TyCtxt<'a, 'tcx, 'tcx>, - pub arena: &'a TypedArena>, +pub(crate) struct TermsContext<'a, 'tcx: 'a> { + pub(crate) tcx: TyCtxt<'a, 'tcx, 'tcx>, + pub(crate) arena: &'a TypedArena>, // For marker types, UnsafeCell, and other lang items where // variance is hardcoded, records the item-id and the hardcoded // variance. - pub lang_items: Vec<(ast::NodeId, Vec)>, + pub(crate) lang_items: Vec<(ast::NodeId, Vec)>, // Maps from the node id of an item to the first inferred index // used for its type & region parameters. - pub inferred_starts: NodeMap, + pub(crate) inferred_starts: NodeMap, // Maps from an InferredIndex to the term for that variable. - pub inferred_terms: Vec>, + pub(crate) inferred_terms: Vec>, } -pub fn determine_parameters_to_be_inferred<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - arena: &'a mut TypedArena>) - -> TermsContext<'a, 'tcx> { +pub(crate) fn determine_parameters_to_be_inferred<'a, 'tcx>( + tcx: TyCtxt<'a, 'tcx, 'tcx>, + arena: &'a mut TypedArena>) + -> TermsContext<'a, 'tcx> +{ let mut terms_cx = TermsContext { tcx: tcx, arena: arena, diff --git a/src/librustc_typeck/variance/test.rs b/src/librustc_typeck/variance/test.rs index 1acadb7e77236..61d2811734c5a 100644 --- a/src/librustc_typeck/variance/test.rs +++ b/src/librustc_typeck/variance/test.rs @@ -12,7 +12,7 @@ use rustc::hir; use rustc::hir::itemlikevisit::ItemLikeVisitor; use rustc::ty::TyCtxt; -pub fn test_variance<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { +pub(crate) fn test_variance<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { tcx.hir.krate().visit_all_item_likes(&mut VarianceTest { tcx }); } diff --git a/src/librustc_typeck/variance/xform.rs b/src/librustc_typeck/variance/xform.rs index 7106ca4d420a8..8d62289f0eae7 100644 --- a/src/librustc_typeck/variance/xform.rs +++ b/src/librustc_typeck/variance/xform.rs @@ -10,7 +10,7 @@ use rustc::ty; -pub fn glb(v1: ty::Variance, v2: ty::Variance) -> ty::Variance { +pub(crate) fn glb(v1: ty::Variance, v2: ty::Variance) -> ty::Variance { // Greatest lower bound of the variance lattice as // defined in The Paper: // diff --git a/src/test/compile-fail-fulldeps/auxiliary/lint_for_crate.rs b/src/test/compile-fail-fulldeps/auxiliary/lint_for_crate.rs index fc53031e7f226..d3f921e0878ae 100644 --- a/src/test/compile-fail-fulldeps/auxiliary/lint_for_crate.rs +++ b/src/test/compile-fail-fulldeps/auxiliary/lint_for_crate.rs @@ -12,6 +12,7 @@ #![feature(plugin_registrar, rustc_private)] #![feature(box_syntax)] +#![feature(macro_vis_matcher)] #[macro_use] extern crate rustc; extern crate rustc_plugin; diff --git a/src/test/compile-fail-fulldeps/auxiliary/lint_group_plugin_test.rs b/src/test/compile-fail-fulldeps/auxiliary/lint_group_plugin_test.rs index 490aa0d469312..a0c72243d4821 100644 --- a/src/test/compile-fail-fulldeps/auxiliary/lint_group_plugin_test.rs +++ b/src/test/compile-fail-fulldeps/auxiliary/lint_group_plugin_test.rs @@ -12,6 +12,7 @@ #![feature(plugin_registrar)] #![feature(box_syntax, rustc_private)] +#![feature(macro_vis_matcher)] // Load rustc as a plugin to get macros #[macro_use] diff --git a/src/test/compile-fail-fulldeps/auxiliary/lint_plugin_test.rs b/src/test/compile-fail-fulldeps/auxiliary/lint_plugin_test.rs index 8647797270f9a..cbbfbd8060360 100644 --- a/src/test/compile-fail-fulldeps/auxiliary/lint_plugin_test.rs +++ b/src/test/compile-fail-fulldeps/auxiliary/lint_plugin_test.rs @@ -12,6 +12,7 @@ #![feature(plugin_registrar)] #![feature(box_syntax, rustc_private)] +#![feature(macro_vis_matcher)] extern crate syntax; diff --git a/src/test/run-pass-fulldeps/auxiliary/lint_for_crate.rs b/src/test/run-pass-fulldeps/auxiliary/lint_for_crate.rs index fc53031e7f226..d3f921e0878ae 100644 --- a/src/test/run-pass-fulldeps/auxiliary/lint_for_crate.rs +++ b/src/test/run-pass-fulldeps/auxiliary/lint_for_crate.rs @@ -12,6 +12,7 @@ #![feature(plugin_registrar, rustc_private)] #![feature(box_syntax)] +#![feature(macro_vis_matcher)] #[macro_use] extern crate rustc; extern crate rustc_plugin; diff --git a/src/test/run-pass-fulldeps/proc-macro/auxiliary/issue-40001-plugin.rs b/src/test/run-pass-fulldeps/proc-macro/auxiliary/issue-40001-plugin.rs index cf1a631937ba4..29b6cc012b393 100644 --- a/src/test/run-pass-fulldeps/proc-macro/auxiliary/issue-40001-plugin.rs +++ b/src/test/run-pass-fulldeps/proc-macro/auxiliary/issue-40001-plugin.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(box_syntax, plugin, plugin_registrar, rustc_private)] +#![feature(macro_vis_matcher)] #![crate_type = "dylib"] #[macro_use] diff --git a/src/test/ui-fulldeps/auxiliary/lint_group_plugin_test.rs b/src/test/ui-fulldeps/auxiliary/lint_group_plugin_test.rs index 490aa0d469312..a0c72243d4821 100644 --- a/src/test/ui-fulldeps/auxiliary/lint_group_plugin_test.rs +++ b/src/test/ui-fulldeps/auxiliary/lint_group_plugin_test.rs @@ -12,6 +12,7 @@ #![feature(plugin_registrar)] #![feature(box_syntax, rustc_private)] +#![feature(macro_vis_matcher)] // Load rustc as a plugin to get macros #[macro_use] diff --git a/src/test/ui-fulldeps/auxiliary/lint_plugin_test.rs b/src/test/ui-fulldeps/auxiliary/lint_plugin_test.rs index 8647797270f9a..cbbfbd8060360 100644 --- a/src/test/ui-fulldeps/auxiliary/lint_plugin_test.rs +++ b/src/test/ui-fulldeps/auxiliary/lint_plugin_test.rs @@ -12,6 +12,7 @@ #![feature(plugin_registrar)] #![feature(box_syntax, rustc_private)] +#![feature(macro_vis_matcher)] extern crate syntax;