]>
Commit | Line | Data |
---|---|---|
1b1a35ee | 1 | #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] |
dc9dc135 | 2 | #![feature(in_band_lifetimes)] |
0bf4aa26 | 3 | #![feature(nll)] |
29967ef6 XL |
4 | #![feature(control_flow_enum)] |
5 | #![feature(try_blocks)] | |
fc512014 | 6 | #![feature(associated_type_defaults)] |
dfeec247 | 7 | #![recursion_limit = "256"] |
e9174d1e | 8 | |
94222f64 | 9 | use rustc_ast::MacroDef; |
74b04a01 | 10 | use rustc_attr as attr; |
0731742a | 11 | use rustc_data_structures::fx::FxHashSet; |
dfeec247 XL |
12 | use rustc_errors::struct_span_err; |
13 | use rustc_hir as hir; | |
14 | use rustc_hir::def::{DefKind, Res}; | |
94222f64 XL |
15 | use rustc_hir::def_id::{DefId, LocalDefId, LocalDefIdSet}; |
16 | use rustc_hir::def_id::{CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE}; | |
dfeec247 XL |
17 | use rustc_hir::intravisit::{self, DeepVisitor, NestedVisitorMap, Visitor}; |
18 | use rustc_hir::{AssocItemKind, HirIdSet, Node, PatKind}; | |
ba9703b0 XL |
19 | use rustc_middle::bug; |
20 | use rustc_middle::hir::map::Map; | |
21 | use rustc_middle::middle::privacy::{AccessLevel, AccessLevels}; | |
29967ef6 | 22 | use rustc_middle::span_bug; |
c295e0f8 | 23 | use rustc_middle::thir::abstract_const::Node as ACNode; |
ba9703b0 XL |
24 | use rustc_middle::ty::fold::TypeVisitor; |
25 | use rustc_middle::ty::query::Providers; | |
5869c6ff XL |
26 | use rustc_middle::ty::subst::{InternalSubsts, Subst}; |
27 | use rustc_middle::ty::{self, Const, GenericParamDefKind, TraitRef, Ty, TyCtxt, TypeFoldable}; | |
ba9703b0 | 28 | use rustc_session::lint; |
dfeec247 | 29 | use rustc_span::hygiene::Transparency; |
94222f64 | 30 | use rustc_span::symbol::{kw, sym, Ident}; |
dfeec247 | 31 | use rustc_span::Span; |
5869c6ff | 32 | use rustc_trait_selection::traits::const_evaluatable::{self, AbstractConst}; |
85aaf69f | 33 | |
0731742a | 34 | use std::marker::PhantomData; |
29967ef6 | 35 | use std::ops::ControlFlow; |
dfeec247 | 36 | use std::{cmp, fmt, mem}; |
85aaf69f | 37 | |
0731742a XL |
38 | //////////////////////////////////////////////////////////////////////////////// |
39 | /// Generic infrastructure used to implement specific visitors below. | |
40 | //////////////////////////////////////////////////////////////////////////////// | |
41 | ||
42 | /// Implemented to visit all `DefId`s in a type. | |
43 | /// Visiting `DefId`s is useful because visibilities and reachabilities are attached to them. | |
44 | /// The idea is to visit "all components of a type", as documented in | |
29967ef6 | 45 | /// <https://github.com/rust-lang/rfcs/blob/master/text/2145-type-privacy.md#how-to-determine-visibility-of-a-type>. |
9fa01778 XL |
46 | /// The default type visitor (`TypeVisitor`) does most of the job, but it has some shortcomings. |
47 | /// First, it doesn't have overridable `fn visit_trait_ref`, so we have to catch trait `DefId`s | |
0731742a XL |
48 | /// manually. Second, it doesn't visit some type components like signatures of fn types, or traits |
49 | /// in `impl Trait`, see individual comments in `DefIdVisitorSkeleton::visit_ty`. | |
dc9dc135 | 50 | trait DefIdVisitor<'tcx> { |
fc512014 XL |
51 | type BreakTy = (); |
52 | ||
dc9dc135 | 53 | fn tcx(&self) -> TyCtxt<'tcx>; |
dfeec247 XL |
54 | fn shallow(&self) -> bool { |
55 | false | |
56 | } | |
57 | fn skip_assoc_tys(&self) -> bool { | |
58 | false | |
59 | } | |
29967ef6 XL |
60 | fn visit_def_id( |
61 | &mut self, | |
62 | def_id: DefId, | |
63 | kind: &str, | |
64 | descr: &dyn fmt::Display, | |
fc512014 | 65 | ) -> ControlFlow<Self::BreakTy>; |
0731742a XL |
66 | |
67 | /// Not overridden, but used to actually visit types and traits. | |
dc9dc135 | 68 | fn skeleton(&mut self) -> DefIdVisitorSkeleton<'_, 'tcx, Self> { |
0731742a XL |
69 | DefIdVisitorSkeleton { |
70 | def_id_visitor: self, | |
71 | visited_opaque_tys: Default::default(), | |
72 | dummy: Default::default(), | |
73 | } | |
74 | } | |
fc512014 | 75 | fn visit(&mut self, ty_fragment: impl TypeFoldable<'tcx>) -> ControlFlow<Self::BreakTy> { |
0731742a XL |
76 | ty_fragment.visit_with(&mut self.skeleton()) |
77 | } | |
fc512014 | 78 | fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> ControlFlow<Self::BreakTy> { |
0731742a XL |
79 | self.skeleton().visit_trait(trait_ref) |
80 | } | |
6a06907d XL |
81 | fn visit_projection_ty( |
82 | &mut self, | |
83 | projection: ty::ProjectionTy<'tcx>, | |
84 | ) -> ControlFlow<Self::BreakTy> { | |
85 | self.skeleton().visit_projection_ty(projection) | |
86 | } | |
fc512014 XL |
87 | fn visit_predicates( |
88 | &mut self, | |
89 | predicates: ty::GenericPredicates<'tcx>, | |
90 | ) -> ControlFlow<Self::BreakTy> { | |
0731742a XL |
91 | self.skeleton().visit_predicates(predicates) |
92 | } | |
93 | } | |
94 | ||
3dfed10e | 95 | struct DefIdVisitorSkeleton<'v, 'tcx, V: ?Sized> { |
0731742a XL |
96 | def_id_visitor: &'v mut V, |
97 | visited_opaque_tys: FxHashSet<DefId>, | |
dc9dc135 | 98 | dummy: PhantomData<TyCtxt<'tcx>>, |
0731742a XL |
99 | } |
100 | ||
dc9dc135 XL |
101 | impl<'tcx, V> DefIdVisitorSkeleton<'_, 'tcx, V> |
102 | where | |
103 | V: DefIdVisitor<'tcx> + ?Sized, | |
0731742a | 104 | { |
fc512014 | 105 | fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> ControlFlow<V::BreakTy> { |
0731742a | 106 | let TraitRef { def_id, substs } = trait_ref; |
29967ef6 XL |
107 | self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref.print_only_trait_path())?; |
108 | if self.def_id_visitor.shallow() { ControlFlow::CONTINUE } else { substs.visit_with(self) } | |
0731742a XL |
109 | } |
110 | ||
6a06907d XL |
111 | fn visit_projection_ty( |
112 | &mut self, | |
113 | projection: ty::ProjectionTy<'tcx>, | |
114 | ) -> ControlFlow<V::BreakTy> { | |
115 | let (trait_ref, assoc_substs) = | |
116 | projection.trait_ref_and_own_substs(self.def_id_visitor.tcx()); | |
117 | self.visit_trait(trait_ref)?; | |
118 | if self.def_id_visitor.shallow() { | |
119 | ControlFlow::CONTINUE | |
120 | } else { | |
121 | assoc_substs.iter().try_for_each(|subst| subst.visit_with(self)) | |
122 | } | |
123 | } | |
124 | ||
fc512014 | 125 | fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow<V::BreakTy> { |
5869c6ff | 126 | match predicate.kind().skip_binder() { |
94222f64 | 127 | ty::PredicateKind::Trait(ty::TraitPredicate { trait_ref, constness: _ }) => { |
3dfed10e XL |
128 | self.visit_trait(trait_ref) |
129 | } | |
5869c6ff | 130 | ty::PredicateKind::Projection(ty::ProjectionPredicate { projection_ty, ty }) => { |
29967ef6 | 131 | ty.visit_with(self)?; |
6a06907d | 132 | self.visit_projection_ty(projection_ty) |
3dfed10e | 133 | } |
5869c6ff | 134 | ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _region)) => { |
3dfed10e XL |
135 | ty.visit_with(self) |
136 | } | |
5869c6ff | 137 | ty::PredicateKind::RegionOutlives(..) => ControlFlow::CONTINUE, |
94222f64 XL |
138 | ty::PredicateKind::ConstEvaluatable(uv) |
139 | if self.def_id_visitor.tcx().features().generic_const_exprs => | |
1b1a35ee | 140 | { |
5869c6ff | 141 | let tcx = self.def_id_visitor.tcx(); |
94222f64 | 142 | if let Ok(Some(ct)) = AbstractConst::new(tcx, uv) { |
5869c6ff XL |
143 | self.visit_abstract_const_expr(tcx, ct)?; |
144 | } | |
29967ef6 | 145 | ControlFlow::CONTINUE |
1b1a35ee | 146 | } |
3dfed10e XL |
147 | _ => bug!("unexpected predicate: {:?}", predicate), |
148 | } | |
149 | } | |
150 | ||
5869c6ff XL |
151 | fn visit_abstract_const_expr( |
152 | &mut self, | |
153 | tcx: TyCtxt<'tcx>, | |
154 | ct: AbstractConst<'tcx>, | |
155 | ) -> ControlFlow<V::BreakTy> { | |
156 | const_evaluatable::walk_abstract_const(tcx, ct, |node| match node.root() { | |
157 | ACNode::Leaf(leaf) => { | |
158 | let leaf = leaf.subst(tcx, ct.substs); | |
159 | self.visit_const(leaf) | |
160 | } | |
136023e0 | 161 | ACNode::Cast(_, _, ty) => self.visit_ty(ty), |
5869c6ff XL |
162 | ACNode::Binop(..) | ACNode::UnaryOp(..) | ACNode::FunctionCall(_, _) => { |
163 | ControlFlow::CONTINUE | |
164 | } | |
165 | }) | |
166 | } | |
167 | ||
fc512014 XL |
168 | fn visit_predicates( |
169 | &mut self, | |
170 | predicates: ty::GenericPredicates<'tcx>, | |
171 | ) -> ControlFlow<V::BreakTy> { | |
dc9dc135 | 172 | let ty::GenericPredicates { parent: _, predicates } = predicates; |
29967ef6 | 173 | predicates.iter().try_for_each(|&(predicate, _span)| self.visit_predicate(predicate)) |
0731742a XL |
174 | } |
175 | } | |
176 | ||
dc9dc135 XL |
177 | impl<'tcx, V> TypeVisitor<'tcx> for DefIdVisitorSkeleton<'_, 'tcx, V> |
178 | where | |
179 | V: DefIdVisitor<'tcx> + ?Sized, | |
0731742a | 180 | { |
fc512014 XL |
181 | type BreakTy = V::BreakTy; |
182 | ||
94222f64 XL |
183 | fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> { |
184 | Some(self.def_id_visitor.tcx()) | |
185 | } | |
186 | ||
fc512014 | 187 | fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<V::BreakTy> { |
0731742a | 188 | let tcx = self.def_id_visitor.tcx(); |
532ac7d7 | 189 | // InternalSubsts are not visited here because they are visited below in `super_visit_with`. |
1b1a35ee | 190 | match *ty.kind() { |
dfeec247 XL |
191 | ty::Adt(&ty::AdtDef { did: def_id, .. }, ..) |
192 | | ty::Foreign(def_id) | |
193 | | ty::FnDef(def_id, ..) | |
194 | | ty::Closure(def_id, ..) | |
195 | | ty::Generator(def_id, ..) => { | |
29967ef6 | 196 | self.def_id_visitor.visit_def_id(def_id, "type", &ty)?; |
0731742a | 197 | if self.def_id_visitor.shallow() { |
29967ef6 | 198 | return ControlFlow::CONTINUE; |
0731742a XL |
199 | } |
200 | // Default type visitor doesn't visit signatures of fn types. | |
201 | // Something like `fn() -> Priv {my_func}` is considered a private type even if | |
202 | // `my_func` is public, so we need to visit signatures. | |
1b1a35ee | 203 | if let ty::FnDef(..) = ty.kind() { |
29967ef6 | 204 | tcx.fn_sig(def_id).visit_with(self)?; |
0731742a XL |
205 | } |
206 | // Inherent static methods don't have self type in substs. | |
207 | // Something like `fn() {my_method}` type of the method | |
208 | // `impl Pub<Priv> { pub fn my_method() {} }` is considered a private type, | |
209 | // so we need to visit the self type additionally. | |
210 | if let Some(assoc_item) = tcx.opt_associated_item(def_id) { | |
211 | if let ty::ImplContainer(impl_def_id) = assoc_item.container { | |
29967ef6 | 212 | tcx.type_of(impl_def_id).visit_with(self)?; |
0731742a XL |
213 | } |
214 | } | |
215 | } | |
f9f354fc | 216 | ty::Projection(proj) => { |
0731742a XL |
217 | if self.def_id_visitor.skip_assoc_tys() { |
218 | // Visitors searching for minimal visibility/reachability want to | |
219 | // conservatively approximate associated types like `<Type as Trait>::Alias` | |
220 | // as visible/reachable even if both `Type` and `Trait` are private. | |
221 | // Ideally, associated types should be substituted in the same way as | |
222 | // free type aliases, but this isn't done yet. | |
29967ef6 | 223 | return ControlFlow::CONTINUE; |
0731742a XL |
224 | } |
225 | // This will also visit substs if necessary, so we don't need to recurse. | |
6a06907d | 226 | return self.visit_projection_ty(proj); |
0731742a XL |
227 | } |
228 | ty::Dynamic(predicates, ..) => { | |
229 | // All traits in the list are considered the "primary" part of the type | |
230 | // and are visited by shallow visitors. | |
fc512014 XL |
231 | for predicate in predicates { |
232 | let trait_ref = match predicate.skip_binder() { | |
0731742a XL |
233 | ty::ExistentialPredicate::Trait(trait_ref) => trait_ref, |
234 | ty::ExistentialPredicate::Projection(proj) => proj.trait_ref(tcx), | |
dfeec247 XL |
235 | ty::ExistentialPredicate::AutoTrait(def_id) => { |
236 | ty::ExistentialTraitRef { def_id, substs: InternalSubsts::empty() } | |
237 | } | |
0731742a XL |
238 | }; |
239 | let ty::ExistentialTraitRef { def_id, substs: _ } = trait_ref; | |
29967ef6 | 240 | self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref)?; |
0731742a XL |
241 | } |
242 | } | |
243 | ty::Opaque(def_id, ..) => { | |
244 | // Skip repeated `Opaque`s to avoid infinite recursion. | |
245 | if self.visited_opaque_tys.insert(def_id) { | |
246 | // The intent is to treat `impl Trait1 + Trait2` identically to | |
247 | // `dyn Trait1 + Trait2`. Therefore we ignore def-id of the opaque type itself | |
248 | // (it either has no visibility, or its visibility is insignificant, like | |
29967ef6 | 249 | // visibilities of type aliases) and recurse into bounds instead to go |
0731742a XL |
250 | // through the trait list (default type visitor doesn't visit those traits). |
251 | // All traits in the list are considered the "primary" part of the type | |
252 | // and are visited by shallow visitors. | |
29967ef6 XL |
253 | self.visit_predicates(ty::GenericPredicates { |
254 | parent: None, | |
255 | predicates: tcx.explicit_item_bounds(def_id), | |
256 | })?; | |
0731742a XL |
257 | } |
258 | } | |
259 | // These types don't have their own def-ids (but may have subcomponents | |
260 | // with def-ids that should be visited recursively). | |
dfeec247 XL |
261 | ty::Bool |
262 | | ty::Char | |
263 | | ty::Int(..) | |
264 | | ty::Uint(..) | |
265 | | ty::Float(..) | |
266 | | ty::Str | |
267 | | ty::Never | |
268 | | ty::Array(..) | |
269 | | ty::Slice(..) | |
270 | | ty::Tuple(..) | |
271 | | ty::RawPtr(..) | |
272 | | ty::Ref(..) | |
273 | | ty::FnPtr(..) | |
274 | | ty::Param(..) | |
f035d41b | 275 | | ty::Error(_) |
dfeec247 XL |
276 | | ty::GeneratorWitness(..) => {} |
277 | ty::Bound(..) | ty::Placeholder(..) | ty::Infer(..) => { | |
278 | bug!("unexpected type: {:?}", ty) | |
279 | } | |
0731742a XL |
280 | } |
281 | ||
29967ef6 XL |
282 | if self.def_id_visitor.shallow() { |
283 | ControlFlow::CONTINUE | |
284 | } else { | |
285 | ty.super_visit_with(self) | |
0731742a XL |
286 | } |
287 | } | |
5869c6ff XL |
288 | |
289 | fn visit_const(&mut self, c: &'tcx Const<'tcx>) -> ControlFlow<Self::BreakTy> { | |
290 | self.visit_ty(c.ty)?; | |
291 | let tcx = self.def_id_visitor.tcx(); | |
292 | if let Ok(Some(ct)) = AbstractConst::from_const(tcx, c) { | |
293 | self.visit_abstract_const_expr(tcx, ct)?; | |
294 | } | |
295 | ControlFlow::CONTINUE | |
296 | } | |
0731742a XL |
297 | } |
298 | ||
416331ca | 299 | fn min(vis1: ty::Visibility, vis2: ty::Visibility, tcx: TyCtxt<'_>) -> ty::Visibility { |
0731742a XL |
300 | if vis1.is_at_least(vis2, tcx) { vis2 } else { vis1 } |
301 | } | |
302 | ||
cc61c64b XL |
303 | //////////////////////////////////////////////////////////////////////////////// |
304 | /// Visitor used to determine if pub(restricted) is used anywhere in the crate. | |
305 | /// | |
306 | /// This is done so that `private_in_public` warnings can be turned into hard errors | |
307 | /// in crates that have been updated to use pub(restricted). | |
308 | //////////////////////////////////////////////////////////////////////////////// | |
dc9dc135 XL |
309 | struct PubRestrictedVisitor<'tcx> { |
310 | tcx: TyCtxt<'tcx>, | |
cc61c64b XL |
311 | has_pub_restricted: bool, |
312 | } | |
313 | ||
dc9dc135 | 314 | impl Visitor<'tcx> for PubRestrictedVisitor<'tcx> { |
dfeec247 XL |
315 | type Map = Map<'tcx>; |
316 | ||
ba9703b0 XL |
317 | fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> { |
318 | NestedVisitorMap::All(self.tcx.hir()) | |
cc61c64b | 319 | } |
dfeec247 | 320 | fn visit_vis(&mut self, vis: &'tcx hir::Visibility<'tcx>) { |
8faf50e0 | 321 | self.has_pub_restricted = self.has_pub_restricted || vis.node.is_pub_restricted(); |
cc61c64b XL |
322 | } |
323 | } | |
324 | ||
0731742a XL |
325 | //////////////////////////////////////////////////////////////////////////////// |
326 | /// Visitor used to determine impl visibility and reachability. | |
327 | //////////////////////////////////////////////////////////////////////////////// | |
328 | ||
329 | struct FindMin<'a, 'tcx, VL: VisibilityLike> { | |
dc9dc135 | 330 | tcx: TyCtxt<'tcx>, |
0731742a XL |
331 | access_levels: &'a AccessLevels, |
332 | min: VL, | |
333 | } | |
334 | ||
dc9dc135 | 335 | impl<'a, 'tcx, VL: VisibilityLike> DefIdVisitor<'tcx> for FindMin<'a, 'tcx, VL> { |
dfeec247 XL |
336 | fn tcx(&self) -> TyCtxt<'tcx> { |
337 | self.tcx | |
338 | } | |
339 | fn shallow(&self) -> bool { | |
340 | VL::SHALLOW | |
341 | } | |
342 | fn skip_assoc_tys(&self) -> bool { | |
343 | true | |
344 | } | |
29967ef6 XL |
345 | fn visit_def_id( |
346 | &mut self, | |
347 | def_id: DefId, | |
348 | _kind: &str, | |
349 | _descr: &dyn fmt::Display, | |
fc512014 | 350 | ) -> ControlFlow<Self::BreakTy> { |
0731742a | 351 | self.min = VL::new_min(self, def_id); |
29967ef6 | 352 | ControlFlow::CONTINUE |
0731742a XL |
353 | } |
354 | } | |
355 | ||
356 | trait VisibilityLike: Sized { | |
357 | const MAX: Self; | |
358 | const SHALLOW: bool = false; | |
416331ca | 359 | fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self; |
0731742a XL |
360 | |
361 | // Returns an over-approximation (`skip_assoc_tys` = true) of visibility due to | |
362 | // associated types for which we can't determine visibility precisely. | |
94222f64 | 363 | fn of_impl(def_id: LocalDefId, tcx: TyCtxt<'_>, access_levels: &AccessLevels) -> Self { |
0731742a | 364 | let mut find = FindMin { tcx, access_levels, min: Self::MAX }; |
0731742a XL |
365 | find.visit(tcx.type_of(def_id)); |
366 | if let Some(trait_ref) = tcx.impl_trait_ref(def_id) { | |
367 | find.visit_trait(trait_ref); | |
368 | } | |
369 | find.min | |
370 | } | |
371 | } | |
372 | impl VisibilityLike for ty::Visibility { | |
373 | const MAX: Self = ty::Visibility::Public; | |
416331ca | 374 | fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self { |
29967ef6 | 375 | min(find.tcx.visibility(def_id), find.min, find.tcx) |
0731742a XL |
376 | } |
377 | } | |
378 | impl VisibilityLike for Option<AccessLevel> { | |
379 | const MAX: Self = Some(AccessLevel::Public); | |
380 | // Type inference is very smart sometimes. | |
381 | // It can make an impl reachable even some components of its type or trait are unreachable. | |
382 | // E.g. methods of `impl ReachableTrait<UnreachableTy> for ReachableTy<UnreachableTy> { ... }` | |
383 | // can be usable from other crates (#57264). So we skip substs when calculating reachability | |
384 | // and consider an impl reachable if its "shallow" type and trait are reachable. | |
385 | // | |
386 | // The assumption we make here is that type-inference won't let you use an impl without knowing | |
387 | // both "shallow" version of its self type and "shallow" version of its trait if it exists | |
388 | // (which require reaching the `DefId`s in them). | |
389 | const SHALLOW: bool = true; | |
416331ca | 390 | fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self { |
dfeec247 | 391 | cmp::min( |
f9f354fc | 392 | if let Some(def_id) = def_id.as_local() { |
94222f64 | 393 | find.access_levels.map.get(&def_id).copied() |
dfeec247 XL |
394 | } else { |
395 | Self::MAX | |
396 | }, | |
397 | find.min, | |
398 | ) | |
0731742a XL |
399 | } |
400 | } | |
401 | ||
85aaf69f | 402 | //////////////////////////////////////////////////////////////////////////////// |
9fa01778 | 403 | /// The embargo visitor, used to determine the exports of the AST. |
85aaf69f SL |
404 | //////////////////////////////////////////////////////////////////////////////// |
405 | ||
dc9dc135 XL |
406 | struct EmbargoVisitor<'tcx> { |
407 | tcx: TyCtxt<'tcx>, | |
85aaf69f | 408 | |
416331ca | 409 | /// Accessibility levels for reachable nodes. |
92a42be0 | 410 | access_levels: AccessLevels, |
416331ca XL |
411 | /// A set of pairs corresponding to modules, where the first module is |
412 | /// reachable via a macro that's defined in the second module. This cannot | |
413 | /// be represented as reachable because it can't handle the following case: | |
414 | /// | |
415 | /// pub mod n { // Should be `Public` | |
416 | /// pub(crate) mod p { // Should *not* be accessible | |
417 | /// pub fn f() -> i32 { 12 } // Must be `Reachable` | |
418 | /// } | |
419 | /// } | |
420 | /// pub macro m() { | |
421 | /// n::p::f() | |
422 | /// } | |
94222f64 | 423 | macro_reachable: FxHashSet<(LocalDefId, LocalDefId)>, |
416331ca | 424 | /// Previous accessibility level; `None` means unreachable. |
92a42be0 | 425 | prev_level: Option<AccessLevel>, |
416331ca | 426 | /// Has something changed in the level map? |
92a42be0 | 427 | changed: bool, |
85aaf69f SL |
428 | } |
429 | ||
dc9dc135 | 430 | struct ReachEverythingInTheInterfaceVisitor<'a, 'tcx> { |
b7449926 | 431 | access_level: Option<AccessLevel>, |
94222f64 | 432 | item_def_id: LocalDefId, |
dc9dc135 | 433 | ev: &'a mut EmbargoVisitor<'tcx>, |
7453a54e SL |
434 | } |
435 | ||
dc9dc135 | 436 | impl EmbargoVisitor<'tcx> { |
94222f64 XL |
437 | fn get(&self, def_id: LocalDefId) -> Option<AccessLevel> { |
438 | self.access_levels.map.get(&def_id).copied() | |
92a42be0 SL |
439 | } |
440 | ||
416331ca | 441 | /// Updates node level and returns the updated level. |
94222f64 XL |
442 | fn update(&mut self, def_id: LocalDefId, level: Option<AccessLevel>) -> Option<AccessLevel> { |
443 | let old_level = self.get(def_id); | |
0731742a | 444 | // Accessibility levels can only grow. |
92a42be0 | 445 | if level > old_level { |
94222f64 | 446 | self.access_levels.map.insert(def_id, level.unwrap()); |
92a42be0 SL |
447 | self.changed = true; |
448 | level | |
449 | } else { | |
450 | old_level | |
451 | } | |
85aaf69f | 452 | } |
7453a54e | 453 | |
dc9dc135 XL |
454 | fn reach( |
455 | &mut self, | |
94222f64 | 456 | def_id: LocalDefId, |
dc9dc135 XL |
457 | access_level: Option<AccessLevel>, |
458 | ) -> ReachEverythingInTheInterfaceVisitor<'_, 'tcx> { | |
476ff2be | 459 | ReachEverythingInTheInterfaceVisitor { |
0731742a | 460 | access_level: cmp::min(access_level, Some(AccessLevel::Reachable)), |
94222f64 | 461 | item_def_id: def_id, |
476ff2be SL |
462 | ev: self, |
463 | } | |
7453a54e | 464 | } |
9fa01778 | 465 | |
94222f64 XL |
466 | // We have to make sure that the items that macros might reference |
467 | // are reachable, since they might be exported transitively. | |
468 | fn update_reachability_from_macro(&mut self, local_def_id: LocalDefId, md: &MacroDef) { | |
469 | // Non-opaque macros cannot make other items more accessible than they already are. | |
470 | ||
471 | let hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id); | |
472 | let attrs = self.tcx.hir().attrs(hir_id); | |
c295e0f8 | 473 | if attr::find_transparency(attrs, md.macro_rules).0 != Transparency::Opaque { |
94222f64 XL |
474 | return; |
475 | } | |
476 | ||
477 | let item_def_id = local_def_id.to_def_id(); | |
478 | let macro_module_def_id = | |
479 | ty::DefIdTree::parent(self.tcx, item_def_id).unwrap().expect_local(); | |
480 | if self.tcx.hir().opt_def_kind(macro_module_def_id) != Some(DefKind::Mod) { | |
481 | // The macro's parent doesn't correspond to a `mod`, return early (#63164, #65252). | |
482 | return; | |
483 | } | |
484 | ||
485 | if self.get(local_def_id).is_none() { | |
486 | return; | |
487 | } | |
488 | ||
489 | // Since we are starting from an externally visible module, | |
490 | // all the parents in the loop below are also guaranteed to be modules. | |
491 | let mut module_def_id = macro_module_def_id; | |
492 | loop { | |
493 | let changed_reachability = | |
494 | self.update_macro_reachable(module_def_id, macro_module_def_id); | |
495 | if changed_reachability || module_def_id == CRATE_DEF_ID { | |
496 | break; | |
497 | } | |
498 | module_def_id = | |
499 | ty::DefIdTree::parent(self.tcx, module_def_id.to_def_id()).unwrap().expect_local(); | |
500 | } | |
501 | } | |
502 | ||
416331ca XL |
503 | /// Updates the item as being reachable through a macro defined in the given |
504 | /// module. Returns `true` if the level has changed. | |
94222f64 XL |
505 | fn update_macro_reachable( |
506 | &mut self, | |
507 | module_def_id: LocalDefId, | |
508 | defining_mod: LocalDefId, | |
509 | ) -> bool { | |
510 | if self.macro_reachable.insert((module_def_id, defining_mod)) { | |
511 | self.update_macro_reachable_mod(module_def_id, defining_mod); | |
416331ca XL |
512 | true |
513 | } else { | |
514 | false | |
515 | } | |
516 | } | |
517 | ||
94222f64 | 518 | fn update_macro_reachable_mod(&mut self, module_def_id: LocalDefId, defining_mod: LocalDefId) { |
416331ca | 519 | let module = self.tcx.hir().get_module(module_def_id).0; |
dfeec247 | 520 | for item_id in module.item_ids { |
6a06907d XL |
521 | let def_kind = self.tcx.def_kind(item_id.def_id); |
522 | let vis = self.tcx.visibility(item_id.def_id); | |
94222f64 | 523 | self.update_macro_reachable_def(item_id.def_id, def_kind, vis, defining_mod); |
416331ca | 524 | } |
416331ca XL |
525 | if let Some(exports) = self.tcx.module_exports(module_def_id) { |
526 | for export in exports { | |
94222f64 | 527 | if export.vis.is_accessible_from(defining_mod.to_def_id(), self.tcx) { |
416331ca | 528 | if let Res::Def(def_kind, def_id) = export.res { |
f9f354fc | 529 | if let Some(def_id) = def_id.as_local() { |
29967ef6 | 530 | let vis = self.tcx.visibility(def_id.to_def_id()); |
94222f64 | 531 | self.update_macro_reachable_def(def_id, def_kind, vis, defining_mod); |
416331ca XL |
532 | } |
533 | } | |
534 | } | |
535 | } | |
536 | } | |
537 | } | |
538 | ||
539 | fn update_macro_reachable_def( | |
540 | &mut self, | |
94222f64 | 541 | def_id: LocalDefId, |
416331ca XL |
542 | def_kind: DefKind, |
543 | vis: ty::Visibility, | |
94222f64 | 544 | module: LocalDefId, |
416331ca XL |
545 | ) { |
546 | let level = Some(AccessLevel::Reachable); | |
547 | if let ty::Visibility::Public = vis { | |
94222f64 | 548 | self.update(def_id, level); |
416331ca XL |
549 | } |
550 | match def_kind { | |
551 | // No type privacy, so can be directly marked as reachable. | |
94222f64 XL |
552 | DefKind::Const | DefKind::Static | DefKind::TraitAlias | DefKind::TyAlias => { |
553 | if vis.is_accessible_from(module.to_def_id(), self.tcx) { | |
554 | self.update(def_id, level); | |
555 | } | |
556 | } | |
557 | ||
558 | // Hygine isn't really implemented for `macro_rules!` macros at the | |
559 | // moment. Accordingly, marking them as reachable is unwise. `macro` macros | |
560 | // have normal hygine, so we can treat them like other items without type | |
561 | // privacy and mark them reachable. | |
562 | DefKind::Macro(_) => { | |
563 | let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id); | |
564 | let item = self.tcx.hir().expect_item(hir_id); | |
565 | if let hir::ItemKind::Macro(MacroDef { macro_rules: false, .. }) = item.kind { | |
566 | if vis.is_accessible_from(module.to_def_id(), self.tcx) { | |
567 | self.update(def_id, level); | |
568 | } | |
416331ca | 569 | } |
dfeec247 | 570 | } |
416331ca XL |
571 | |
572 | // We can't use a module name as the final segment of a path, except | |
573 | // in use statements. Since re-export checking doesn't consider | |
574 | // hygiene these don't need to be marked reachable. The contents of | |
575 | // the module, however may be reachable. | |
576 | DefKind::Mod => { | |
94222f64 XL |
577 | if vis.is_accessible_from(module.to_def_id(), self.tcx) { |
578 | self.update_macro_reachable(def_id, module); | |
416331ca XL |
579 | } |
580 | } | |
581 | ||
582 | DefKind::Struct | DefKind::Union => { | |
94222f64 | 583 | // While structs and unions have type privacy, their fields do not. |
416331ca | 584 | if let ty::Visibility::Public = vis { |
94222f64 XL |
585 | let item = |
586 | self.tcx.hir().expect_item(self.tcx.hir().local_def_id_to_hir_id(def_id)); | |
416331ca | 587 | if let hir::ItemKind::Struct(ref struct_def, _) |
dfeec247 | 588 | | hir::ItemKind::Union(ref struct_def, _) = item.kind |
416331ca XL |
589 | { |
590 | for field in struct_def.fields() { | |
94222f64 XL |
591 | let def_id = self.tcx.hir().local_def_id(field.hir_id); |
592 | let field_vis = self.tcx.visibility(def_id); | |
593 | if field_vis.is_accessible_from(module.to_def_id(), self.tcx) { | |
594 | self.reach(def_id, level).ty(); | |
416331ca XL |
595 | } |
596 | } | |
597 | } else { | |
598 | bug!("item {:?} with DefKind {:?}", item, def_kind); | |
599 | } | |
600 | } | |
601 | } | |
602 | ||
603 | // These have type privacy, so are not reachable unless they're | |
f9f354fc | 604 | // public, or are not namespaced at all. |
416331ca XL |
605 | DefKind::AssocConst |
606 | | DefKind::AssocTy | |
416331ca XL |
607 | | DefKind::ConstParam |
608 | | DefKind::Ctor(_, _) | |
609 | | DefKind::Enum | |
610 | | DefKind::ForeignTy | |
611 | | DefKind::Fn | |
612 | | DefKind::OpaqueTy | |
ba9703b0 | 613 | | DefKind::AssocFn |
416331ca XL |
614 | | DefKind::Trait |
615 | | DefKind::TyParam | |
f9f354fc XL |
616 | | DefKind::Variant |
617 | | DefKind::LifetimeParam | |
618 | | DefKind::ExternCrate | |
619 | | DefKind::Use | |
620 | | DefKind::ForeignMod | |
621 | | DefKind::AnonConst | |
622 | | DefKind::Field | |
623 | | DefKind::GlobalAsm | |
624 | | DefKind::Impl | |
625 | | DefKind::Closure | |
626 | | DefKind::Generator => (), | |
416331ca XL |
627 | } |
628 | } | |
9fa01778 | 629 | |
94222f64 | 630 | /// Given the path segments of an `ItemKind::Use`, then we need |
9fa01778 XL |
631 | /// to update the visibility of the intermediate use so that it isn't linted |
632 | /// by `unreachable_pub`. | |
633 | /// | |
48663c56 | 634 | /// This isn't trivial as `path.res` has the `DefId` of the eventual target |
9fa01778 XL |
635 | /// of the use statement not of the next intermediate use statement. |
636 | /// | |
637 | /// To do this, consider the last two segments of the path to our intermediate | |
638 | /// use statement. We expect the penultimate segment to be a module and the | |
639 | /// last segment to be the name of the item we are exporting. We can then | |
640 | /// look at the items contained in the module for the use statement with that | |
641 | /// name and update that item's visibility. | |
642 | /// | |
643 | /// FIXME: This solution won't work with glob imports and doesn't respect | |
644 | /// namespaces. See <https://github.com/rust-lang/rust/pull/57922#discussion_r251234202>. | |
dfeec247 XL |
645 | fn update_visibility_of_intermediate_use_statements( |
646 | &mut self, | |
647 | segments: &[hir::PathSegment<'_>], | |
648 | ) { | |
3dfed10e | 649 | if let [.., module, segment] = segments { |
dfeec247 XL |
650 | if let Some(item) = module |
651 | .res | |
48663c56 | 652 | .and_then(|res| res.mod_def_id()) |
dfeec247 XL |
653 | // If the module is `self`, i.e. the current crate, |
654 | // there will be no corresponding item. | |
655 | .filter(|def_id| def_id.index != CRATE_DEF_INDEX || def_id.krate != LOCAL_CRATE) | |
f9f354fc | 656 | .and_then(|def_id| { |
3dfed10e | 657 | def_id.as_local().map(|def_id| self.tcx.hir().local_def_id_to_hir_id(def_id)) |
f9f354fc | 658 | }) |
dc9dc135 | 659 | .map(|module_hir_id| self.tcx.hir().expect_item(module_hir_id)) |
dfeec247 | 660 | { |
e74abb32 | 661 | if let hir::ItemKind::Mod(m) = &item.kind { |
6a06907d XL |
662 | for &item_id in m.item_ids { |
663 | let item = self.tcx.hir().item(item_id); | |
664 | if !self.tcx.hygienic_eq( | |
665 | segment.ident, | |
666 | item.ident, | |
667 | item_id.def_id.to_def_id(), | |
668 | ) { | |
dfeec247 XL |
669 | continue; |
670 | } | |
e74abb32 | 671 | if let hir::ItemKind::Use(..) = item.kind { |
94222f64 | 672 | self.update(item.def_id, Some(AccessLevel::Exported)); |
9fa01778 XL |
673 | } |
674 | } | |
675 | } | |
676 | } | |
677 | } | |
678 | } | |
85aaf69f SL |
679 | } |
680 | ||
dc9dc135 | 681 | impl Visitor<'tcx> for EmbargoVisitor<'tcx> { |
dfeec247 XL |
682 | type Map = Map<'tcx>; |
683 | ||
92a42be0 SL |
684 | /// We want to visit items in the context of their containing |
685 | /// module and so forth, so supply a crate for doing a deep walk. | |
ba9703b0 XL |
686 | fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> { |
687 | NestedVisitorMap::All(self.tcx.hir()) | |
92a42be0 | 688 | } |
85aaf69f | 689 | |
dfeec247 | 690 | fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { |
e74abb32 | 691 | let inherited_item_level = match item.kind { |
dfeec247 | 692 | hir::ItemKind::Impl { .. } => { |
94222f64 XL |
693 | Option::<AccessLevel>::of_impl(item.def_id, self.tcx, &self.access_levels) |
694 | } | |
695 | // Only exported `macro_rules!` items are public, but they always are. | |
696 | hir::ItemKind::Macro(MacroDef { macro_rules: true, .. }) => { | |
697 | let def_id = item.def_id.to_def_id(); | |
698 | let is_macro_export = self.tcx.has_attr(def_id, sym::macro_export); | |
699 | if is_macro_export { Some(AccessLevel::Public) } else { None } | |
dfeec247 | 700 | } |
0731742a | 701 | // Foreign modules inherit level from parents. |
fc512014 | 702 | hir::ItemKind::ForeignMod { .. } => self.prev_level, |
0731742a | 703 | // Other `pub` items inherit levels from parents. |
dfeec247 XL |
704 | hir::ItemKind::Const(..) |
705 | | hir::ItemKind::Enum(..) | |
706 | | hir::ItemKind::ExternCrate(..) | |
707 | | hir::ItemKind::GlobalAsm(..) | |
708 | | hir::ItemKind::Fn(..) | |
94222f64 | 709 | | hir::ItemKind::Macro(..) |
dfeec247 XL |
710 | | hir::ItemKind::Mod(..) |
711 | | hir::ItemKind::Static(..) | |
712 | | hir::ItemKind::Struct(..) | |
713 | | hir::ItemKind::Trait(..) | |
714 | | hir::ItemKind::TraitAlias(..) | |
715 | | hir::ItemKind::OpaqueTy(..) | |
716 | | hir::ItemKind::TyAlias(..) | |
717 | | hir::ItemKind::Union(..) | |
718 | | hir::ItemKind::Use(..) => { | |
719 | if item.vis.node.is_pub() { | |
720 | self.prev_level | |
721 | } else { | |
722 | None | |
723 | } | |
85aaf69f | 724 | } |
92a42be0 | 725 | }; |
85aaf69f | 726 | |
0731742a | 727 | // Update level of the item itself. |
94222f64 | 728 | let item_level = self.update(item.def_id, inherited_item_level); |
85aaf69f | 729 | |
0731742a | 730 | // Update levels of nested things. |
e74abb32 | 731 | match item.kind { |
8faf50e0 | 732 | hir::ItemKind::Enum(ref def, _) => { |
dfeec247 | 733 | for variant in def.variants { |
94222f64 XL |
734 | let variant_level = |
735 | self.update(self.tcx.hir().local_def_id(variant.id), item_level); | |
e1599b0c | 736 | if let Some(ctor_hir_id) = variant.data.ctor_hir_id() { |
94222f64 | 737 | self.update(self.tcx.hir().local_def_id(ctor_hir_id), item_level); |
532ac7d7 | 738 | } |
e1599b0c | 739 | for field in variant.data.fields() { |
94222f64 | 740 | self.update(self.tcx.hir().local_def_id(field.hir_id), variant_level); |
92a42be0 | 741 | } |
85aaf69f SL |
742 | } |
743 | } | |
5869c6ff XL |
744 | hir::ItemKind::Impl(ref impl_) => { |
745 | for impl_item_ref in impl_.items { | |
c295e0f8 XL |
746 | if impl_.of_trait.is_some() |
747 | || self.tcx.visibility(impl_item_ref.id.def_id) == ty::Visibility::Public | |
748 | { | |
94222f64 | 749 | self.update(impl_item_ref.id.def_id, item_level); |
85aaf69f SL |
750 | } |
751 | } | |
752 | } | |
dfeec247 | 753 | hir::ItemKind::Trait(.., trait_item_refs) => { |
32a655c1 | 754 | for trait_item_ref in trait_item_refs { |
94222f64 | 755 | self.update(trait_item_ref.id.def_id, item_level); |
85aaf69f SL |
756 | } |
757 | } | |
8faf50e0 | 758 | hir::ItemKind::Struct(ref def, _) | hir::ItemKind::Union(ref def, _) => { |
532ac7d7 | 759 | if let Some(ctor_hir_id) = def.ctor_hir_id() { |
94222f64 | 760 | self.update(self.tcx.hir().local_def_id(ctor_hir_id), item_level); |
85aaf69f | 761 | } |
b039eaaf | 762 | for field in def.fields() { |
8faf50e0 | 763 | if field.vis.node.is_pub() { |
94222f64 | 764 | self.update(self.tcx.hir().local_def_id(field.hir_id), item_level); |
c34b1796 AL |
765 | } |
766 | } | |
85aaf69f | 767 | } |
94222f64 XL |
768 | hir::ItemKind::Macro(ref macro_def) => { |
769 | self.update_reachability_from_macro(item.def_id, macro_def); | |
770 | } | |
fc512014 XL |
771 | hir::ItemKind::ForeignMod { items, .. } => { |
772 | for foreign_item in items { | |
c295e0f8 | 773 | if self.tcx.visibility(foreign_item.id.def_id) == ty::Visibility::Public { |
94222f64 | 774 | self.update(foreign_item.id.def_id, item_level); |
92a42be0 SL |
775 | } |
776 | } | |
777 | } | |
94222f64 | 778 | |
dfeec247 XL |
779 | hir::ItemKind::OpaqueTy(..) |
780 | | hir::ItemKind::Use(..) | |
781 | | hir::ItemKind::Static(..) | |
782 | | hir::ItemKind::Const(..) | |
783 | | hir::ItemKind::GlobalAsm(..) | |
784 | | hir::ItemKind::TyAlias(..) | |
785 | | hir::ItemKind::Mod(..) | |
786 | | hir::ItemKind::TraitAlias(..) | |
787 | | hir::ItemKind::Fn(..) | |
788 | | hir::ItemKind::ExternCrate(..) => {} | |
7453a54e SL |
789 | } |
790 | ||
0731742a | 791 | // Mark all items in interfaces of reachable items as reachable. |
e74abb32 | 792 | match item.kind { |
0731742a | 793 | // The interface is empty. |
94222f64 | 794 | hir::ItemKind::Macro(..) | hir::ItemKind::ExternCrate(..) => {} |
0731742a | 795 | // All nested items are checked by `visit_item`. |
8faf50e0 | 796 | hir::ItemKind::Mod(..) => {} |
9fa01778 XL |
797 | // Re-exports are handled in `visit_mod`. However, in order to avoid looping over |
798 | // all of the items of a mod in `visit_mod` looking for use statements, we handle | |
799 | // making sure that intermediate use statements have their visibilities updated here. | |
c295e0f8 | 800 | hir::ItemKind::Use(path, _) => { |
9fa01778 XL |
801 | if item_level.is_some() { |
802 | self.update_visibility_of_intermediate_use_statements(path.segments.as_ref()); | |
803 | } | |
804 | } | |
0731742a | 805 | // The interface is empty. |
8faf50e0 | 806 | hir::ItemKind::GlobalAsm(..) => {} |
416331ca | 807 | hir::ItemKind::OpaqueTy(..) => { |
3dfed10e | 808 | // HACK(jynelson): trying to infer the type of `impl trait` breaks `async-std` (and `pub async fn` in general) |
fc512014 | 809 | // Since rustdoc never needs to do codegen and doesn't care about link-time reachability, |
3dfed10e XL |
810 | // mark this as unreachable. |
811 | // See https://github.com/rust-lang/rust/issues/75100 | |
812 | if !self.tcx.sess.opts.actually_rustdoc { | |
813 | // FIXME: This is some serious pessimization intended to workaround deficiencies | |
814 | // in the reachability pass (`middle/reachable.rs`). Types are marked as link-time | |
815 | // reachable if they are returned via `impl Trait`, even from private functions. | |
816 | let exist_level = | |
817 | cmp::max(item_level, Some(AccessLevel::ReachableFromImplTrait)); | |
94222f64 | 818 | self.reach(item.def_id, exist_level).generics().predicates().ty(); |
3dfed10e | 819 | } |
0731742a XL |
820 | } |
821 | // Visit everything. | |
dfeec247 XL |
822 | hir::ItemKind::Const(..) |
823 | | hir::ItemKind::Static(..) | |
824 | | hir::ItemKind::Fn(..) | |
825 | | hir::ItemKind::TyAlias(..) => { | |
7453a54e | 826 | if item_level.is_some() { |
94222f64 | 827 | self.reach(item.def_id, item_level).generics().predicates().ty(); |
7453a54e SL |
828 | } |
829 | } | |
dfeec247 | 830 | hir::ItemKind::Trait(.., trait_item_refs) => { |
476ff2be | 831 | if item_level.is_some() { |
94222f64 | 832 | self.reach(item.def_id, item_level).generics().predicates(); |
476ff2be | 833 | |
32a655c1 | 834 | for trait_item_ref in trait_item_refs { |
94222f64 | 835 | let mut reach = self.reach(trait_item_ref.id.def_id, item_level); |
476ff2be SL |
836 | reach.generics().predicates(); |
837 | ||
dfeec247 XL |
838 | if trait_item_ref.kind == AssocItemKind::Type |
839 | && !trait_item_ref.defaultness.has_value() | |
840 | { | |
476ff2be SL |
841 | // No type to visit. |
842 | } else { | |
7cac9316 | 843 | reach.ty(); |
476ff2be SL |
844 | } |
845 | } | |
846 | } | |
847 | } | |
8faf50e0 | 848 | hir::ItemKind::TraitAlias(..) => { |
ff7c6d11 | 849 | if item_level.is_some() { |
94222f64 | 850 | self.reach(item.def_id, item_level).generics().predicates(); |
ff7c6d11 XL |
851 | } |
852 | } | |
0731742a | 853 | // Visit everything except for private impl items. |
5869c6ff | 854 | hir::ItemKind::Impl(ref impl_) => { |
476ff2be | 855 | if item_level.is_some() { |
94222f64 | 856 | self.reach(item.def_id, item_level).generics().predicates().ty().trait_ref(); |
476ff2be | 857 | |
5869c6ff | 858 | for impl_item_ref in impl_.items { |
94222f64 | 859 | let impl_item_level = self.get(impl_item_ref.id.def_id); |
0731742a | 860 | if impl_item_level.is_some() { |
94222f64 | 861 | self.reach(impl_item_ref.id.def_id, impl_item_level) |
dfeec247 XL |
862 | .generics() |
863 | .predicates() | |
864 | .ty(); | |
476ff2be SL |
865 | } |
866 | } | |
867 | } | |
868 | } | |
869 | ||
0731742a | 870 | // Visit everything, but enum variants have their own levels. |
8faf50e0 | 871 | hir::ItemKind::Enum(ref def, _) => { |
7453a54e | 872 | if item_level.is_some() { |
94222f64 | 873 | self.reach(item.def_id, item_level).generics().predicates(); |
7453a54e | 874 | } |
dfeec247 | 875 | for variant in def.variants { |
94222f64 | 876 | let variant_level = self.get(self.tcx.hir().local_def_id(variant.id)); |
0731742a | 877 | if variant_level.is_some() { |
e1599b0c | 878 | for field in variant.data.fields() { |
94222f64 XL |
879 | self.reach(self.tcx.hir().local_def_id(field.hir_id), variant_level) |
880 | .ty(); | |
7453a54e SL |
881 | } |
882 | // Corner case: if the variant is reachable, but its | |
883 | // enum is not, make the enum reachable as well. | |
94222f64 | 884 | self.update(item.def_id, variant_level); |
7453a54e SL |
885 | } |
886 | } | |
887 | } | |
0731742a | 888 | // Visit everything, but foreign items have their own levels. |
fc512014 XL |
889 | hir::ItemKind::ForeignMod { items, .. } => { |
890 | for foreign_item in items { | |
94222f64 | 891 | let foreign_item_level = self.get(foreign_item.id.def_id); |
0731742a | 892 | if foreign_item_level.is_some() { |
94222f64 | 893 | self.reach(foreign_item.id.def_id, foreign_item_level) |
dfeec247 XL |
894 | .generics() |
895 | .predicates() | |
896 | .ty(); | |
7453a54e SL |
897 | } |
898 | } | |
899 | } | |
0731742a | 900 | // Visit everything except for private fields. |
dfeec247 | 901 | hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => { |
7453a54e | 902 | if item_level.is_some() { |
94222f64 | 903 | self.reach(item.def_id, item_level).generics().predicates(); |
7453a54e | 904 | for field in struct_def.fields() { |
94222f64 XL |
905 | let def_id = self.tcx.hir().local_def_id(field.hir_id); |
906 | let field_level = self.get(def_id); | |
0731742a | 907 | if field_level.is_some() { |
94222f64 | 908 | self.reach(def_id, field_level).ty(); |
85aaf69f SL |
909 | } |
910 | } | |
911 | } | |
912 | } | |
85aaf69f SL |
913 | } |
914 | ||
0731742a | 915 | let orig_level = mem::replace(&mut self.prev_level, item_level); |
92a42be0 | 916 | intravisit::walk_item(self, item); |
92a42be0 | 917 | self.prev_level = orig_level; |
85aaf69f SL |
918 | } |
919 | ||
dfeec247 | 920 | fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) { |
92a42be0 SL |
921 | // Blocks can have public items, for example impls, but they always |
922 | // start as completely private regardless of publicity of a function, | |
0731742a XL |
923 | // constant, type, field, etc., in which this block resides. |
924 | let orig_level = mem::replace(&mut self.prev_level, None); | |
92a42be0 | 925 | intravisit::walk_block(self, b); |
92a42be0 | 926 | self.prev_level = orig_level; |
85aaf69f SL |
927 | } |
928 | ||
dfeec247 | 929 | fn visit_mod(&mut self, m: &'tcx hir::Mod<'tcx>, _sp: Span, id: hir::HirId) { |
85aaf69f SL |
930 | // This code is here instead of in visit_item so that the |
931 | // crate module gets processed as well. | |
92a42be0 | 932 | if self.prev_level.is_some() { |
416331ca | 933 | let def_id = self.tcx.hir().local_def_id(id); |
ea8adc8c XL |
934 | if let Some(exports) = self.tcx.module_exports(def_id) { |
935 | for export in exports.iter() { | |
13cf67c4 | 936 | if export.vis == ty::Visibility::Public { |
48663c56 | 937 | if let Some(def_id) = export.res.opt_def_id() { |
f9f354fc | 938 | if let Some(def_id) = def_id.as_local() { |
94222f64 | 939 | self.update(def_id, Some(AccessLevel::Exported)); |
13cf67c4 | 940 | } |
ff7c6d11 | 941 | } |
9cc50fc6 | 942 | } |
85aaf69f SL |
943 | } |
944 | } | |
945 | } | |
92a42be0 | 946 | |
5bcae85e | 947 | intravisit::walk_mod(self, m, id); |
92a42be0 | 948 | } |
7453a54e SL |
949 | } |
950 | ||
dc9dc135 | 951 | impl ReachEverythingInTheInterfaceVisitor<'_, 'tcx> { |
476ff2be | 952 | fn generics(&mut self) -> &mut Self { |
94b46f34 XL |
953 | for param in &self.ev.tcx.generics_of(self.item_def_id).params { |
954 | match param.kind { | |
532ac7d7 | 955 | GenericParamDefKind::Lifetime => {} |
94b46f34 XL |
956 | GenericParamDefKind::Type { has_default, .. } => { |
957 | if has_default { | |
0731742a | 958 | self.visit(self.ev.tcx.type_of(param.def_id)); |
94b46f34 XL |
959 | } |
960 | } | |
cdc7bbd5 | 961 | GenericParamDefKind::Const { has_default, .. } => { |
532ac7d7 | 962 | self.visit(self.ev.tcx.type_of(param.def_id)); |
cdc7bbd5 XL |
963 | if has_default { |
964 | self.visit(self.ev.tcx.const_param_default(param.def_id)); | |
965 | } | |
532ac7d7 | 966 | } |
8bb4bdeb XL |
967 | } |
968 | } | |
476ff2be SL |
969 | self |
970 | } | |
9e0c209e | 971 | |
476ff2be | 972 | fn predicates(&mut self) -> &mut Self { |
0731742a | 973 | self.visit_predicates(self.ev.tcx.predicates_of(self.item_def_id)); |
476ff2be SL |
974 | self |
975 | } | |
976 | ||
7cac9316 | 977 | fn ty(&mut self) -> &mut Self { |
0731742a | 978 | self.visit(self.ev.tcx.type_of(self.item_def_id)); |
476ff2be SL |
979 | self |
980 | } | |
981 | ||
0731742a XL |
982 | fn trait_ref(&mut self) -> &mut Self { |
983 | if let Some(trait_ref) = self.ev.tcx.impl_trait_ref(self.item_def_id) { | |
984 | self.visit_trait(trait_ref); | |
041b39d2 | 985 | } |
476ff2be SL |
986 | self |
987 | } | |
988 | } | |
989 | ||
dc9dc135 | 990 | impl DefIdVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'_, 'tcx> { |
dfeec247 XL |
991 | fn tcx(&self) -> TyCtxt<'tcx> { |
992 | self.ev.tcx | |
993 | } | |
29967ef6 XL |
994 | fn visit_def_id( |
995 | &mut self, | |
996 | def_id: DefId, | |
997 | _kind: &str, | |
998 | _descr: &dyn fmt::Display, | |
fc512014 | 999 | ) -> ControlFlow<Self::BreakTy> { |
f9f354fc | 1000 | if let Some(def_id) = def_id.as_local() { |
29967ef6 XL |
1001 | if let (ty::Visibility::Public, _) | (_, Some(AccessLevel::ReachableFromImplTrait)) = |
1002 | (self.tcx().visibility(def_id.to_def_id()), self.access_level) | |
416331ca | 1003 | { |
94222f64 | 1004 | self.ev.update(def_id, self.access_level); |
416331ca | 1005 | } |
7453a54e | 1006 | } |
29967ef6 | 1007 | ControlFlow::CONTINUE |
7453a54e | 1008 | } |
7453a54e SL |
1009 | } |
1010 | ||
7cac9316 XL |
1011 | ////////////////////////////////////////////////////////////////////////////////////// |
1012 | /// Name privacy visitor, checks privacy and reports violations. | |
1013 | /// Most of name privacy checks are performed during the main resolution phase, | |
1014 | /// or later in type checking when field accesses and associated items are resolved. | |
1015 | /// This pass performs remaining checks for fields in struct expressions and patterns. | |
1016 | ////////////////////////////////////////////////////////////////////////////////////// | |
85aaf69f | 1017 | |
f035d41b | 1018 | struct NamePrivacyVisitor<'tcx> { |
dc9dc135 | 1019 | tcx: TyCtxt<'tcx>, |
3dfed10e | 1020 | maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>, |
94222f64 | 1021 | current_item: LocalDefId, |
85aaf69f SL |
1022 | } |
1023 | ||
f035d41b | 1024 | impl<'tcx> NamePrivacyVisitor<'tcx> { |
3dfed10e | 1025 | /// Gets the type-checking results for the current body. |
f035d41b XL |
1026 | /// As this will ICE if called outside bodies, only call when working with |
1027 | /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies). | |
1028 | #[track_caller] | |
3dfed10e XL |
1029 | fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> { |
1030 | self.maybe_typeck_results | |
1031 | .expect("`NamePrivacyVisitor::typeck_results` called outside of body") | |
f035d41b XL |
1032 | } |
1033 | ||
0531ce1d | 1034 | // Checks that a field in a struct constructor (expression or pattern) is accessible. |
dfeec247 XL |
1035 | fn check_field( |
1036 | &mut self, | |
1037 | use_ctxt: Span, // syntax context of the field name at the use site | |
1038 | span: Span, // span of the field pattern, e.g., `x: 0` | |
1039 | def: &'tcx ty::AdtDef, // definition of the struct or enum | |
1040 | field: &'tcx ty::FieldDef, | |
ba9703b0 | 1041 | in_update_syntax: bool, |
dfeec247 | 1042 | ) { |
94222f64 XL |
1043 | if def.is_enum() { |
1044 | return; | |
1045 | } | |
1046 | ||
dfeec247 | 1047 | // definition of the field |
5869c6ff | 1048 | let ident = Ident::new(kw::Empty, use_ctxt); |
94222f64 XL |
1049 | let hir_id = self.tcx.hir().local_def_id_to_hir_id(self.current_item); |
1050 | let def_id = self.tcx.adjust_ident_and_get_scope(ident, def.did, hir_id).1; | |
1051 | if !field.vis.is_accessible_from(def_id, self.tcx) { | |
ba9703b0 XL |
1052 | let label = if in_update_syntax { |
1053 | format!("field `{}` is private", field.ident) | |
1054 | } else { | |
1055 | "private field".to_string() | |
1056 | }; | |
1057 | ||
dfeec247 XL |
1058 | struct_span_err!( |
1059 | self.tcx.sess, | |
1060 | span, | |
1061 | E0451, | |
1062 | "field `{}` of {} `{}` is private", | |
1063 | field.ident, | |
1064 | def.variant_descr(), | |
1065 | self.tcx.def_path_str(def.did) | |
1066 | ) | |
ba9703b0 | 1067 | .span_label(span, label) |
dfeec247 | 1068 | .emit(); |
85aaf69f SL |
1069 | } |
1070 | } | |
85aaf69f SL |
1071 | } |
1072 | ||
f035d41b | 1073 | impl<'tcx> Visitor<'tcx> for NamePrivacyVisitor<'tcx> { |
dfeec247 XL |
1074 | type Map = Map<'tcx>; |
1075 | ||
92a42be0 SL |
1076 | /// We want to visit items in the context of their containing |
1077 | /// module and so forth, so supply a crate for doing a deep walk. | |
ba9703b0 XL |
1078 | fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> { |
1079 | NestedVisitorMap::All(self.tcx.hir()) | |
32a655c1 SL |
1080 | } |
1081 | ||
dfeec247 | 1082 | fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) { |
9fa01778 XL |
1083 | // Don't visit nested modules, since we run a separate visitor walk |
1084 | // for each module in `privacy_access_levels` | |
1085 | } | |
1086 | ||
32a655c1 | 1087 | fn visit_nested_body(&mut self, body: hir::BodyId) { |
3dfed10e XL |
1088 | let old_maybe_typeck_results = |
1089 | self.maybe_typeck_results.replace(self.tcx.typeck_body(body)); | |
0731742a | 1090 | let body = self.tcx.hir().body(body); |
32a655c1 | 1091 | self.visit_body(body); |
3dfed10e | 1092 | self.maybe_typeck_results = old_maybe_typeck_results; |
92a42be0 SL |
1093 | } |
1094 | ||
dfeec247 | 1095 | fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { |
94222f64 | 1096 | let orig_current_item = mem::replace(&mut self.current_item, item.def_id); |
92a42be0 | 1097 | intravisit::walk_item(self, item); |
7cac9316 | 1098 | self.current_item = orig_current_item; |
85aaf69f SL |
1099 | } |
1100 | ||
dfeec247 | 1101 | fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { |
c295e0f8 | 1102 | if let hir::ExprKind::Struct(qpath, fields, ref base) = expr.kind { |
3dfed10e XL |
1103 | let res = self.typeck_results().qpath_res(qpath, expr.hir_id); |
1104 | let adt = self.typeck_results().expr_ty(expr).ty_adt_def().unwrap(); | |
ba9703b0 | 1105 | let variant = adt.variant_of_res(res); |
c295e0f8 | 1106 | if let Some(base) = *base { |
ba9703b0 XL |
1107 | // If the expression uses FRU we need to make sure all the unmentioned fields |
1108 | // are checked for privacy (RFC 736). Rather than computing the set of | |
1109 | // unmentioned fields, just check them all. | |
1110 | for (vf_index, variant_field) in variant.fields.iter().enumerate() { | |
3dfed10e XL |
1111 | let field = fields.iter().find(|f| { |
1112 | self.tcx.field_index(f.hir_id, self.typeck_results()) == vf_index | |
1113 | }); | |
ba9703b0 XL |
1114 | let (use_ctxt, span) = match field { |
1115 | Some(field) => (field.ident.span, field.span), | |
1116 | None => (base.span, base.span), | |
1117 | }; | |
1118 | self.check_field(use_ctxt, span, adt, variant_field, true); | |
1119 | } | |
1120 | } else { | |
1121 | for field in fields { | |
1122 | let use_ctxt = field.ident.span; | |
3dfed10e | 1123 | let index = self.tcx.field_index(field.hir_id, self.typeck_results()); |
ba9703b0 | 1124 | self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false); |
85aaf69f SL |
1125 | } |
1126 | } | |
85aaf69f SL |
1127 | } |
1128 | ||
92a42be0 | 1129 | intravisit::walk_expr(self, expr); |
85aaf69f SL |
1130 | } |
1131 | ||
dfeec247 | 1132 | fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) { |
ba9703b0 | 1133 | if let PatKind::Struct(ref qpath, fields, _) = pat.kind { |
3dfed10e XL |
1134 | let res = self.typeck_results().qpath_res(qpath, pat.hir_id); |
1135 | let adt = self.typeck_results().pat_ty(pat).ty_adt_def().unwrap(); | |
ba9703b0 XL |
1136 | let variant = adt.variant_of_res(res); |
1137 | for field in fields { | |
1138 | let use_ctxt = field.ident.span; | |
3dfed10e | 1139 | let index = self.tcx.field_index(field.hir_id, self.typeck_results()); |
ba9703b0 | 1140 | self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false); |
85aaf69f | 1141 | } |
85aaf69f SL |
1142 | } |
1143 | ||
7cac9316 | 1144 | intravisit::walk_pat(self, pat); |
85aaf69f | 1145 | } |
85aaf69f SL |
1146 | } |
1147 | ||
041b39d2 XL |
1148 | //////////////////////////////////////////////////////////////////////////////////////////// |
1149 | /// Type privacy visitor, checks types for privacy and reports violations. | |
cdc7bbd5 | 1150 | /// Both explicitly written types and inferred types of expressions and patterns are checked. |
041b39d2 XL |
1151 | /// Checks are performed on "semantic" types regardless of names and their hygiene. |
1152 | //////////////////////////////////////////////////////////////////////////////////////////// | |
1153 | ||
f035d41b | 1154 | struct TypePrivacyVisitor<'tcx> { |
dc9dc135 | 1155 | tcx: TyCtxt<'tcx>, |
3dfed10e | 1156 | maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>, |
f9f354fc | 1157 | current_item: LocalDefId, |
041b39d2 XL |
1158 | span: Span, |
1159 | } | |
1160 | ||
f035d41b | 1161 | impl<'tcx> TypePrivacyVisitor<'tcx> { |
3dfed10e | 1162 | /// Gets the type-checking results for the current body. |
f035d41b XL |
1163 | /// As this will ICE if called outside bodies, only call when working with |
1164 | /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies). | |
1165 | #[track_caller] | |
3dfed10e XL |
1166 | fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> { |
1167 | self.maybe_typeck_results | |
1168 | .expect("`TypePrivacyVisitor::typeck_results` called outside of body") | |
f035d41b XL |
1169 | } |
1170 | ||
041b39d2 | 1171 | fn item_is_accessible(&self, did: DefId) -> bool { |
29967ef6 | 1172 | self.tcx.visibility(did).is_accessible_from(self.current_item.to_def_id(), self.tcx) |
041b39d2 XL |
1173 | } |
1174 | ||
0731742a | 1175 | // Take node-id of an expression or pattern and check its type for privacy. |
3b2f2976 | 1176 | fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool { |
041b39d2 | 1177 | self.span = span; |
3dfed10e | 1178 | let typeck_results = self.typeck_results(); |
29967ef6 XL |
1179 | let result: ControlFlow<()> = try { |
1180 | self.visit(typeck_results.node_type(id))?; | |
1181 | self.visit(typeck_results.node_substs(id))?; | |
1182 | if let Some(adjustments) = typeck_results.adjustments().get(id) { | |
1183 | adjustments.iter().try_for_each(|adjustment| self.visit(adjustment.target))?; | |
041b39d2 | 1184 | } |
29967ef6 XL |
1185 | }; |
1186 | result.is_break() | |
041b39d2 | 1187 | } |
ff7c6d11 | 1188 | |
0731742a XL |
1189 | fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool { |
1190 | let is_error = !self.item_is_accessible(def_id); | |
1191 | if is_error { | |
ba9703b0 XL |
1192 | self.tcx |
1193 | .sess | |
1194 | .struct_span_err(self.span, &format!("{} `{}` is private", kind, descr)) | |
1195 | .span_label(self.span, &format!("private {}", kind)) | |
1196 | .emit(); | |
ff7c6d11 | 1197 | } |
0731742a | 1198 | is_error |
ff7c6d11 | 1199 | } |
041b39d2 XL |
1200 | } |
1201 | ||
f035d41b | 1202 | impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> { |
dfeec247 XL |
1203 | type Map = Map<'tcx>; |
1204 | ||
041b39d2 XL |
1205 | /// We want to visit items in the context of their containing |
1206 | /// module and so forth, so supply a crate for doing a deep walk. | |
ba9703b0 XL |
1207 | fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> { |
1208 | NestedVisitorMap::All(self.tcx.hir()) | |
041b39d2 XL |
1209 | } |
1210 | ||
dfeec247 | 1211 | fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) { |
9fa01778 XL |
1212 | // Don't visit nested modules, since we run a separate visitor walk |
1213 | // for each module in `privacy_access_levels` | |
1214 | } | |
1215 | ||
041b39d2 | 1216 | fn visit_nested_body(&mut self, body: hir::BodyId) { |
3dfed10e XL |
1217 | let old_maybe_typeck_results = |
1218 | self.maybe_typeck_results.replace(self.tcx.typeck_body(body)); | |
0731742a | 1219 | let body = self.tcx.hir().body(body); |
041b39d2 | 1220 | self.visit_body(body); |
3dfed10e | 1221 | self.maybe_typeck_results = old_maybe_typeck_results; |
041b39d2 XL |
1222 | } |
1223 | ||
94222f64 XL |
1224 | fn visit_generic_arg(&mut self, generic_arg: &'tcx hir::GenericArg<'tcx>) { |
1225 | match generic_arg { | |
1226 | hir::GenericArg::Type(t) => self.visit_ty(t), | |
1227 | hir::GenericArg::Infer(inf) => self.visit_infer(inf), | |
1228 | hir::GenericArg::Lifetime(_) | hir::GenericArg::Const(_) => {} | |
1229 | } | |
1230 | } | |
1231 | ||
dfeec247 | 1232 | fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) { |
ea8adc8c | 1233 | self.span = hir_ty.span; |
3dfed10e | 1234 | if let Some(typeck_results) = self.maybe_typeck_results { |
ea8adc8c | 1235 | // Types in bodies. |
29967ef6 | 1236 | if self.visit(typeck_results.node_type(hir_ty.hir_id)).is_break() { |
ea8adc8c XL |
1237 | return; |
1238 | } | |
1239 | } else { | |
1240 | // Types in signatures. | |
1241 | // FIXME: This is very ineffective. Ideally each HIR type should be converted | |
1242 | // into a semantic type only once and the result should be cached somehow. | |
29967ef6 | 1243 | if self.visit(rustc_typeck::hir_ty_to_ty(self.tcx, hir_ty)).is_break() { |
ea8adc8c XL |
1244 | return; |
1245 | } | |
1246 | } | |
1247 | ||
1248 | intravisit::walk_ty(self, hir_ty); | |
1249 | } | |
1250 | ||
94222f64 XL |
1251 | fn visit_infer(&mut self, inf: &'tcx hir::InferArg) { |
1252 | self.span = inf.span; | |
1253 | if let Some(typeck_results) = self.maybe_typeck_results { | |
1254 | if let Some(ty) = typeck_results.node_type_opt(inf.hir_id) { | |
1255 | if self.visit(ty).is_break() { | |
1256 | return; | |
1257 | } | |
1258 | } | |
1259 | } else { | |
1260 | let local_id = self.tcx.hir().local_def_id(inf.hir_id); | |
1261 | if let Some(did) = self.tcx.opt_const_param_of(local_id) { | |
1262 | if self.visit_def_id(did, "inferred", &"").is_break() { | |
1263 | return; | |
1264 | } | |
1265 | } | |
1266 | ||
1267 | // FIXME see above note for same issue. | |
1268 | if self.visit(rustc_typeck::hir_ty_to_ty(self.tcx, &inf.to_ty())).is_break() { | |
1269 | return; | |
1270 | } | |
1271 | } | |
1272 | intravisit::walk_inf(self, inf); | |
1273 | } | |
1274 | ||
dfeec247 | 1275 | fn visit_trait_ref(&mut self, trait_ref: &'tcx hir::TraitRef<'tcx>) { |
ff7c6d11 | 1276 | self.span = trait_ref.path.span; |
3dfed10e | 1277 | if self.maybe_typeck_results.is_none() { |
ff7c6d11 XL |
1278 | // Avoid calling `hir_trait_to_predicates` in bodies, it will ICE. |
1279 | // The traits' privacy in bodies is already checked as a part of trait object types. | |
ba9703b0 XL |
1280 | let bounds = rustc_typeck::hir_trait_to_predicates( |
1281 | self.tcx, | |
1282 | trait_ref, | |
1283 | // NOTE: This isn't really right, but the actual type doesn't matter here. It's | |
1284 | // just required by `ty::TraitRef`. | |
1285 | self.tcx.types.never, | |
1286 | ); | |
416331ca | 1287 | |
dfeec247 | 1288 | for (trait_predicate, _, _) in bounds.trait_bounds { |
29967ef6 | 1289 | if self.visit_trait(trait_predicate.skip_binder()).is_break() { |
416331ca XL |
1290 | return; |
1291 | } | |
ff7c6d11 | 1292 | } |
416331ca | 1293 | |
dc9dc135 | 1294 | for (poly_predicate, _) in bounds.projection_bounds { |
29967ef6 XL |
1295 | if self.visit(poly_predicate.skip_binder().ty).is_break() |
1296 | || self | |
6a06907d | 1297 | .visit_projection_ty(poly_predicate.skip_binder().projection_ty) |
29967ef6 | 1298 | .is_break() |
416331ca | 1299 | { |
ff7c6d11 XL |
1300 | return; |
1301 | } | |
1302 | } | |
ea8adc8c XL |
1303 | } |
1304 | ||
1305 | intravisit::walk_trait_ref(self, trait_ref); | |
1306 | } | |
1307 | ||
041b39d2 | 1308 | // Check types of expressions |
dfeec247 | 1309 | fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { |
3b2f2976 | 1310 | if self.check_expr_pat_type(expr.hir_id, expr.span) { |
041b39d2 XL |
1311 | // Do not check nested expressions if the error already happened. |
1312 | return; | |
1313 | } | |
e74abb32 | 1314 | match expr.kind { |
c295e0f8 | 1315 | hir::ExprKind::Assign(_, rhs, _) | hir::ExprKind::Match(rhs, ..) => { |
041b39d2 | 1316 | // Do not report duplicate errors for `x = y` and `match x { ... }`. |
3b2f2976 | 1317 | if self.check_expr_pat_type(rhs.hir_id, rhs.span) { |
041b39d2 XL |
1318 | return; |
1319 | } | |
1320 | } | |
f035d41b | 1321 | hir::ExprKind::MethodCall(_, span, _, _) => { |
041b39d2 | 1322 | // Method calls have to be checked specially. |
041b39d2 | 1323 | self.span = span; |
3dfed10e | 1324 | if let Some(def_id) = self.typeck_results().type_dependent_def_id(expr.hir_id) { |
29967ef6 | 1325 | if self.visit(self.tcx.type_of(def_id)).is_break() { |
8faf50e0 XL |
1326 | return; |
1327 | } | |
1328 | } else { | |
dfeec247 XL |
1329 | self.tcx |
1330 | .sess | |
1331 | .delay_span_bug(expr.span, "no type-dependent def for method call"); | |
041b39d2 XL |
1332 | } |
1333 | } | |
1334 | _ => {} | |
1335 | } | |
1336 | ||
1337 | intravisit::walk_expr(self, expr); | |
1338 | } | |
1339 | ||
ff7c6d11 XL |
1340 | // Prohibit access to associated items with insufficient nominal visibility. |
1341 | // | |
1342 | // Additionally, until better reachability analysis for macros 2.0 is available, | |
1343 | // we prohibit access to private statics from other crates, this allows to give | |
1344 | // more code internal visibility at link time. (Access to private functions | |
0531ce1d | 1345 | // is already prohibited by type privacy for function types.) |
dfeec247 | 1346 | fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: hir::HirId, span: Span) { |
f035d41b XL |
1347 | let def = match qpath { |
1348 | hir::QPath::Resolved(_, path) => match path.res { | |
1349 | Res::Def(kind, def_id) => Some((kind, def_id)), | |
1350 | _ => None, | |
1351 | }, | |
3dfed10e XL |
1352 | hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self |
1353 | .maybe_typeck_results | |
1354 | .and_then(|typeck_results| typeck_results.type_dependent_def(id)), | |
ff7c6d11 | 1355 | }; |
29967ef6 XL |
1356 | let def = def.filter(|(kind, _)| { |
1357 | matches!( | |
1358 | kind, | |
1359 | DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Static | |
1360 | ) | |
48663c56 XL |
1361 | }); |
1362 | if let Some((kind, def_id)) = def { | |
dfeec247 XL |
1363 | let is_local_static = |
1364 | if let DefKind::Static = kind { def_id.is_local() } else { false }; | |
ff7c6d11 | 1365 | if !self.item_is_accessible(def_id) && !is_local_static { |
ba9703b0 XL |
1366 | let sess = self.tcx.sess; |
1367 | let sm = sess.source_map(); | |
1368 | let name = match qpath { | |
3dfed10e XL |
1369 | hir::QPath::Resolved(..) | hir::QPath::LangItem(..) => { |
1370 | sm.span_to_snippet(qpath.span()).ok() | |
1371 | } | |
ba9703b0 | 1372 | hir::QPath::TypeRelative(_, segment) => Some(segment.ident.to_string()), |
ff7c6d11 | 1373 | }; |
ba9703b0 XL |
1374 | let kind = kind.descr(def_id); |
1375 | let msg = match name { | |
1376 | Some(name) => format!("{} `{}` is private", kind, name), | |
1377 | None => format!("{} is private", kind), | |
1378 | }; | |
1379 | sess.struct_span_err(span, &msg) | |
1380 | .span_label(span, &format!("private {}", kind)) | |
1381 | .emit(); | |
ff7c6d11 | 1382 | return; |
041b39d2 XL |
1383 | } |
1384 | } | |
1385 | ||
1386 | intravisit::walk_qpath(self, qpath, id, span); | |
1387 | } | |
1388 | ||
0731742a | 1389 | // Check types of patterns. |
dfeec247 | 1390 | fn visit_pat(&mut self, pattern: &'tcx hir::Pat<'tcx>) { |
3b2f2976 | 1391 | if self.check_expr_pat_type(pattern.hir_id, pattern.span) { |
041b39d2 XL |
1392 | // Do not check nested patterns if the error already happened. |
1393 | return; | |
1394 | } | |
1395 | ||
1396 | intravisit::walk_pat(self, pattern); | |
1397 | } | |
1398 | ||
dfeec247 | 1399 | fn visit_local(&mut self, local: &'tcx hir::Local<'tcx>) { |
c295e0f8 | 1400 | if let Some(init) = local.init { |
3b2f2976 | 1401 | if self.check_expr_pat_type(init.hir_id, init.span) { |
041b39d2 XL |
1402 | // Do not report duplicate errors for `let x = y`. |
1403 | return; | |
1404 | } | |
1405 | } | |
1406 | ||
1407 | intravisit::walk_local(self, local); | |
1408 | } | |
1409 | ||
0731742a | 1410 | // Check types in item interfaces. |
dfeec247 | 1411 | fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { |
6a06907d | 1412 | let orig_current_item = mem::replace(&mut self.current_item, item.def_id); |
3dfed10e | 1413 | let old_maybe_typeck_results = self.maybe_typeck_results.take(); |
041b39d2 | 1414 | intravisit::walk_item(self, item); |
3dfed10e | 1415 | self.maybe_typeck_results = old_maybe_typeck_results; |
041b39d2 XL |
1416 | self.current_item = orig_current_item; |
1417 | } | |
1418 | } | |
1419 | ||
f035d41b | 1420 | impl DefIdVisitor<'tcx> for TypePrivacyVisitor<'tcx> { |
dfeec247 XL |
1421 | fn tcx(&self) -> TyCtxt<'tcx> { |
1422 | self.tcx | |
1423 | } | |
29967ef6 XL |
1424 | fn visit_def_id( |
1425 | &mut self, | |
1426 | def_id: DefId, | |
1427 | kind: &str, | |
1428 | descr: &dyn fmt::Display, | |
fc512014 | 1429 | ) -> ControlFlow<Self::BreakTy> { |
29967ef6 XL |
1430 | if self.check_def_id(def_id, kind, descr) { |
1431 | ControlFlow::BREAK | |
1432 | } else { | |
1433 | ControlFlow::CONTINUE | |
1434 | } | |
041b39d2 XL |
1435 | } |
1436 | } | |
1437 | ||
9cc50fc6 SL |
1438 | /////////////////////////////////////////////////////////////////////////////// |
1439 | /// Obsolete visitors for checking for private items in public interfaces. | |
1440 | /// These visitors are supposed to be kept in frozen state and produce an | |
1441 | /// "old error node set". For backward compatibility the new visitor reports | |
1442 | /// warnings instead of hard errors when the erroneous node is not in this old set. | |
1443 | /////////////////////////////////////////////////////////////////////////////// | |
1444 | ||
dc9dc135 XL |
1445 | struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { |
1446 | tcx: TyCtxt<'tcx>, | |
92a42be0 | 1447 | access_levels: &'a AccessLevels, |
85aaf69f | 1448 | in_variant: bool, |
0731742a | 1449 | // Set of errors produced by this obsolete visitor. |
532ac7d7 | 1450 | old_error_set: HirIdSet, |
85aaf69f SL |
1451 | } |
1452 | ||
dc9dc135 | 1453 | struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> { |
9cc50fc6 | 1454 | inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>, |
0731742a | 1455 | /// Whether the type refers to private types. |
85aaf69f | 1456 | contains_private: bool, |
0731742a XL |
1457 | /// Whether we've recurred at all (i.e., if we're pointing at the |
1458 | /// first type on which `visit_ty` was called). | |
85aaf69f | 1459 | at_outer_type: bool, |
0731742a | 1460 | /// Whether that first type is a public path. |
85aaf69f SL |
1461 | outer_type_is_public_path: bool, |
1462 | } | |
1463 | ||
9cc50fc6 | 1464 | impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { |
dfeec247 | 1465 | fn path_is_private_type(&self, path: &hir::Path<'_>) -> bool { |
48663c56 XL |
1466 | let did = match path.res { |
1467 | Res::PrimTy(..) | Res::SelfTy(..) | Res::Err => return false, | |
1468 | res => res.def_id(), | |
85aaf69f | 1469 | }; |
b039eaaf | 1470 | |
85aaf69f SL |
1471 | // A path can only be private if: |
1472 | // it's in this crate... | |
f9f354fc | 1473 | if let Some(did) = did.as_local() { |
b039eaaf | 1474 | // .. and it corresponds to a private type in the AST (this returns |
0731742a | 1475 | // `None` for type parameters). |
3dfed10e | 1476 | match self.tcx.hir().find(self.tcx.hir().local_def_id_to_hir_id(did)) { |
c295e0f8 | 1477 | Some(Node::Item(item)) => !item.vis.node.is_pub(), |
b039eaaf SL |
1478 | Some(_) | None => false, |
1479 | } | |
1480 | } else { | |
ba9703b0 | 1481 | false |
85aaf69f | 1482 | } |
85aaf69f SL |
1483 | } |
1484 | ||
94222f64 | 1485 | fn trait_is_public(&self, trait_id: LocalDefId) -> bool { |
85aaf69f | 1486 | // FIXME: this would preferably be using `exported_items`, but all |
0731742a | 1487 | // traits are exported currently (see `EmbargoVisitor.exported_trait`). |
92a42be0 | 1488 | self.access_levels.is_public(trait_id) |
85aaf69f SL |
1489 | } |
1490 | ||
dfeec247 | 1491 | fn check_generic_bound(&mut self, bound: &hir::GenericBound<'_>) { |
8faf50e0 | 1492 | if let hir::GenericBound::Trait(ref trait_ref, _) = *bound { |
c295e0f8 | 1493 | if self.path_is_private_type(trait_ref.trait_ref.path) { |
532ac7d7 | 1494 | self.old_error_set.insert(trait_ref.trait_ref.hir_ref_id); |
85aaf69f SL |
1495 | } |
1496 | } | |
1497 | } | |
c34b1796 | 1498 | |
94222f64 XL |
1499 | fn item_is_public(&self, def_id: LocalDefId, vis: &hir::Visibility<'_>) -> bool { |
1500 | self.access_levels.is_reachable(def_id) || vis.node.is_pub() | |
c34b1796 | 1501 | } |
85aaf69f SL |
1502 | } |
1503 | ||
9cc50fc6 | 1504 | impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> { |
ba9703b0 | 1505 | type Map = intravisit::ErasedMap<'v>; |
dfeec247 | 1506 | |
ba9703b0 | 1507 | fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> { |
476ff2be SL |
1508 | NestedVisitorMap::None |
1509 | } | |
1510 | ||
94222f64 XL |
1511 | fn visit_generic_arg(&mut self, generic_arg: &'v hir::GenericArg<'v>) { |
1512 | match generic_arg { | |
1513 | hir::GenericArg::Type(t) => self.visit_ty(t), | |
1514 | hir::GenericArg::Infer(inf) => self.visit_ty(&inf.to_ty()), | |
1515 | hir::GenericArg::Lifetime(_) | hir::GenericArg::Const(_) => {} | |
1516 | } | |
1517 | } | |
1518 | ||
dfeec247 | 1519 | fn visit_ty(&mut self, ty: &hir::Ty<'_>) { |
c295e0f8 | 1520 | if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = ty.kind { |
476ff2be | 1521 | if self.inner.path_is_private_type(path) { |
85aaf69f | 1522 | self.contains_private = true; |
0731742a | 1523 | // Found what we're looking for, so let's stop working. |
dfeec247 | 1524 | return; |
476ff2be SL |
1525 | } |
1526 | } | |
e74abb32 | 1527 | if let hir::TyKind::Path(_) = ty.kind { |
476ff2be | 1528 | if self.at_outer_type { |
85aaf69f SL |
1529 | self.outer_type_is_public_path = true; |
1530 | } | |
1531 | } | |
1532 | self.at_outer_type = false; | |
92a42be0 | 1533 | intravisit::walk_ty(self, ty) |
85aaf69f SL |
1534 | } |
1535 | ||
0731742a | 1536 | // Don't want to recurse into `[, .. expr]`. |
dfeec247 | 1537 | fn visit_expr(&mut self, _: &hir::Expr<'_>) {} |
85aaf69f SL |
1538 | } |
1539 | ||
476ff2be | 1540 | impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { |
dfeec247 XL |
1541 | type Map = Map<'tcx>; |
1542 | ||
92a42be0 SL |
1543 | /// We want to visit items in the context of their containing |
1544 | /// module and so forth, so supply a crate for doing a deep walk. | |
ba9703b0 XL |
1545 | fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> { |
1546 | NestedVisitorMap::All(self.tcx.hir()) | |
92a42be0 SL |
1547 | } |
1548 | ||
dfeec247 | 1549 | fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { |
e74abb32 | 1550 | match item.kind { |
0731742a | 1551 | // Contents of a private mod can be re-exported, so we need |
85aaf69f | 1552 | // to check internals. |
8faf50e0 | 1553 | hir::ItemKind::Mod(_) => {} |
85aaf69f SL |
1554 | |
1555 | // An `extern {}` doesn't introduce a new privacy | |
1556 | // namespace (the contents have their own privacies). | |
fc512014 | 1557 | hir::ItemKind::ForeignMod { .. } => {} |
85aaf69f | 1558 | |
c295e0f8 | 1559 | hir::ItemKind::Trait(.., bounds, _) => { |
94222f64 | 1560 | if !self.trait_is_public(item.def_id) { |
dfeec247 | 1561 | return; |
85aaf69f SL |
1562 | } |
1563 | ||
62682a34 | 1564 | for bound in bounds.iter() { |
8faf50e0 | 1565 | self.check_generic_bound(bound) |
85aaf69f SL |
1566 | } |
1567 | } | |
1568 | ||
0731742a | 1569 | // Impls need some special handling to try to offer useful |
85aaf69f | 1570 | // error messages without (too many) false positives |
0731742a | 1571 | // (i.e., we could just return here to not check them at |
85aaf69f | 1572 | // all, or some worse estimation of whether an impl is |
c34b1796 | 1573 | // publicly visible). |
5869c6ff | 1574 | hir::ItemKind::Impl(ref impl_) => { |
85aaf69f SL |
1575 | // `impl [... for] Private` is never visible. |
1576 | let self_contains_private; | |
0731742a XL |
1577 | // `impl [... for] Public<...>`, but not `impl [... for] |
1578 | // Vec<Public>` or `(Public,)`, etc. | |
85aaf69f SL |
1579 | let self_is_public_path; |
1580 | ||
0731742a | 1581 | // Check the properties of the `Self` type: |
85aaf69f | 1582 | { |
9cc50fc6 | 1583 | let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor { |
85aaf69f SL |
1584 | inner: self, |
1585 | contains_private: false, | |
1586 | at_outer_type: true, | |
1587 | outer_type_is_public_path: false, | |
1588 | }; | |
c295e0f8 | 1589 | visitor.visit_ty(impl_.self_ty); |
85aaf69f SL |
1590 | self_contains_private = visitor.contains_private; |
1591 | self_is_public_path = visitor.outer_type_is_public_path; | |
1592 | } | |
1593 | ||
0731742a | 1594 | // Miscellaneous info about the impl: |
85aaf69f SL |
1595 | |
1596 | // `true` iff this is `impl Private for ...`. | |
5869c6ff | 1597 | let not_private_trait = impl_.of_trait.as_ref().map_or( |
dfeec247 XL |
1598 | true, // no trait counts as public trait |
1599 | |tr| { | |
94222f64 XL |
1600 | if let Some(def_id) = tr.path.res.def_id().as_local() { |
1601 | self.trait_is_public(def_id) | |
b039eaaf SL |
1602 | } else { |
1603 | true // external traits must be public | |
1604 | } | |
dfeec247 XL |
1605 | }, |
1606 | ); | |
85aaf69f SL |
1607 | |
1608 | // `true` iff this is a trait impl or at least one method is public. | |
1609 | // | |
1610 | // `impl Public { $( fn ...() {} )* }` is not visible. | |
1611 | // | |
1612 | // This is required over just using the methods' privacy | |
1613 | // directly because we might have `impl<T: Foo<Private>> ...`, | |
1614 | // and we shouldn't warn about the generics if all the methods | |
1615 | // are private (because `T` won't be visible externally). | |
5869c6ff XL |
1616 | let trait_or_some_public_method = impl_.of_trait.is_some() |
1617 | || impl_.items.iter().any(|impl_item_ref| { | |
dfeec247 XL |
1618 | let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); |
1619 | match impl_item.kind { | |
ba9703b0 | 1620 | hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..) => { |
94222f64 | 1621 | self.access_levels.is_reachable(impl_item_ref.id.def_id) |
dfeec247 | 1622 | } |
f035d41b | 1623 | hir::ImplItemKind::TyAlias(_) => false, |
dfeec247 XL |
1624 | } |
1625 | }); | |
85aaf69f | 1626 | |
dfeec247 | 1627 | if !self_contains_private && not_private_trait && trait_or_some_public_method { |
5869c6ff | 1628 | intravisit::walk_generics(self, &impl_.generics); |
85aaf69f | 1629 | |
5869c6ff | 1630 | match impl_.of_trait { |
85aaf69f | 1631 | None => { |
5869c6ff | 1632 | for impl_item_ref in impl_.items { |
c34b1796 AL |
1633 | // This is where we choose whether to walk down |
1634 | // further into the impl to check its items. We | |
1635 | // should only walk into public items so that we | |
1636 | // don't erroneously report errors for private | |
1637 | // types in private items. | |
0731742a | 1638 | let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); |
e74abb32 | 1639 | match impl_item.kind { |
ba9703b0 | 1640 | hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..) |
94222f64 XL |
1641 | if self |
1642 | .item_is_public(impl_item.def_id, &impl_item.vis) => | |
c34b1796 | 1643 | { |
92a42be0 | 1644 | intravisit::walk_impl_item(self, impl_item) |
c34b1796 | 1645 | } |
416331ca | 1646 | hir::ImplItemKind::TyAlias(..) => { |
92a42be0 | 1647 | intravisit::walk_impl_item(self, impl_item) |
85aaf69f | 1648 | } |
c34b1796 | 1649 | _ => {} |
85aaf69f SL |
1650 | } |
1651 | } | |
1652 | } | |
5869c6ff | 1653 | Some(ref tr) => { |
c34b1796 | 1654 | // Any private types in a trait impl fall into three |
85aaf69f SL |
1655 | // categories. |
1656 | // 1. mentioned in the trait definition | |
1657 | // 2. mentioned in the type params/generics | |
c34b1796 | 1658 | // 3. mentioned in the associated types of the impl |
85aaf69f SL |
1659 | // |
1660 | // Those in 1. can only occur if the trait is in | |
1661 | // this crate and will've been warned about on the | |
1662 | // trait definition (there's no need to warn twice | |
1663 | // so we don't check the methods). | |
1664 | // | |
1665 | // Those in 2. are warned via walk_generics and this | |
1666 | // call here. | |
c295e0f8 | 1667 | intravisit::walk_path(self, tr.path); |
c34b1796 AL |
1668 | |
1669 | // Those in 3. are warned with this call. | |
5869c6ff | 1670 | for impl_item_ref in impl_.items { |
0731742a | 1671 | let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); |
c295e0f8 | 1672 | if let hir::ImplItemKind::TyAlias(ty) = impl_item.kind { |
d9579d0f | 1673 | self.visit_ty(ty); |
c34b1796 AL |
1674 | } |
1675 | } | |
85aaf69f SL |
1676 | } |
1677 | } | |
5869c6ff | 1678 | } else if impl_.of_trait.is_none() && self_is_public_path { |
0731742a | 1679 | // `impl Public<Private> { ... }`. Any public static |
85aaf69f SL |
1680 | // methods will be visible as `Public::foo`. |
1681 | let mut found_pub_static = false; | |
5869c6ff | 1682 | for impl_item_ref in impl_.items { |
c295e0f8 XL |
1683 | if self.access_levels.is_reachable(impl_item_ref.id.def_id) |
1684 | || self.tcx.visibility(impl_item_ref.id.def_id) | |
1685 | == ty::Visibility::Public | |
1686 | { | |
0731742a | 1687 | let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); |
32a655c1 | 1688 | match impl_item_ref.kind { |
dc9dc135 | 1689 | AssocItemKind::Const => { |
d9579d0f | 1690 | found_pub_static = true; |
92a42be0 | 1691 | intravisit::walk_impl_item(self, impl_item); |
d9579d0f | 1692 | } |
ba9703b0 | 1693 | AssocItemKind::Fn { has_self: false } => { |
85aaf69f | 1694 | found_pub_static = true; |
92a42be0 | 1695 | intravisit::walk_impl_item(self, impl_item); |
85aaf69f | 1696 | } |
32a655c1 | 1697 | _ => {} |
85aaf69f | 1698 | } |
85aaf69f SL |
1699 | } |
1700 | } | |
1701 | if found_pub_static { | |
5869c6ff | 1702 | intravisit::walk_generics(self, &impl_.generics) |
85aaf69f SL |
1703 | } |
1704 | } | |
dfeec247 | 1705 | return; |
85aaf69f SL |
1706 | } |
1707 | ||
1708 | // `type ... = ...;` can contain private types, because | |
1709 | // we're introducing a new name. | |
416331ca | 1710 | hir::ItemKind::TyAlias(..) => return, |
85aaf69f | 1711 | |
0731742a | 1712 | // Not at all public, so we don't care. |
94222f64 | 1713 | _ if !self.item_is_public(item.def_id, &item.vis) => { |
c34b1796 AL |
1714 | return; |
1715 | } | |
85aaf69f SL |
1716 | |
1717 | _ => {} | |
1718 | } | |
1719 | ||
c34b1796 | 1720 | // We've carefully constructed it so that if we're here, then |
85aaf69f | 1721 | // any `visit_ty`'s will be called on things that are in |
0731742a | 1722 | // public signatures, i.e., things that we're interested in for |
85aaf69f | 1723 | // this visitor. |
92a42be0 | 1724 | intravisit::walk_item(self, item); |
85aaf69f SL |
1725 | } |
1726 | ||
dfeec247 XL |
1727 | fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) { |
1728 | for param in generics.params { | |
1729 | for bound in param.bounds { | |
b7449926 | 1730 | self.check_generic_bound(bound); |
85aaf69f | 1731 | } |
b7449926 | 1732 | } |
dfeec247 | 1733 | for predicate in generics.where_clause.predicates { |
85aaf69f | 1734 | match predicate { |
0731742a | 1735 | hir::WherePredicate::BoundPredicate(bound_pred) => { |
62682a34 | 1736 | for bound in bound_pred.bounds.iter() { |
8faf50e0 | 1737 | self.check_generic_bound(bound) |
85aaf69f SL |
1738 | } |
1739 | } | |
0731742a XL |
1740 | hir::WherePredicate::RegionPredicate(_) => {} |
1741 | hir::WherePredicate::EqPredicate(eq_pred) => { | |
c295e0f8 | 1742 | self.visit_ty(eq_pred.rhs_ty); |
85aaf69f SL |
1743 | } |
1744 | } | |
1745 | } | |
1746 | } | |
1747 | ||
dfeec247 | 1748 | fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) { |
94222f64 | 1749 | if self.access_levels.is_reachable(item.def_id) { |
92a42be0 | 1750 | intravisit::walk_foreign_item(self, item) |
85aaf69f SL |
1751 | } |
1752 | } | |
1753 | ||
dfeec247 | 1754 | fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) { |
c295e0f8 | 1755 | if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = t.kind { |
476ff2be | 1756 | if self.path_is_private_type(path) { |
532ac7d7 | 1757 | self.old_error_set.insert(t.hir_id); |
85aaf69f SL |
1758 | } |
1759 | } | |
92a42be0 | 1760 | intravisit::walk_ty(self, t) |
85aaf69f SL |
1761 | } |
1762 | ||
dfeec247 XL |
1763 | fn visit_variant( |
1764 | &mut self, | |
1765 | v: &'tcx hir::Variant<'tcx>, | |
1766 | g: &'tcx hir::Generics<'tcx>, | |
1767 | item_id: hir::HirId, | |
1768 | ) { | |
94222f64 | 1769 | if self.access_levels.is_reachable(self.tcx.hir().local_def_id(v.id)) { |
85aaf69f | 1770 | self.in_variant = true; |
92a42be0 | 1771 | intravisit::walk_variant(self, v, g, item_id); |
85aaf69f SL |
1772 | self.in_variant = false; |
1773 | } | |
1774 | } | |
1775 | ||
6a06907d | 1776 | fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) { |
8faf50e0 | 1777 | if s.vis.node.is_pub() || self.in_variant { |
6a06907d | 1778 | intravisit::walk_field_def(self, s); |
85aaf69f SL |
1779 | } |
1780 | } | |
1781 | ||
0731742a | 1782 | // We don't need to introspect into these at all: an |
85aaf69f SL |
1783 | // expression/block context can't possibly contain exported things. |
1784 | // (Making them no-ops stops us from traversing the whole AST without | |
1785 | // having to be super careful about our `walk_...` calls above.) | |
dfeec247 XL |
1786 | fn visit_block(&mut self, _: &'tcx hir::Block<'tcx>) {} |
1787 | fn visit_expr(&mut self, _: &'tcx hir::Expr<'tcx>) {} | |
85aaf69f SL |
1788 | } |
1789 | ||
9cc50fc6 SL |
1790 | /////////////////////////////////////////////////////////////////////////////// |
1791 | /// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and | |
1792 | /// finds any private components in it. | |
1793 | /// PrivateItemsInPublicInterfacesVisitor ensures there are no private types | |
1794 | /// and traits in public interfaces. | |
1795 | /////////////////////////////////////////////////////////////////////////////// | |
1796 | ||
dc9dc135 XL |
1797 | struct SearchInterfaceForPrivateItemsVisitor<'tcx> { |
1798 | tcx: TyCtxt<'tcx>, | |
94222f64 | 1799 | item_def_id: LocalDefId, |
0731742a | 1800 | /// The visitor checks that each component type is at least this visible. |
54a0048b | 1801 | required_visibility: ty::Visibility, |
cc61c64b | 1802 | has_pub_restricted: bool, |
476ff2be | 1803 | has_old_errors: bool, |
ff7c6d11 | 1804 | in_assoc_ty: bool, |
9cc50fc6 SL |
1805 | } |
1806 | ||
dc9dc135 | 1807 | impl SearchInterfaceForPrivateItemsVisitor<'tcx> { |
476ff2be | 1808 | fn generics(&mut self) -> &mut Self { |
94b46f34 XL |
1809 | for param in &self.tcx.generics_of(self.item_def_id).params { |
1810 | match param.kind { | |
532ac7d7 | 1811 | GenericParamDefKind::Lifetime => {} |
94b46f34 XL |
1812 | GenericParamDefKind::Type { has_default, .. } => { |
1813 | if has_default { | |
0731742a | 1814 | self.visit(self.tcx.type_of(param.def_id)); |
94b46f34 XL |
1815 | } |
1816 | } | |
94222f64 | 1817 | // FIXME(generic_const_exprs): May want to look inside const here |
cdc7bbd5 | 1818 | GenericParamDefKind::Const { .. } => { |
532ac7d7 XL |
1819 | self.visit(self.tcx.type_of(param.def_id)); |
1820 | } | |
8bb4bdeb XL |
1821 | } |
1822 | } | |
476ff2be | 1823 | self |
54a0048b | 1824 | } |
54a0048b | 1825 | |
476ff2be | 1826 | fn predicates(&mut self) -> &mut Self { |
0731742a | 1827 | // N.B., we use `explicit_predicates_of` and not `predicates_of` |
0bf4aa26 XL |
1828 | // because we don't want to report privacy errors due to where |
1829 | // clauses that the compiler inferred. We only want to | |
1830 | // consider the ones that the user wrote. This is important | |
1831 | // for the inferred outlives rules; see | |
1832 | // `src/test/ui/rfc-2093-infer-outlives/privacy.rs`. | |
0731742a | 1833 | self.visit_predicates(self.tcx.explicit_predicates_of(self.item_def_id)); |
476ff2be SL |
1834 | self |
1835 | } | |
1836 | ||
29967ef6 XL |
1837 | fn bounds(&mut self) -> &mut Self { |
1838 | self.visit_predicates(ty::GenericPredicates { | |
1839 | parent: None, | |
1840 | predicates: self.tcx.explicit_item_bounds(self.item_def_id), | |
1841 | }); | |
1842 | self | |
1843 | } | |
1844 | ||
7cac9316 | 1845 | fn ty(&mut self) -> &mut Self { |
0731742a | 1846 | self.visit(self.tcx.type_of(self.item_def_id)); |
476ff2be SL |
1847 | self |
1848 | } | |
1849 | ||
0731742a | 1850 | fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool { |
9fa01778 | 1851 | if self.leaks_private_dep(def_id) { |
74b04a01 | 1852 | self.tcx.struct_span_lint_hir( |
dfeec247 | 1853 | lint::builtin::EXPORTED_PRIVATE_DEPENDENCIES, |
94222f64 XL |
1854 | self.tcx.hir().local_def_id_to_hir_id(self.item_def_id), |
1855 | self.tcx.def_span(self.item_def_id.to_def_id()), | |
74b04a01 XL |
1856 | |lint| { |
1857 | lint.build(&format!( | |
1858 | "{} `{}` from private dependency '{}' in public \ | |
1859 | interface", | |
1860 | kind, | |
1861 | descr, | |
1862 | self.tcx.crate_name(def_id.krate) | |
1863 | )) | |
1864 | .emit() | |
1865 | }, | |
dfeec247 | 1866 | ); |
9fa01778 XL |
1867 | } |
1868 | ||
f9f354fc | 1869 | let hir_id = match def_id.as_local() { |
3dfed10e | 1870 | Some(def_id) => self.tcx.hir().local_def_id_to_hir_id(def_id), |
0731742a XL |
1871 | None => return false, |
1872 | }; | |
041b39d2 | 1873 | |
29967ef6 | 1874 | let vis = self.tcx.visibility(def_id); |
0731742a | 1875 | if !vis.is_at_least(self.required_visibility, self.tcx) { |
29967ef6 XL |
1876 | let vis_descr = match vis { |
1877 | ty::Visibility::Public => "public", | |
1878 | ty::Visibility::Invisible => "private", | |
1879 | ty::Visibility::Restricted(vis_def_id) => { | |
1880 | if vis_def_id == self.tcx.parent_module(hir_id).to_def_id() { | |
1881 | "private" | |
1882 | } else if vis_def_id.is_top_level_module() { | |
1883 | "crate-private" | |
1884 | } else { | |
1885 | "restricted" | |
1886 | } | |
1887 | } | |
1888 | }; | |
74b04a01 | 1889 | let make_msg = || format!("{} {} `{}` in public interface", vis_descr, kind, descr); |
94222f64 | 1890 | let span = self.tcx.def_span(self.item_def_id.to_def_id()); |
0731742a XL |
1891 | if self.has_pub_restricted || self.has_old_errors || self.in_assoc_ty { |
1892 | let mut err = if kind == "trait" { | |
94222f64 | 1893 | struct_span_err!(self.tcx.sess, span, E0445, "{}", make_msg()) |
041b39d2 | 1894 | } else { |
94222f64 | 1895 | struct_span_err!(self.tcx.sess, span, E0446, "{}", make_msg()) |
0731742a | 1896 | }; |
29967ef6 XL |
1897 | let vis_span = |
1898 | self.tcx.sess.source_map().guess_head_span(self.tcx.def_span(def_id)); | |
94222f64 | 1899 | err.span_label(span, format!("can't leak {} {}", vis_descr, kind)); |
0731742a XL |
1900 | err.span_label(vis_span, format!("`{}` declared as {}", descr, vis_descr)); |
1901 | err.emit(); | |
1902 | } else { | |
1903 | let err_code = if kind == "trait" { "E0445" } else { "E0446" }; | |
74b04a01 | 1904 | self.tcx.struct_span_lint_hir( |
dfeec247 XL |
1905 | lint::builtin::PRIVATE_IN_PUBLIC, |
1906 | hir_id, | |
94222f64 | 1907 | span, |
74b04a01 | 1908 | |lint| lint.build(&format!("{} (error {})", make_msg(), err_code)).emit(), |
dfeec247 | 1909 | ); |
041b39d2 XL |
1910 | } |
1911 | } | |
9fa01778 | 1912 | |
0731742a | 1913 | false |
041b39d2 | 1914 | } |
9fa01778 XL |
1915 | |
1916 | /// An item is 'leaked' from a private dependency if all | |
1917 | /// of the following are true: | |
1918 | /// 1. It's contained within a public type | |
1919 | /// 2. It comes from a private crate | |
1920 | fn leaks_private_dep(&self, item_id: DefId) -> bool { | |
dfeec247 XL |
1921 | let ret = self.required_visibility == ty::Visibility::Public |
1922 | && self.tcx.is_private_dep(item_id.krate); | |
9fa01778 | 1923 | |
3dfed10e | 1924 | tracing::debug!("leaks_private_dep(item_id={:?})={}", item_id, ret); |
ba9703b0 | 1925 | ret |
9fa01778 | 1926 | } |
9cc50fc6 SL |
1927 | } |
1928 | ||
dc9dc135 | 1929 | impl DefIdVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'tcx> { |
dfeec247 XL |
1930 | fn tcx(&self) -> TyCtxt<'tcx> { |
1931 | self.tcx | |
1932 | } | |
29967ef6 XL |
1933 | fn visit_def_id( |
1934 | &mut self, | |
1935 | def_id: DefId, | |
1936 | kind: &str, | |
1937 | descr: &dyn fmt::Display, | |
fc512014 | 1938 | ) -> ControlFlow<Self::BreakTy> { |
29967ef6 XL |
1939 | if self.check_def_id(def_id, kind, descr) { |
1940 | ControlFlow::BREAK | |
1941 | } else { | |
1942 | ControlFlow::CONTINUE | |
1943 | } | |
9cc50fc6 | 1944 | } |
9cc50fc6 SL |
1945 | } |
1946 | ||
6a06907d | 1947 | struct PrivateItemsInPublicInterfacesVisitor<'tcx> { |
dc9dc135 | 1948 | tcx: TyCtxt<'tcx>, |
cc61c64b | 1949 | has_pub_restricted: bool, |
94222f64 | 1950 | old_error_set_ancestry: LocalDefIdSet, |
9cc50fc6 SL |
1951 | } |
1952 | ||
6a06907d | 1953 | impl<'tcx> PrivateItemsInPublicInterfacesVisitor<'tcx> { |
dc9dc135 XL |
1954 | fn check( |
1955 | &self, | |
94222f64 | 1956 | def_id: LocalDefId, |
dc9dc135 XL |
1957 | required_visibility: ty::Visibility, |
1958 | ) -> SearchInterfaceForPrivateItemsVisitor<'tcx> { | |
476ff2be SL |
1959 | SearchInterfaceForPrivateItemsVisitor { |
1960 | tcx: self.tcx, | |
94222f64 | 1961 | item_def_id: def_id, |
3b2f2976 | 1962 | required_visibility, |
cc61c64b | 1963 | has_pub_restricted: self.has_pub_restricted, |
94222f64 | 1964 | has_old_errors: self.old_error_set_ancestry.contains(&def_id), |
ff7c6d11 | 1965 | in_assoc_ty: false, |
9fa01778 XL |
1966 | } |
1967 | } | |
1968 | ||
dc9dc135 XL |
1969 | fn check_assoc_item( |
1970 | &self, | |
94222f64 | 1971 | def_id: LocalDefId, |
dc9dc135 XL |
1972 | assoc_item_kind: AssocItemKind, |
1973 | defaultness: hir::Defaultness, | |
1974 | vis: ty::Visibility, | |
1975 | ) { | |
94222f64 | 1976 | let mut check = self.check(def_id, vis); |
9fa01778 XL |
1977 | |
1978 | let (check_ty, is_assoc_ty) = match assoc_item_kind { | |
ba9703b0 | 1979 | AssocItemKind::Const | AssocItemKind::Fn { .. } => (true, false), |
dc9dc135 | 1980 | AssocItemKind::Type => (defaultness.has_value(), true), |
9fa01778 XL |
1981 | }; |
1982 | check.in_assoc_ty = is_assoc_ty; | |
1983 | check.generics().predicates(); | |
1984 | if check_ty { | |
1985 | check.ty(); | |
476ff2be | 1986 | } |
9cc50fc6 SL |
1987 | } |
1988 | } | |
1989 | ||
6a06907d | 1990 | impl<'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'tcx> { |
dfeec247 XL |
1991 | type Map = Map<'tcx>; |
1992 | ||
ba9703b0 XL |
1993 | fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> { |
1994 | NestedVisitorMap::OnlyBodies(self.tcx.hir()) | |
476ff2be SL |
1995 | } |
1996 | ||
dfeec247 | 1997 | fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { |
476ff2be | 1998 | let tcx = self.tcx; |
6a06907d | 1999 | let item_visibility = tcx.visibility(item.def_id); |
54a0048b | 2000 | |
e74abb32 | 2001 | match item.kind { |
0731742a | 2002 | // Crates are always public. |
8faf50e0 | 2003 | hir::ItemKind::ExternCrate(..) => {} |
0731742a | 2004 | // All nested items are checked by `visit_item`. |
8faf50e0 | 2005 | hir::ItemKind::Mod(..) => {} |
0731742a | 2006 | // Checked in resolve. |
8faf50e0 | 2007 | hir::ItemKind::Use(..) => {} |
0731742a | 2008 | // No subitems. |
94222f64 | 2009 | hir::ItemKind::Macro(..) | hir::ItemKind::GlobalAsm(..) => {} |
0731742a | 2010 | // Subitems of these items have inherited publicity. |
dfeec247 XL |
2011 | hir::ItemKind::Const(..) |
2012 | | hir::ItemKind::Static(..) | |
2013 | | hir::ItemKind::Fn(..) | |
2014 | | hir::ItemKind::TyAlias(..) => { | |
94222f64 | 2015 | self.check(item.def_id, item_visibility).generics().predicates().ty(); |
0731742a | 2016 | } |
416331ca XL |
2017 | hir::ItemKind::OpaqueTy(..) => { |
2018 | // `ty()` for opaque types is the underlying type, | |
0731742a | 2019 | // it's not a part of interface, so we skip it. |
94222f64 | 2020 | self.check(item.def_id, item_visibility).generics().bounds(); |
476ff2be | 2021 | } |
dfeec247 | 2022 | hir::ItemKind::Trait(.., trait_item_refs) => { |
94222f64 | 2023 | self.check(item.def_id, item_visibility).generics().predicates(); |
476ff2be | 2024 | |
32a655c1 | 2025 | for trait_item_ref in trait_item_refs { |
dc9dc135 | 2026 | self.check_assoc_item( |
94222f64 | 2027 | trait_item_ref.id.def_id, |
dc9dc135 XL |
2028 | trait_item_ref.kind, |
2029 | trait_item_ref.defaultness, | |
2030 | item_visibility, | |
2031 | ); | |
29967ef6 XL |
2032 | |
2033 | if let AssocItemKind::Type = trait_item_ref.kind { | |
94222f64 | 2034 | self.check(trait_item_ref.id.def_id, item_visibility).bounds(); |
29967ef6 | 2035 | } |
476ff2be SL |
2036 | } |
2037 | } | |
8faf50e0 | 2038 | hir::ItemKind::TraitAlias(..) => { |
94222f64 | 2039 | self.check(item.def_id, item_visibility).generics().predicates(); |
ff7c6d11 | 2040 | } |
8faf50e0 | 2041 | hir::ItemKind::Enum(ref def, _) => { |
94222f64 | 2042 | self.check(item.def_id, item_visibility).generics().predicates(); |
476ff2be | 2043 | |
dfeec247 | 2044 | for variant in def.variants { |
e1599b0c | 2045 | for field in variant.data.fields() { |
94222f64 | 2046 | self.check(self.tcx.hir().local_def_id(field.hir_id), item_visibility).ty(); |
476ff2be SL |
2047 | } |
2048 | } | |
9cc50fc6 | 2049 | } |
0731742a | 2050 | // Subitems of foreign modules have their own publicity. |
fc512014 XL |
2051 | hir::ItemKind::ForeignMod { items, .. } => { |
2052 | for foreign_item in items { | |
6a06907d | 2053 | let vis = tcx.visibility(foreign_item.id.def_id); |
94222f64 | 2054 | self.check(foreign_item.id.def_id, vis).generics().predicates().ty(); |
9cc50fc6 SL |
2055 | } |
2056 | } | |
0731742a | 2057 | // Subitems of structs and unions have their own publicity. |
dfeec247 | 2058 | hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => { |
94222f64 | 2059 | self.check(item.def_id, item_visibility).generics().predicates(); |
54a0048b SL |
2060 | |
2061 | for field in struct_def.fields() { | |
94222f64 XL |
2062 | let def_id = tcx.hir().local_def_id(field.hir_id); |
2063 | let field_visibility = tcx.visibility(def_id); | |
2064 | self.check(def_id, min(item_visibility, field_visibility, tcx)).ty(); | |
9cc50fc6 SL |
2065 | } |
2066 | } | |
9cc50fc6 | 2067 | // An inherent impl is public when its type is public |
0731742a | 2068 | // Subitems of inherent impls have their own publicity. |
9cc50fc6 | 2069 | // A trait impl is public when both its type and its trait are public |
0731742a | 2070 | // Subitems of trait impls have inherited publicity. |
5869c6ff | 2071 | hir::ItemKind::Impl(ref impl_) => { |
94222f64 XL |
2072 | let impl_vis = ty::Visibility::of_impl(item.def_id, tcx, &Default::default()); |
2073 | self.check(item.def_id, impl_vis).generics().predicates(); | |
5869c6ff XL |
2074 | for impl_item_ref in impl_.items { |
2075 | let impl_item_vis = if impl_.of_trait.is_none() { | |
6a06907d | 2076 | min(tcx.visibility(impl_item_ref.id.def_id), impl_vis, tcx) |
0731742a XL |
2077 | } else { |
2078 | impl_vis | |
2079 | }; | |
dc9dc135 | 2080 | self.check_assoc_item( |
94222f64 | 2081 | impl_item_ref.id.def_id, |
dc9dc135 XL |
2082 | impl_item_ref.kind, |
2083 | impl_item_ref.defaultness, | |
2084 | impl_item_vis, | |
2085 | ); | |
9cc50fc6 SL |
2086 | } |
2087 | } | |
2088 | } | |
2089 | } | |
2090 | } | |
2091 | ||
f035d41b | 2092 | pub fn provide(providers: &mut Providers) { |
cc61c64b | 2093 | *providers = Providers { |
29967ef6 | 2094 | visibility, |
cc61c64b | 2095 | privacy_access_levels, |
532ac7d7 | 2096 | check_private_in_public, |
9fa01778 | 2097 | check_mod_privacy, |
cc61c64b XL |
2098 | ..*providers |
2099 | }; | |
2100 | } | |
2101 | ||
29967ef6 XL |
2102 | fn visibility(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Visibility { |
2103 | let def_id = def_id.expect_local(); | |
136023e0 | 2104 | match tcx.resolutions(()).visibilities.get(&def_id) { |
29967ef6 XL |
2105 | Some(vis) => *vis, |
2106 | None => { | |
2107 | let hir_id = tcx.hir().local_def_id_to_hir_id(def_id); | |
2108 | match tcx.hir().get(hir_id) { | |
2109 | // Unique types created for closures participate in type privacy checking. | |
2110 | // They have visibilities inherited from the module they are defined in. | |
2111 | Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => { | |
2112 | ty::Visibility::Restricted(tcx.parent_module(hir_id).to_def_id()) | |
2113 | } | |
2114 | // - AST lowering may clone `use` items and the clones don't | |
2115 | // get their entries in the resolver's visibility table. | |
2116 | // - AST lowering also creates opaque type items with inherited visibilies. | |
2117 | // Visibility on them should have no effect, but to avoid the visibility | |
2118 | // query failing on some items, we provide it for opaque types as well. | |
2119 | Node::Item(hir::Item { | |
2120 | vis, | |
2121 | kind: hir::ItemKind::Use(..) | hir::ItemKind::OpaqueTy(..), | |
2122 | .. | |
2123 | }) => ty::Visibility::from_hir(vis, hir_id, tcx), | |
2124 | // Visibilities of trait impl items are inherited from their traits | |
2125 | // and are not filled in resolve. | |
2126 | Node::ImplItem(impl_item) => { | |
2127 | match tcx.hir().get(tcx.hir().get_parent_item(hir_id)) { | |
2128 | Node::Item(hir::Item { | |
5869c6ff | 2129 | kind: hir::ItemKind::Impl(hir::Impl { of_trait: Some(tr), .. }), |
29967ef6 XL |
2130 | .. |
2131 | }) => tr.path.res.opt_def_id().map_or_else( | |
2132 | || { | |
2133 | tcx.sess.delay_span_bug(tr.path.span, "trait without a def-id"); | |
2134 | ty::Visibility::Public | |
2135 | }, | |
2136 | |def_id| tcx.visibility(def_id), | |
2137 | ), | |
2138 | _ => span_bug!(impl_item.span, "the parent is not a trait impl"), | |
2139 | } | |
2140 | } | |
2141 | _ => span_bug!( | |
2142 | tcx.def_span(def_id), | |
2143 | "visibility table unexpectedly missing a def-id: {:?}", | |
2144 | def_id, | |
2145 | ), | |
2146 | } | |
2147 | } | |
2148 | } | |
2149 | } | |
2150 | ||
f9f354fc | 2151 | fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { |
7cac9316 | 2152 | // Check privacy of names not checked in previous compilation stages. |
94222f64 XL |
2153 | let mut visitor = |
2154 | NamePrivacyVisitor { tcx, maybe_typeck_results: None, current_item: module_def_id }; | |
532ac7d7 | 2155 | let (module, span, hir_id) = tcx.hir().get_module(module_def_id); |
48663c56 | 2156 | |
9fa01778 | 2157 | intravisit::walk_mod(&mut visitor, module, hir_id); |
85aaf69f | 2158 | |
041b39d2 XL |
2159 | // Check privacy of explicitly written types and traits as well as |
2160 | // inferred types of expressions and patterns. | |
f035d41b | 2161 | let mut visitor = |
3dfed10e | 2162 | TypePrivacyVisitor { tcx, maybe_typeck_results: None, current_item: module_def_id, span }; |
9fa01778 XL |
2163 | intravisit::walk_mod(&mut visitor, module, hir_id); |
2164 | } | |
2165 | ||
17df50a5 | 2166 | fn privacy_access_levels(tcx: TyCtxt<'_>, (): ()) -> &AccessLevels { |
85aaf69f SL |
2167 | // Build up a set of all exported items in the AST. This is a set of all |
2168 | // items which are reachable from external crates based on visibility. | |
2169 | let mut visitor = EmbargoVisitor { | |
3b2f2976 | 2170 | tcx, |
92a42be0 | 2171 | access_levels: Default::default(), |
416331ca | 2172 | macro_reachable: Default::default(), |
92a42be0 SL |
2173 | prev_level: Some(AccessLevel::Public), |
2174 | changed: false, | |
85aaf69f SL |
2175 | }; |
2176 | loop { | |
c295e0f8 | 2177 | tcx.hir().walk_toplevel_module(&mut visitor); |
92a42be0 SL |
2178 | if visitor.changed { |
2179 | visitor.changed = false; | |
2180 | } else { | |
dfeec247 | 2181 | break; |
85aaf69f SL |
2182 | } |
2183 | } | |
94222f64 | 2184 | visitor.update(CRATE_DEF_ID, Some(AccessLevel::Public)); |
85aaf69f | 2185 | |
dc9dc135 | 2186 | tcx.arena.alloc(visitor.access_levels) |
532ac7d7 | 2187 | } |
9cc50fc6 | 2188 | |
17df50a5 XL |
2189 | fn check_private_in_public(tcx: TyCtxt<'_>, (): ()) { |
2190 | let access_levels = tcx.privacy_access_levels(()); | |
532ac7d7 | 2191 | |
532ac7d7 XL |
2192 | let mut visitor = ObsoleteVisiblePrivateTypesVisitor { |
2193 | tcx, | |
c295e0f8 | 2194 | access_levels, |
532ac7d7 XL |
2195 | in_variant: false, |
2196 | old_error_set: Default::default(), | |
2197 | }; | |
c295e0f8 | 2198 | tcx.hir().walk_toplevel_module(&mut visitor); |
532ac7d7 XL |
2199 | |
2200 | let has_pub_restricted = { | |
dfeec247 | 2201 | let mut pub_restricted_visitor = PubRestrictedVisitor { tcx, has_pub_restricted: false }; |
c295e0f8 | 2202 | tcx.hir().walk_toplevel_module(&mut pub_restricted_visitor); |
532ac7d7 XL |
2203 | pub_restricted_visitor.has_pub_restricted |
2204 | }; | |
92a42be0 | 2205 | |
6a06907d XL |
2206 | let mut old_error_set_ancestry = HirIdSet::default(); |
2207 | for mut id in visitor.old_error_set.iter().copied() { | |
2208 | loop { | |
2209 | if !old_error_set_ancestry.insert(id) { | |
2210 | break; | |
2211 | } | |
2212 | let parent = tcx.hir().get_parent_node(id); | |
2213 | if parent == id { | |
2214 | break; | |
2215 | } | |
2216 | id = parent; | |
2217 | } | |
2218 | } | |
2219 | ||
532ac7d7 | 2220 | // Check for private types and traits in public interfaces. |
94222f64 XL |
2221 | let mut visitor = PrivateItemsInPublicInterfacesVisitor { |
2222 | tcx, | |
2223 | has_pub_restricted, | |
2224 | // Only definition IDs are ever searched in `old_error_set_ancestry`, | |
2225 | // so we can filter away all non-definition IDs at this point. | |
2226 | old_error_set_ancestry: old_error_set_ancestry | |
2227 | .into_iter() | |
2228 | .filter_map(|hir_id| tcx.hir().opt_local_def_id(hir_id)) | |
2229 | .collect(), | |
2230 | }; | |
c295e0f8 | 2231 | tcx.hir().visit_all_item_likes(&mut DeepVisitor::new(&mut visitor)); |
85aaf69f | 2232 | } |