]> git.lizzy.rs Git - rust.git/commitdiff
Properly parse '--extern-private' with name and path
authorAaron Hill <aa1ronham@gmail.com>
Thu, 21 Mar 2019 03:27:08 +0000 (23:27 -0400)
committerAaron Hill <aa1ronham@gmail.com>
Sun, 14 Apr 2019 04:37:25 +0000 (00:37 -0400)
src/librustc/middle/cstore.rs
src/librustc/session/config.rs
src/librustc/ty/context.rs
src/librustc_metadata/creader.rs
src/librustc_metadata/cstore.rs
src/librustc_metadata/cstore_impl.rs
src/librustc_privacy/lib.rs
src/test/ui/privacy/pub-priv-dep/pub-priv1.rs
src/tools/compiletest/src/header.rs
src/tools/compiletest/src/runtest.rs

index e4890977c9bd62357ad9e5786cb02076a9e79d46..d22de6c6476996ea85f254427de7fbb933b75784 100644 (file)
@@ -199,6 +199,7 @@ pub trait CrateStore {
 
     // "queries" used in resolve that aren't tracked for incremental compilation
     fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol;
+    fn crate_is_private_dep_untracked(&self, cnum: CrateNum) -> bool;
     fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator;
     fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh;
     fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum>;
index 7c0eab26b09b633b420fdd1a62144d0b4cc57347..92f9346ef6e47ce835b1adc5abfacc19f4c51cb7 100644 (file)
@@ -285,6 +285,7 @@ pub fn should_codegen(&self) -> bool {
 #[derive(Clone, Hash)]
 pub struct Externs(BTreeMap<String, BTreeSet<Option<String>>>);
 
+
 impl Externs {
     pub fn new(data: BTreeMap<String, BTreeSet<Option<String>>>) -> Externs {
         Externs(data)
@@ -299,6 +300,21 @@ pub fn iter<'a>(&'a self) -> BTreeMapIter<'a, String, BTreeSet<Option<String>>>
     }
 }
 
+// Similar to 'Externs', but used for the '--extern-private' option
+#[derive(Clone, Hash)]
+pub struct ExternPrivates(BTreeMap<String, BTreeSet<String>>);
+
+impl ExternPrivates {
+    pub fn get(&self, key: &str) -> Option<&BTreeSet<String>> {
+        self.0.get(key)
+    }
+
+    pub fn iter<'a>(&'a self) -> BTreeMapIter<'a, String, BTreeSet<String>> {
+        self.0.iter()
+    }
+}
+
+
 macro_rules! hash_option {
     ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [UNTRACKED]) => ({});
     ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [TRACKED]) => ({
@@ -428,9 +444,9 @@ pub struct Options {
 
         edition: Edition [TRACKED],
 
-        // The list of crates to consider private when
+        // The crates to consider private when
         // checking leaked private dependency types in public interfaces
-        extern_private: Vec<String> [TRACKED],
+        extern_private: ExternPrivates [UNTRACKED],
     }
 );
 
@@ -633,7 +649,7 @@ fn default() -> Options {
             cli_forced_thinlto_off: false,
             remap_path_prefix: Vec::new(),
             edition: DEFAULT_EDITION,
-            extern_private: Vec::new()
+            extern_private: ExternPrivates(BTreeMap::new())
         }
     }
 }
@@ -2315,10 +2331,25 @@ pub fn build_session_options_and_crate_config(
         )
     }
 
-    let extern_private = matches.opt_strs("extern-private");
+    let mut extern_private: BTreeMap<_, BTreeSet<_>> = BTreeMap::new();
+
+    for arg in matches.opt_strs("extern-private").into_iter() {
+        let mut parts = arg.splitn(2, '=');
+        let name = parts.next().unwrap_or_else(||
+            early_error(error_format, "--extern-private value must not be empty"));
+        let location = parts.next().map(|s| s.to_string()).unwrap_or_else(||
+            early_error(error_format, "--extern-private value must include a location"));
+
+
+        extern_private
+            .entry(name.to_owned())
+            .or_default()
+            .insert(location);
+
+    }
 
     let mut externs: BTreeMap<_, BTreeSet<_>> = BTreeMap::new();
-    for arg in matches.opt_strs("extern").into_iter().chain(matches.opt_strs("extern-private")) {
+    for arg in matches.opt_strs("extern").into_iter() {
         let mut parts = arg.splitn(2, '=');
         let name = parts.next().unwrap_or_else(||
             early_error(error_format, "--extern value must not be empty"));
@@ -2386,7 +2417,7 @@ pub fn build_session_options_and_crate_config(
             cli_forced_thinlto_off: disable_thinlto,
             remap_path_prefix,
             edition,
-            extern_private
+            extern_private: ExternPrivates(extern_private)
         },
         cfg,
     )
index 7dc4dee3fbf9164901f569377af4552690911141..8bfdd0801d40f712133c088865be5279d219b8c7 100644 (file)
@@ -1391,6 +1391,16 @@ pub fn def_path(self, id: DefId) -> hir_map::DefPath {
         }
     }
 
+    /// Returns whether or not the crate with CrateNum 'cnum'
+    /// is marked as a private dependency
+    pub fn is_private_dep(self, cnum: CrateNum) -> bool {
+        if cnum == LOCAL_CRATE {
+            false
+        } else {
+            self.cstore.crate_is_private_dep_untracked(cnum)
+        }
+    }
+
     #[inline]
     pub fn def_path_hash(self, def_id: DefId) -> hir_map::DefPathHash {
         if def_id.is_local() {
index 66daa4518bef6becdc8f5ffba921ec7ee2d88c63..53348e75aa9327e3f3624b4f171aff7b8e258448 100644 (file)
@@ -195,12 +195,29 @@ fn register_crate(
         ident: Symbol,
         span: Span,
         lib: Library,
-        dep_kind: DepKind
+        dep_kind: DepKind,
+        name: Symbol
     ) -> (CrateNum, Lrc<cstore::CrateMetadata>) {
         let crate_root = lib.metadata.get_root();
-        info!("register crate `extern crate {} as {}`", crate_root.name, ident);
         self.verify_no_symbol_conflicts(span, &crate_root);
 
+        let mut private_dep = false;
+        if let Some(s) = self.sess.opts.extern_private.get(&name.as_str()) {
+            for path in s {
+                let p = Some(path.as_str());
+                if p == lib.dylib.as_ref().and_then(|r| r.0.to_str()) ||
+                    p == lib.rlib.as_ref().and_then(|r| r.0.to_str()) {
+
+                    private_dep = true;
+                }
+            }
+        }
+
+
+        info!("register crate `extern crate {} as {}` (private_dep = {})",
+            crate_root.name, ident, private_dep);
+
+
         // Claim this crate number and cache it
         let cnum = self.cstore.alloc_new_crate_num();
 
@@ -272,7 +289,8 @@ fn register_crate(
                 dylib,
                 rlib,
                 rmeta,
-            }
+            },
+            private_dep
         };
 
         let cmeta = Lrc::new(cmeta);
@@ -390,7 +408,7 @@ fn resolve_crate<'b>(
                 Ok((cnum, data))
             }
             (LoadResult::Loaded(library), host_library) => {
-                Ok(self.register_crate(host_library, root, ident, span, library, dep_kind))
+                Ok(self.register_crate(host_library, root, ident, span, library, dep_kind, name))
             }
             _ => panic!()
         }
index d646879b4d45ddb6083eaabf493a0eb3e8afe867..22a13f37722b8cfced8117c8d8f7684b62ae7b37 100644 (file)
@@ -79,6 +79,10 @@ pub struct CrateMetadata {
     pub source: CrateSource,
 
     pub proc_macros: Option<Vec<(ast::Name, Lrc<SyntaxExtension>)>>,
+
+    /// Whether or not this crate should be consider a private dependency
+    /// for purposes of the 'exported_private_dependencies' lint
+    pub private_dep: bool
 }
 
 pub struct CStore {
@@ -114,7 +118,8 @@ pub(super) fn alloc_new_crate_num(&self) -> CrateNum {
     }
 
     pub(super) fn get_crate_data(&self, cnum: CrateNum) -> Lrc<CrateMetadata> {
-        self.metas.borrow()[cnum].clone().unwrap()
+        self.metas.borrow()[cnum].clone()
+            .unwrap_or_else(|| panic!("Failed to get crate data for {:?}", cnum))
     }
 
     pub(super) fn set_crate_data(&self, cnum: CrateNum, data: Lrc<CrateMetadata>) {
index 995532a00cd6e98c91e8a06b8602658bbe27607b..75671facf9446058851009af744b9f3fcb22d176 100644 (file)
@@ -399,6 +399,7 @@ pub fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind {
         r
     }
 
+
     pub fn crate_edition_untracked(&self, cnum: CrateNum) -> Edition {
         self.get_crate_data(cnum).root.edition
     }
@@ -494,6 +495,10 @@ fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol
         self.get_crate_data(cnum).name
     }
 
+    fn crate_is_private_dep_untracked(&self, cnum: CrateNum) -> bool {
+        self.get_crate_data(cnum).private_dep
+    }
+
     fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator
     {
         self.get_crate_data(cnum).root.disambiguator
index 9a8970b2935e091540478ad025818ec5ec88e50e..44621e5dc95d1b2b823f810fc109a6f7c64c780a 100644 (file)
@@ -1540,7 +1540,6 @@ struct SearchInterfaceForPrivateItemsVisitor<'a, 'tcx: 'a> {
     has_pub_restricted: bool,
     has_old_errors: bool,
     in_assoc_ty: bool,
-    private_crates: FxHashSet<CrateNum>
 }
 
 impl<'a, 'tcx: 'a> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
@@ -1622,7 +1621,7 @@ fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display)
     /// 2. It comes from a private crate
     fn leaks_private_dep(&self, item_id: DefId) -> bool {
         let ret = self.required_visibility == ty::Visibility::Public &&
-            self.private_crates.contains(&item_id.krate);
+            self.tcx.is_private_dep(item_id.krate);
 
         log::debug!("leaks_private_dep(item_id={:?})={}", item_id, ret);
         return ret;
@@ -1640,7 +1639,6 @@ struct PrivateItemsInPublicInterfacesVisitor<'a, 'tcx: 'a> {
     tcx: TyCtxt<'a, 'tcx, 'tcx>,
     has_pub_restricted: bool,
     old_error_set: &'a HirIdSet,
-    private_crates: FxHashSet<CrateNum>
 }
 
 impl<'a, 'tcx> PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
@@ -1678,7 +1676,6 @@ fn check(&self, item_id: hir::HirId, required_visibility: ty::Visibility)
             has_pub_restricted: self.has_pub_restricted,
             has_old_errors,
             in_assoc_ty: false,
-            private_crates: self.private_crates.clone()
         }
     }
 
@@ -1876,17 +1873,11 @@ fn check_private_in_public<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>, krate: CrateNum) {
         pub_restricted_visitor.has_pub_restricted
     };
 
-    let private_crates: FxHashSet<CrateNum> = tcx.sess.opts.extern_private.iter()
-        .flat_map(|c| {
-            tcx.crates().iter().find(|&&krate| &tcx.crate_name(krate) == c).cloned()
-        }).collect();
-
     // Check for private types and traits in public interfaces.
     let mut visitor = PrivateItemsInPublicInterfacesVisitor {
         tcx,
         has_pub_restricted,
         old_error_set: &visitor.old_error_set,
-        private_crates
     };
     krate.visit_all_item_likes(&mut DeepVisitor::new(&mut visitor));
 }
index 9ebc96017fe9c659328db839c5e890ffe4722b4c..784615354a95c6f5e105a4b5eb957bac7888d452 100644 (file)
@@ -1,6 +1,6 @@
  // aux-build:priv_dep.rs
  // aux-build:pub_dep.rs
- // compile-flags: --extern-private priv_dep
+ // extern-private:priv_dep
 #![deny(exported_private_dependencies)]
 
 // This crate is a private dependency
index 2fe837e99d33f916f00e4f2b32b3ef7c0520a262..c548b1efa75cbdc88953c83b6ad5f057d2b3adb1 100644 (file)
@@ -286,6 +286,9 @@ pub struct TestProps {
     // directory as the test, but for backwards compatibility reasons
     // we also check the auxiliary directory)
     pub aux_builds: Vec<String>,
+    // A list of crates to pass '--extern-private name:PATH' flags for
+    // This should be a subset of 'aux_build'
+    pub extern_private: Vec<String>,
     // Environment settings to use for compiling
     pub rustc_env: Vec<(String, String)>,
     // Environment settings to use during execution
@@ -353,6 +356,7 @@ pub fn new() -> Self {
             run_flags: None,
             pp_exact: None,
             aux_builds: vec![],
+            extern_private: vec![],
             revisions: vec![],
             rustc_env: vec![],
             exec_env: vec![],
@@ -469,6 +473,10 @@ fn load_from(&mut self, testfile: &Path, cfg: Option<&str>, config: &Config) {
                 self.aux_builds.push(ab);
             }
 
+            if let Some(ep) = config.parse_extern_private(ln) {
+                self.extern_private.push(ep);
+            }
+
             if let Some(ee) = config.parse_env(ln, "exec-env") {
                 self.exec_env.push(ee);
             }
@@ -610,6 +618,10 @@ fn parse_aux_build(&self, line: &str) -> Option<String> {
             .map(|r| r.trim().to_string())
     }
 
+    fn parse_extern_private(&self, line: &str) -> Option<String> {
+        self.parse_name_value_directive(line, "extern-private")
+    }
+
     fn parse_compile_flags(&self, line: &str) -> Option<String> {
         self.parse_name_value_directive(line, "compile-flags")
     }
index 2021dd513aa6209c3207715f24c19c11c2899397..cec1d83eb0262364251ea4341b87ac6ca715c2e3 100644 (file)
@@ -74,6 +74,17 @@ pub fn dylib_env_var() -> &'static str {
     }
 }
 
+/// The platform-specific library file extension
+pub fn lib_extension() -> &'static str {
+    if cfg!(windows) {
+        ".dll"
+    } else if cfg!(target_os = "macos") {
+        ".dylib"
+    } else {
+        ".so"
+    }
+}
+
 #[derive(Debug, PartialEq)]
 pub enum DiffLine {
     Context(String),
@@ -1585,6 +1596,13 @@ fn compose_and_run_compiler(&self, mut rustc: Command, input: Option<String>) ->
             create_dir_all(&aux_dir).unwrap();
         }
 
+        for priv_dep in &self.props.extern_private {
+            let lib_name = format!("lib{}{}", priv_dep, lib_extension());
+            rustc
+                .arg("--extern-private")
+                .arg(format!("{}={}", priv_dep, aux_dir.join(lib_name).to_str().unwrap()));
+        }
+
         for rel_ab in &self.props.aux_builds {
             let aux_testpaths = self.compute_aux_test_paths(rel_ab);
             let aux_props =