Extract privacy checking from name resolution

This commit is the culmination of my recent effort to refine Rust's notion of
privacy and visibility among crates. The major goals of this commit were to
remove privacy checking from resolve for the sake of sane error messages, and to
attempt a much more rigid and well-tested implementation of visibility
throughout rust. The implemented rules for name visibility are:

1. Everything pub from the root namespace is visible to anyone
2. You may access any private item of your ancestors.

"Accessing a private item" depends on what the item is, so for a function this
means that you can call it, but for a module it means that you can look inside
of it. Once you look inside a private module, any accessed item must be "pub
from the root" where the new root is the private module that you looked into.
These rules required some more analysis results to get propagated from trans to
privacy in the form of a few hash tables.

I added a new test in which my goal was to showcase all of the privacy nuances
of the language, and I hope to place any new bugs into this file to prevent
regressions.

Overall, I was unable to completely remove the notion of privacy from resolve.
One use of privacy is for dealing with glob imports. Essentially a glob import
can only import *public* items from the destination, and because this must be
done at namespace resolution time, resolve must maintain the notion of "what
items are public in a module". There are some sad approximations of privacy, but
I unfortunately can't see clear methods to extract them outside.

The other use case of privacy in resolve now is one that must stick around
regardless of glob imports. When dealing with privacy, checking a private path
needs to know "what the last private thing was" when looking at a path. Resolve
is the only compiler pass which knows the answer to this question, so it
maintains the answer on a per-path resolution basis (works similarly to the
def_map generated).

Closes #8215
This commit is contained in:
Alex Crichton 2013-10-05 14:37:39 -07:00
parent 8eb28bb7dc
commit 439e2770be
13 changed files with 1543 additions and 1187 deletions

View File

@ -199,7 +199,6 @@ pub fn phase_2_configure_and_expand(sess: Session,
pub struct CrateAnalysis {
exp_map2: middle::resolve::ExportMap2,
exported_items: @middle::privacy::ExportedItems,
ty_cx: ty::ctxt,
maps: astencode::Maps,
reachable: @mut HashSet<ast::NodeId>
@ -229,7 +228,9 @@ pub fn phase_3_run_analysis_passes(sess: Session,
let middle::resolve::CrateMap {
def_map: def_map,
exp_map2: exp_map2,
trait_map: trait_map
trait_map: trait_map,
external_exports: external_exports,
last_private_map: last_private_map
} =
time(time_passes, "resolution", (), |_|
middle::resolve::resolve_crate(sess, lang_items, crate));
@ -261,9 +262,10 @@ pub fn phase_3_run_analysis_passes(sess: Session,
middle::check_const::check_crate(sess, crate, ast_map, def_map,
method_map, ty_cx));
let exported_items =
time(time_passes, "privacy checking", (), |_|
middle::privacy::check_crate(ty_cx, &method_map, &exp_map2, crate));
let maps = (external_exports, last_private_map);
time(time_passes, "privacy checking", maps, |(a, b)|
middle::privacy::check_crate(ty_cx, &method_map, &exp_map2,
a, b, crate));
time(time_passes, "effect checking", (), |_|
middle::effect::check_crate(ty_cx, method_map, crate));
@ -305,7 +307,6 @@ pub fn phase_3_run_analysis_passes(sess: Session,
CrateAnalysis {
exp_map2: exp_map2,
exported_items: @exported_items,
ty_cx: ty_cx,
maps: astencode::Maps {
root_map: root_map,

View File

@ -837,8 +837,9 @@ fn each_child_of_item_or_crate(intr: @ident_interner,
let def_like = item_to_def_like(child_item_doc,
child_def_id,
cdata.cnum);
callback(def_like, token::str_to_ident(name),
item_visibility(child_item_doc));
// These items have a public visibility because they're part of
// a public re-export.
callback(def_like, token::str_to_ident(name), ast::public);
}
}

View File

@ -58,7 +58,6 @@ pub struct EncodeParams<'self> {
diag: @mut span_handler,
tcx: ty::ctxt,
reexports2: middle::resolve::ExportMap2,
exported_items: @middle::privacy::ExportedItems,
item_symbols: &'self HashMap<ast::NodeId, ~str>,
discrim_symbols: &'self HashMap<ast::NodeId, @str>,
non_inlineable_statics: &'self HashSet<ast::NodeId>,
@ -89,7 +88,6 @@ pub struct EncodeContext<'self> {
tcx: ty::ctxt,
stats: @mut Stats,
reexports2: middle::resolve::ExportMap2,
exported_items: @middle::privacy::ExportedItems,
item_symbols: &'self HashMap<ast::NodeId, ~str>,
discrim_symbols: &'self HashMap<ast::NodeId, @str>,
non_inlineable_statics: &'self HashSet<ast::NodeId>,
@ -1277,12 +1275,7 @@ fn my_visit_item(i:@item, items: ast_map::map, ebml_w:&writer::Encoder,
let mut ebml_w = ebml_w.clone();
// See above
let ecx : &EncodeContext = unsafe { cast::transmute(ecx_ptr) };
let vis = if ecx.exported_items.contains(&i.id) {
ast::public
} else {
ast::inherited
};
encode_info_for_item(ecx, &mut ebml_w, i, index, *pt, vis);
encode_info_for_item(ecx, &mut ebml_w, i, index, *pt, i.vis);
}
_ => fail2!("bad item")
}
@ -1628,7 +1621,7 @@ impl<'self> Visitor<()> for ImplVisitor<'self> {
// Load eagerly if this is an implementation of the Drop trait
// or if the trait is not defined in this crate.
if def_id == self.ecx.tcx.lang_items.drop_trait().unwrap() ||
if Some(def_id) == self.ecx.tcx.lang_items.drop_trait() ||
def_id.crate != LOCAL_CRATE {
self.ebml_w.start_tag(tag_impls_impl);
encode_def_id(self.ebml_w, local_def(item.id));
@ -1744,7 +1737,6 @@ pub fn encode_metadata(parms: EncodeParams, crate: &Crate) -> ~[u8] {
diag,
tcx,
reexports2,
exported_items,
discrim_symbols,
cstore,
encode_inlined_item,
@ -1760,7 +1752,6 @@ pub fn encode_metadata(parms: EncodeParams, crate: &Crate) -> ~[u8] {
tcx: tcx,
stats: stats,
reexports2: reexports2,
exported_items: exported_items,
item_symbols: item_symbols,
discrim_symbols: discrim_symbols,
non_inlineable_statics: non_inlineable_statics,

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -3034,7 +3034,6 @@ pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::encode_
diag: diag,
tcx: cx.tcx,
reexports2: cx.exp_map2,
exported_items: cx.exported_items,
item_symbols: item_symbols,
discrim_symbols: discrim_symbols,
non_inlineable_statics: &cx.non_inlineable_statics,
@ -3116,7 +3115,6 @@ pub fn trans_crate(sess: session::Session,
llmod_id,
analysis.ty_cx,
analysis.exp_map2,
analysis.exported_items,
analysis.maps,
symbol_hasher,
link_meta,

View File

@ -49,7 +49,6 @@ pub struct CrateContext {
intrinsics: HashMap<&'static str, ValueRef>,
item_vals: HashMap<ast::NodeId, ValueRef>,
exp_map2: resolve::ExportMap2,
exported_items: @privacy::ExportedItems,
reachable: @mut HashSet<ast::NodeId>,
item_symbols: HashMap<ast::NodeId, ~str>,
link_meta: LinkMeta,
@ -125,7 +124,6 @@ impl CrateContext {
name: &str,
tcx: ty::ctxt,
emap2: resolve::ExportMap2,
exported_items: @privacy::ExportedItems,
maps: astencode::Maps,
symbol_hasher: hash::State,
link_meta: LinkMeta,
@ -185,7 +183,6 @@ impl CrateContext {
intrinsics: intrinsics,
item_vals: HashMap::new(),
exp_map2: emap2,
exported_items: exported_items,
reachable: reachable,
item_symbols: HashMap::new(),
link_meta: link_meta,

View File

@ -702,32 +702,6 @@ pub fn struct_def_is_tuple_like(struct_def: &ast::struct_def) -> bool {
struct_def.ctor_id.is_some()
}
pub fn visibility_to_privacy(visibility: visibility) -> Privacy {
match visibility {
public => Public,
inherited | private => Private
}
}
pub fn variant_visibility_to_privacy(visibility: visibility,
enclosing_is_public: bool)
-> Privacy {
if enclosing_is_public {
match visibility {
public | inherited => Public,
private => Private
}
} else {
visibility_to_privacy(visibility)
}
}
#[deriving(Eq)]
pub enum Privacy {
Private,
Public
}
/// Returns true if the given pattern consists solely of an identifier
/// and false otherwise.
pub fn pat_is_ident(pat: @ast::Pat) -> bool {

View File

@ -0,0 +1,45 @@
// Copyright 2013 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 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Make sure that globs only bring in public things.
use bar::*;
mod bar {
use import = self::fpriv;
fn fpriv() {}
extern {
fn epriv();
}
enum A { A1 }
pub enum B { B1 }
struct C;
type D = int;
}
fn foo<T>() {}
fn main() {
fpriv(); //~ ERROR: unresolved
epriv(); //~ ERROR: unresolved
A1; //~ ERROR: unresolved
B1;
C; //~ ERROR: unresolved
import(); //~ ERROR: unresolved
foo::<A>(); //~ ERROR: undeclared
//~^ ERROR: undeclared
foo::<C>(); //~ ERROR: undeclared
//~^ ERROR: undeclared
foo::<D>(); //~ ERROR: undeclared
//~^ ERROR: undeclared
}

View File

@ -0,0 +1,168 @@
// Copyright 2013 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 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[no_std]; // makes debugging this test *a lot* easier (during resolve)
mod bar {
// shouln't bring in too much
pub use self::glob::*;
// can't publicly re-export private items
pub use self::baz::{foo, bar};
//~^ ERROR: function `bar` is private
pub use self::private::ppriv;
//~^ ERROR: function `ppriv` is private
pub struct A;
impl A {
pub fn foo() {}
fn bar() {}
pub fn foo2(&self) {}
fn bar2(&self) {}
}
pub enum Enum {
priv Priv,
Pub
}
mod baz {
pub struct A;
impl A {
pub fn foo() {}
fn bar() {}
pub fn foo2(&self) {}
fn bar2(&self) {}
}
// both of these are re-exported by `bar`, but only one should be
// validly re-exported
pub fn foo() {}
fn bar() {}
}
extern {
fn epriv();
pub fn epub();
}
fn test() {
self::Priv;
self::Pub;
unsafe {
epriv();
epub();
}
self::baz::A;
self::baz::A::foo();
self::baz::A::bar(); //~ ERROR: method `bar` is private
self::baz::A.foo2();
self::baz::A.bar2(); //~ ERROR: method `bar2` is private
// this used to cause an ICE in privacy traversal.
super::gpub();
}
mod glob {
pub fn gpub() {}
fn gpriv() {}
}
mod private {
fn ppriv() {}
}
}
pub fn gpub() {}
fn lol() {
bar::A;
bar::A::foo();
bar::A::bar(); //~ ERROR: method `bar` is private
bar::A.foo2();
bar::A.bar2(); //~ ERROR: method `bar2` is private
}
mod foo {
fn test() {
::bar::A::foo();
::bar::A::bar(); //~ ERROR: method `bar` is private
::bar::A.foo2();
::bar::A.bar2(); //~ ERROR: method `bar2` is private
::bar::baz::A::foo(); //~ ERROR: method `foo` is private
::bar::baz::A::bar(); //~ ERROR: method `bar` is private
::bar::baz::A.foo2(); //~ ERROR: struct `A` is private
::bar::baz::A.bar2(); //~ ERROR: struct `A` is private
//~^ ERROR: method `bar2` is private
::lol();
::bar::Priv; //~ ERROR: variant `Priv` is private
::bar::Pub;
unsafe {
::bar::epriv(); //~ ERROR: function `epriv` is private
::bar::epub();
}
::bar::foo();
::bar::bar();
::bar::gpub();
::bar::baz::foo(); //~ ERROR: function `foo` is private
::bar::baz::bar(); //~ ERROR: function `bar` is private
}
fn test2() {
use bar::baz::{foo, bar};
//~^ ERROR: function `foo` is private
//~^^ ERROR: function `bar` is private
foo();
bar();
}
fn test3() {
use bar::baz;
//~^ ERROR: module `baz` is private
}
fn test4() {
use bar::{foo, bar};
foo();
bar();
}
fn test5() {
use bar;
bar::foo();
bar::bar();
}
}
pub mod mytest {
// Even though the inner `A` struct is a publicly exported item (usable from
// external crates through `foo::foo`, it should not be accessible through
// its definition path (which has the private `i` module).
use self::foo::foo;
use self::foo::i::A; //~ ERROR: type `A` is private
pub mod foo {
pub use foo = self::i::A;
mod i {
pub struct A;
}
}
}
#[start] fn main(_: int, _: **u8) -> int { 3 }

View File

@ -0,0 +1,37 @@
// Copyright 2013 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 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[no_std]; // makes debugging this test *a lot* easier (during resolve)
// Test to make sure that globs don't leak in regular `use` statements.
mod bar {
pub use self::glob::*;
mod glob {
use foo;
}
}
pub fn foo() {}
fn test1() {
use bar::foo; //~ ERROR: unresolved import
//~^ ERROR: failed to resolve
}
fn test2() {
use bar::glob::foo;
//~^ ERROR: there is no
//~^^ ERROR: failed to resolve
}
#[start] fn main(_: int, _: **u8) -> int { 3 }

View File

@ -0,0 +1,32 @@
// Copyright 2013 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 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[no_std]; // makes debugging this test *a lot* easier (during resolve)
// Test to make sure that private items imported through globs remain private
// when they're used.
mod bar {
pub use self::glob::*;
mod glob {
fn gpriv() {}
}
}
pub fn foo() {}
fn test1() {
use bar::gpriv; //~ ERROR: unresolved import
//~^ ERROR: failed to resolve
gpriv();
}
#[start] fn main(_: int, _: **u8) -> int { 3 }

View File

@ -0,0 +1,31 @@
// Copyright 2013 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 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[no_std]; // makes debugging this test *a lot* easier (during resolve)
// Test to make sure that private items imported through globs remain private
// when they're used.
mod bar {
pub use self::glob::*;
mod glob {
fn gpriv() {}
}
}
pub fn foo() {}
fn test2() {
use bar::glob::gpriv; //~ ERROR: function `gpriv` is private
gpriv();
}
#[start] fn main(_: int, _: **u8) -> int { 3 }