1#![feature(associated_type_defaults)]
3#![feature(default_field_values)]
4#![feature(try_blocks)]
5mod errors;
8
9use std::fmt;
10use std::marker::PhantomData;
11use std::ops::ControlFlow;
12
13use errors::{
14 FieldIsPrivate, FieldIsPrivateLabel, FromPrivateDependencyInPublicInterface, InPublicInterface,
15 ItemIsPrivate, PrivateInterfacesOrBoundsLint, ReportEffectiveVisibility, UnnameableTypesLint,
16 UnnamedItemIsPrivate,
17};
18use rustc_ast::MacroDef;
19use rustc_ast::visit::{VisitorResult, try_visit};
20use rustc_data_structures::fx::FxHashSet;
21use rustc_data_structures::intern::Interned;
22use rustc_errors::{MultiSpan, listify};
23use rustc_hir as hir;
24use rustc_hir::def::{DefKind, Res};
25use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId};
26use rustc_hir::intravisit::{self, InferKind, Visitor};
27use rustc_hir::{AmbigArg, ForeignItemId, ItemId, OwnerId, PatKind, find_attr};
28use rustc_middle::middle::privacy::{EffectiveVisibilities, EffectiveVisibility, Level};
29use rustc_middle::query::Providers;
30use rustc_middle::ty::print::PrintTraitRefExt as _;
31use rustc_middle::ty::{
32 self, AssocContainer, Const, GenericParamDefKind, TraitRef, Ty, TyCtxt, TypeSuperVisitable,
33 TypeVisitable, TypeVisitor,
34};
35use rustc_middle::{bug, span_bug};
36use rustc_session::lint;
37use rustc_span::hygiene::Transparency;
38use rustc_span::{Ident, Span, Symbol, sym};
39use tracing::debug;
40
41struct LazyDefPathStr<'tcx> {
46 def_id: DefId,
47 tcx: TyCtxt<'tcx>,
48}
49
50impl<'tcx> fmt::Display for LazyDefPathStr<'tcx> {
51 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52 f.write_fmt(format_args!("{0}", self.tcx.def_path_str(self.def_id)))write!(f, "{}", self.tcx.def_path_str(self.def_id))
53 }
54}
55
56pub trait DefIdVisitor<'tcx> {
65 type Result: VisitorResult = ();
66 const SHALLOW: bool = false;
67 fn skip_assoc_tys(&self) -> bool {
68 false
69 }
70
71 fn tcx(&self) -> TyCtxt<'tcx>;
72 fn visit_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display)
76 -> Self::Result;
77
78 fn skeleton(&mut self) -> DefIdVisitorSkeleton<'_, 'tcx, Self> {
80 DefIdVisitorSkeleton {
81 def_id_visitor: self,
82 visited_tys: Default::default(),
83 dummy: Default::default(),
84 }
85 }
86 fn visit(&mut self, ty_fragment: impl TypeVisitable<TyCtxt<'tcx>>) -> Self::Result {
87 ty_fragment.visit_with(&mut self.skeleton())
88 }
89 fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> Self::Result {
90 self.skeleton().visit_trait(trait_ref)
91 }
92 fn visit_predicates(&mut self, predicates: ty::GenericPredicates<'tcx>) -> Self::Result {
93 self.skeleton().visit_clauses(predicates.predicates)
94 }
95 fn visit_clauses(&mut self, clauses: &[(ty::Clause<'tcx>, Span)]) -> Self::Result {
96 self.skeleton().visit_clauses(clauses)
97 }
98}
99
100pub struct DefIdVisitorSkeleton<'v, 'tcx, V: ?Sized> {
101 def_id_visitor: &'v mut V,
102 visited_tys: FxHashSet<Ty<'tcx>>,
103 dummy: PhantomData<TyCtxt<'tcx>>,
104}
105
106impl<'tcx, V> DefIdVisitorSkeleton<'_, 'tcx, V>
107where
108 V: DefIdVisitor<'tcx> + ?Sized,
109{
110 fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> V::Result {
111 let TraitRef { def_id, args, .. } = trait_ref;
112 match ::rustc_ast_ir::visit::VisitorResult::branch(self.def_id_visitor.visit_def_id(def_id,
"trait", &trait_ref.print_only_trait_path())) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(self.def_id_visitor.visit_def_id(
113 def_id,
114 "trait",
115 &trait_ref.print_only_trait_path()
116 ));
117 if V::SHALLOW { V::Result::output() } else { args.visit_with(self) }
118 }
119
120 fn visit_projection_term(&mut self, projection: ty::AliasTerm<'tcx>) -> V::Result {
121 let tcx = self.def_id_visitor.tcx();
122 let (trait_ref, assoc_args) = projection.trait_ref_and_own_args(tcx);
123 match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_trait(trait_ref))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(self.visit_trait(trait_ref));
124 if V::SHALLOW {
125 V::Result::output()
126 } else {
127 V::Result::from_branch(
128 assoc_args.iter().try_for_each(|arg| arg.visit_with(self).branch()),
129 )
130 }
131 }
132
133 fn visit_clause(&mut self, clause: ty::Clause<'tcx>) -> V::Result {
134 match clause.kind().skip_binder() {
135 ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity: _ }) => {
136 self.visit_trait(trait_ref)
137 }
138 ty::ClauseKind::HostEffect(pred) => {
139 match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_trait(pred.trait_ref))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(self.visit_trait(pred.trait_ref));
140 pred.constness.visit_with(self)
141 }
142 ty::ClauseKind::Projection(ty::ProjectionPredicate {
143 projection_term: projection_ty,
144 term,
145 }) => {
146 match ::rustc_ast_ir::visit::VisitorResult::branch(term.visit_with(self)) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(term.visit_with(self));
147 self.visit_projection_term(projection_ty)
148 }
149 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty, _region)) => ty.visit_with(self),
150 ty::ClauseKind::RegionOutlives(..) => V::Result::output(),
151 ty::ClauseKind::ConstArgHasType(ct, ty) => {
152 match ::rustc_ast_ir::visit::VisitorResult::branch(ct.visit_with(self)) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(ct.visit_with(self));
153 ty.visit_with(self)
154 }
155 ty::ClauseKind::ConstEvaluatable(ct) => ct.visit_with(self),
156 ty::ClauseKind::WellFormed(term) => term.visit_with(self),
157 ty::ClauseKind::UnstableFeature(_) => V::Result::output(),
158 }
159 }
160
161 fn visit_clauses(&mut self, clauses: &[(ty::Clause<'tcx>, Span)]) -> V::Result {
162 for &(clause, _) in clauses {
163 match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_clause(clause))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(self.visit_clause(clause));
164 }
165 V::Result::output()
166 }
167}
168
169impl<'tcx, V> TypeVisitor<TyCtxt<'tcx>> for DefIdVisitorSkeleton<'_, 'tcx, V>
170where
171 V: DefIdVisitor<'tcx> + ?Sized,
172{
173 type Result = V::Result;
174
175 fn visit_predicate(&mut self, p: ty::Predicate<'tcx>) -> Self::Result {
176 self.visit_clause(p.as_clause().unwrap())
177 }
178
179 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
180 let tcx = self.def_id_visitor.tcx();
181 let ty_kind = *ty.kind();
184 match ty_kind {
185 ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), ..)
186 | ty::Foreign(def_id)
187 | ty::FnDef(def_id, ..)
188 | ty::Closure(def_id, ..)
189 | ty::CoroutineClosure(def_id, ..)
190 | ty::Coroutine(def_id, ..) => {
191 match ::rustc_ast_ir::visit::VisitorResult::branch(self.def_id_visitor.visit_def_id(def_id,
"type", &ty)) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(self.def_id_visitor.visit_def_id(def_id, "type", &ty));
192 if V::SHALLOW {
193 return V::Result::output();
194 }
195 if let ty::FnDef(..) = ty_kind {
199 match ::rustc_ast_ir::visit::VisitorResult::branch(tcx.fn_sig(def_id).instantiate_identity().visit_with(self))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(tcx.fn_sig(def_id).instantiate_identity().visit_with(self));
201 }
202 if let Some(assoc_item) = tcx.opt_associated_item(def_id)
207 && let Some(impl_def_id) = assoc_item.impl_container(tcx)
208 {
209 match ::rustc_ast_ir::visit::VisitorResult::branch(tcx.type_of(impl_def_id).instantiate_identity().visit_with(self))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(tcx.type_of(impl_def_id).instantiate_identity().visit_with(self));
210 }
211 }
212 ty::Alias(kind @ (ty::Inherent | ty::Free | ty::Projection), data) => {
213 if self.def_id_visitor.skip_assoc_tys() {
214 return V::Result::output();
220 }
221 if !self.visited_tys.insert(ty) {
222 return V::Result::output();
226 }
227
228 match ::rustc_ast_ir::visit::VisitorResult::branch(self.def_id_visitor.visit_def_id(data.def_id,
match kind {
ty::Inherent | ty::Projection => "associated type",
ty::Free => "type alias",
ty::Opaque =>
::core::panicking::panic("internal error: entered unreachable code"),
}, &LazyDefPathStr { def_id: data.def_id, tcx })) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(self.def_id_visitor.visit_def_id(
229 data.def_id,
230 match kind {
231 ty::Inherent | ty::Projection => "associated type",
232 ty::Free => "type alias",
233 ty::Opaque => unreachable!(),
234 },
235 &LazyDefPathStr { def_id: data.def_id, tcx },
236 ));
237
238 return if V::SHALLOW {
240 V::Result::output()
241 } else if kind == ty::Projection {
242 self.visit_projection_term(data.into())
243 } else {
244 V::Result::from_branch(
245 data.args.iter().try_for_each(|arg| arg.visit_with(self).branch()),
246 )
247 };
248 }
249 ty::Dynamic(predicates, ..) => {
250 for predicate in predicates {
253 let trait_ref = match predicate.skip_binder() {
254 ty::ExistentialPredicate::Trait(trait_ref) => trait_ref,
255 ty::ExistentialPredicate::Projection(proj) => proj.trait_ref(tcx),
256 ty::ExistentialPredicate::AutoTrait(def_id) => {
257 ty::ExistentialTraitRef::new(tcx, def_id, ty::GenericArgs::empty())
258 }
259 };
260 let ty::ExistentialTraitRef { def_id, .. } = trait_ref;
261 match ::rustc_ast_ir::visit::VisitorResult::branch(self.def_id_visitor.visit_def_id(def_id,
"trait", &trait_ref)) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref));
262 }
263 }
264 ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => {
265 if self.visited_tys.insert(ty) {
267 match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_clauses(tcx.explicit_item_bounds(def_id).skip_binder()))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(self.visit_clauses(tcx.explicit_item_bounds(def_id).skip_binder()));
275 }
276 }
277 ty::Bool
280 | ty::Char
281 | ty::Int(..)
282 | ty::Uint(..)
283 | ty::Float(..)
284 | ty::Str
285 | ty::Never
286 | ty::Array(..)
287 | ty::Slice(..)
288 | ty::Tuple(..)
289 | ty::RawPtr(..)
290 | ty::Ref(..)
291 | ty::Pat(..)
292 | ty::FnPtr(..)
293 | ty::UnsafeBinder(_)
294 | ty::Param(..)
295 | ty::Bound(..)
296 | ty::Error(_)
297 | ty::CoroutineWitness(..) => {}
298 ty::Placeholder(..) | ty::Infer(..) => {
299 ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected type: {0:?}", ty))bug!("unexpected type: {:?}", ty)
300 }
301 }
302
303 if V::SHALLOW { V::Result::output() } else { ty.super_visit_with(self) }
304 }
305
306 fn visit_const(&mut self, c: Const<'tcx>) -> Self::Result {
307 let tcx = self.def_id_visitor.tcx();
308 tcx.expand_abstract_consts(c).super_visit_with(self)
309 }
310}
311
312fn assoc_has_type_of(tcx: TyCtxt<'_>, item: &ty::AssocItem) -> bool {
313 if let ty::AssocKind::Type { data: ty::AssocTypeData::Normal(..) } = item.kind
314 && let hir::Node::TraitItem(item) =
315 tcx.hir_node(tcx.local_def_id_to_hir_id(item.def_id.expect_local()))
316 && let hir::TraitItemKind::Type(_, None) = item.kind
317 {
318 false
319 } else {
320 true
321 }
322}
323
324fn min(vis1: ty::Visibility, vis2: ty::Visibility, tcx: TyCtxt<'_>) -> ty::Visibility {
325 if vis1.is_at_least(vis2, tcx) { vis2 } else { vis1 }
326}
327
328struct FindMin<'a, 'tcx, VL: VisibilityLike, const SHALLOW: bool> {
330 tcx: TyCtxt<'tcx>,
331 effective_visibilities: &'a EffectiveVisibilities,
332 min: VL,
333}
334
335impl<'a, 'tcx, VL: VisibilityLike, const SHALLOW: bool> DefIdVisitor<'tcx>
336 for FindMin<'a, 'tcx, VL, SHALLOW>
337{
338 const SHALLOW: bool = SHALLOW;
339 fn skip_assoc_tys(&self) -> bool {
340 true
341 }
342 fn tcx(&self) -> TyCtxt<'tcx> {
343 self.tcx
344 }
345 fn visit_def_id(&mut self, def_id: DefId, _kind: &str, _descr: &dyn fmt::Display) {
346 if let Some(def_id) = def_id.as_local() {
347 self.min = VL::new_min(self, def_id);
348 }
349 }
350}
351
352trait VisibilityLike: Sized {
353 const MAX: Self;
354 fn new_min<const SHALLOW: bool>(
355 find: &FindMin<'_, '_, Self, SHALLOW>,
356 def_id: LocalDefId,
357 ) -> Self;
358
359 fn of_impl<const SHALLOW: bool>(
362 def_id: LocalDefId,
363 of_trait: bool,
364 tcx: TyCtxt<'_>,
365 effective_visibilities: &EffectiveVisibilities,
366 ) -> Self {
367 let mut find = FindMin::<_, SHALLOW> { tcx, effective_visibilities, min: Self::MAX };
368 find.visit(tcx.type_of(def_id).instantiate_identity());
369 if of_trait {
370 find.visit_trait(tcx.impl_trait_ref(def_id).instantiate_identity());
371 }
372 find.min
373 }
374}
375
376impl VisibilityLike for ty::Visibility {
377 const MAX: Self = ty::Visibility::Public;
378 fn new_min<const SHALLOW: bool>(
379 find: &FindMin<'_, '_, Self, SHALLOW>,
380 def_id: LocalDefId,
381 ) -> Self {
382 min(find.tcx.local_visibility(def_id), find.min, find.tcx)
383 }
384}
385
386impl VisibilityLike for EffectiveVisibility {
387 const MAX: Self = EffectiveVisibility::from_vis(ty::Visibility::Public);
388 fn new_min<const SHALLOW: bool>(
389 find: &FindMin<'_, '_, Self, SHALLOW>,
390 def_id: LocalDefId,
391 ) -> Self {
392 let effective_vis =
393 find.effective_visibilities.effective_vis(def_id).copied().unwrap_or_else(|| {
394 let private_vis = ty::Visibility::Restricted(
395 find.tcx.parent_module_from_def_id(def_id).to_local_def_id(),
396 );
397 EffectiveVisibility::from_vis(private_vis)
398 });
399
400 effective_vis.min(find.min, find.tcx)
401 }
402}
403
404struct EmbargoVisitor<'tcx> {
406 tcx: TyCtxt<'tcx>,
407
408 effective_visibilities: EffectiveVisibilities,
410 macro_reachable: FxHashSet<(LocalModDefId, LocalModDefId)>,
423 changed: bool,
425}
426
427struct ReachEverythingInTheInterfaceVisitor<'a, 'tcx> {
428 effective_vis: EffectiveVisibility,
429 item_def_id: LocalDefId,
430 ev: &'a mut EmbargoVisitor<'tcx>,
431 level: Level,
432}
433
434impl<'tcx> EmbargoVisitor<'tcx> {
435 fn get(&self, def_id: LocalDefId) -> Option<EffectiveVisibility> {
436 self.effective_visibilities.effective_vis(def_id).copied()
437 }
438
439 fn update(
441 &mut self,
442 def_id: LocalDefId,
443 inherited_effective_vis: EffectiveVisibility,
444 level: Level,
445 ) {
446 let nominal_vis = self.tcx.local_visibility(def_id);
447 self.update_eff_vis(def_id, inherited_effective_vis, Some(nominal_vis), level);
448 }
449
450 fn update_eff_vis(
451 &mut self,
452 def_id: LocalDefId,
453 inherited_effective_vis: EffectiveVisibility,
454 max_vis: Option<ty::Visibility>,
455 level: Level,
456 ) {
457 let private_vis =
459 ty::Visibility::Restricted(self.tcx.parent_module_from_def_id(def_id).into());
460 if max_vis != Some(private_vis) {
461 self.changed |= self.effective_visibilities.update(
462 def_id,
463 max_vis,
464 || private_vis,
465 inherited_effective_vis,
466 level,
467 self.tcx,
468 );
469 }
470 }
471
472 fn reach(
473 &mut self,
474 def_id: LocalDefId,
475 effective_vis: EffectiveVisibility,
476 ) -> ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
477 ReachEverythingInTheInterfaceVisitor {
478 effective_vis,
479 item_def_id: def_id,
480 ev: self,
481 level: Level::Reachable,
482 }
483 }
484
485 fn reach_through_impl_trait(
486 &mut self,
487 def_id: LocalDefId,
488 effective_vis: EffectiveVisibility,
489 ) -> ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
490 ReachEverythingInTheInterfaceVisitor {
491 effective_vis,
492 item_def_id: def_id,
493 ev: self,
494 level: Level::ReachableThroughImplTrait,
495 }
496 }
497
498 fn update_reachability_from_macro(
501 &mut self,
502 local_def_id: LocalDefId,
503 md: &MacroDef,
504 macro_ev: EffectiveVisibility,
505 ) {
506 let hir_id = self.tcx.local_def_id_to_hir_id(local_def_id);
508 let attrs = self.tcx.hir_attrs(hir_id);
509
510 if {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcMacroTransparency(x)) => {
break 'done Some(*x);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, RustcMacroTransparency(x) => *x)
511 .unwrap_or(Transparency::fallback(md.macro_rules))
512 != Transparency::Opaque
513 {
514 return;
515 }
516
517 let macro_module_def_id = self.tcx.local_parent(local_def_id);
518 if self.tcx.def_kind(macro_module_def_id) != DefKind::Mod {
519 return;
521 }
522 let macro_module_def_id = LocalModDefId::new_unchecked(macro_module_def_id);
524
525 if self.effective_visibilities.public_at_level(local_def_id).is_none() {
526 return;
527 }
528
529 let mut module_def_id = macro_module_def_id;
532 loop {
533 let changed_reachability =
534 self.update_macro_reachable(module_def_id, macro_module_def_id, macro_ev);
535 if changed_reachability || module_def_id == LocalModDefId::CRATE_DEF_ID {
536 break;
537 }
538 module_def_id = LocalModDefId::new_unchecked(self.tcx.local_parent(module_def_id));
539 }
540 }
541
542 fn update_macro_reachable(
545 &mut self,
546 module_def_id: LocalModDefId,
547 defining_mod: LocalModDefId,
548 macro_ev: EffectiveVisibility,
549 ) -> bool {
550 if self.macro_reachable.insert((module_def_id, defining_mod)) {
551 for child in self.tcx.module_children_local(module_def_id.to_local_def_id()) {
552 if let Res::Def(def_kind, def_id) = child.res
553 && let Some(def_id) = def_id.as_local()
554 && child.vis.is_accessible_from(defining_mod, self.tcx)
555 {
556 let vis = self.tcx.local_visibility(def_id);
557 self.update_macro_reachable_def(def_id, def_kind, vis, defining_mod, macro_ev);
558 }
559 }
560 true
561 } else {
562 false
563 }
564 }
565
566 fn update_macro_reachable_def(
567 &mut self,
568 def_id: LocalDefId,
569 def_kind: DefKind,
570 vis: ty::Visibility,
571 module: LocalModDefId,
572 macro_ev: EffectiveVisibility,
573 ) {
574 self.update(def_id, macro_ev, Level::Reachable);
575 match def_kind {
576 DefKind::Const { .. }
578 | DefKind::Static { .. }
579 | DefKind::TraitAlias
580 | DefKind::TyAlias => {
581 if vis.is_accessible_from(module, self.tcx) {
582 self.update(def_id, macro_ev, Level::Reachable);
583 }
584 }
585
586 DefKind::Macro(_) => {
591 let item = self.tcx.hir_expect_item(def_id);
592 if let hir::ItemKind::Macro(_, MacroDef { macro_rules: false, .. }, _) = item.kind {
593 if vis.is_accessible_from(module, self.tcx) {
594 self.update(def_id, macro_ev, Level::Reachable);
595 }
596 }
597 }
598
599 DefKind::Mod => {
604 if vis.is_accessible_from(module, self.tcx) {
605 self.update_macro_reachable(
606 LocalModDefId::new_unchecked(def_id),
607 module,
608 macro_ev,
609 );
610 }
611 }
612
613 DefKind::Struct | DefKind::Union => {
614 let struct_def = self.tcx.adt_def(def_id);
616 for field in &struct_def.non_enum_variant().fields {
617 let def_id = field.did.expect_local();
618 let field_vis = self.tcx.local_visibility(def_id);
619 if field_vis.is_accessible_from(module, self.tcx) {
620 self.reach(def_id, macro_ev).ty();
621 }
622 }
623 }
624
625 DefKind::AssocConst { .. }
628 | DefKind::AssocTy
629 | DefKind::ConstParam
630 | DefKind::Ctor(_, _)
631 | DefKind::Enum
632 | DefKind::ForeignTy
633 | DefKind::Fn
634 | DefKind::OpaqueTy
635 | DefKind::AssocFn
636 | DefKind::Trait
637 | DefKind::TyParam
638 | DefKind::Variant
639 | DefKind::LifetimeParam
640 | DefKind::ExternCrate
641 | DefKind::Use
642 | DefKind::ForeignMod
643 | DefKind::AnonConst
644 | DefKind::InlineConst
645 | DefKind::Field
646 | DefKind::GlobalAsm
647 | DefKind::Impl { .. }
648 | DefKind::Closure
649 | DefKind::SyntheticCoroutineBody => (),
650 }
651 }
652}
653
654impl<'tcx> EmbargoVisitor<'tcx> {
655 fn check_assoc_item(&mut self, item: &ty::AssocItem, item_ev: EffectiveVisibility) {
656 let def_id = item.def_id.expect_local();
657 let tcx = self.tcx;
658 let mut reach = self.reach(def_id, item_ev);
659 reach.generics().predicates();
660 if assoc_has_type_of(tcx, item) {
661 reach.ty();
662 }
663 if item.is_type() && item.container == AssocContainer::Trait {
664 reach.bounds();
665 }
666 }
667
668 fn check_def_id(&mut self, owner_id: OwnerId) {
669 let item_ev = self.get(owner_id.def_id);
672 match self.tcx.def_kind(owner_id) {
673 DefKind::Use | DefKind::ExternCrate | DefKind::GlobalAsm => {}
675 DefKind::Mod => {}
677 DefKind::Macro { .. } => {
678 if let Some(item_ev) = item_ev {
679 let (_, macro_def, _) =
680 self.tcx.hir_expect_item(owner_id.def_id).expect_macro();
681 self.update_reachability_from_macro(owner_id.def_id, macro_def, item_ev);
682 }
683 }
684 DefKind::ForeignTy
685 | DefKind::Const { .. }
686 | DefKind::Static { .. }
687 | DefKind::Fn
688 | DefKind::TyAlias => {
689 if let Some(item_ev) = item_ev {
690 self.reach(owner_id.def_id, item_ev).generics().predicates().ty();
691 }
692 }
693 DefKind::Trait => {
694 if let Some(item_ev) = item_ev {
695 self.reach(owner_id.def_id, item_ev).generics().predicates();
696
697 for assoc_item in self.tcx.associated_items(owner_id).in_definition_order() {
698 let def_id = assoc_item.def_id.expect_local();
699 self.update(def_id, item_ev, Level::Reachable);
700
701 self.check_assoc_item(assoc_item, item_ev);
702 }
703 }
704 }
705 DefKind::TraitAlias => {
706 if let Some(item_ev) = item_ev {
707 self.reach(owner_id.def_id, item_ev).generics().predicates();
708 }
709 }
710 DefKind::Impl { of_trait } => {
711 let item_ev = EffectiveVisibility::of_impl::<true>(
722 owner_id.def_id,
723 of_trait,
724 self.tcx,
725 &self.effective_visibilities,
726 );
727
728 self.update_eff_vis(owner_id.def_id, item_ev, None, Level::Direct);
729
730 {
731 let mut reach = self.reach(owner_id.def_id, item_ev);
732 reach.generics().predicates().ty();
733 if of_trait {
734 reach.trait_ref();
735 }
736 }
737
738 for assoc_item in self.tcx.associated_items(owner_id).in_definition_order() {
739 let def_id = assoc_item.def_id.expect_local();
740 let max_vis =
741 if of_trait { None } else { Some(self.tcx.local_visibility(def_id)) };
742 self.update_eff_vis(def_id, item_ev, max_vis, Level::Direct);
743
744 if let Some(impl_item_ev) = self.get(def_id) {
745 self.check_assoc_item(assoc_item, impl_item_ev);
746 }
747 }
748 }
749 DefKind::Enum => {
750 if let Some(item_ev) = item_ev {
751 self.reach(owner_id.def_id, item_ev).generics().predicates();
752 }
753 let def = self.tcx.adt_def(owner_id);
754 for variant in def.variants() {
755 if let Some(item_ev) = item_ev {
756 self.update(variant.def_id.expect_local(), item_ev, Level::Reachable);
757 }
758
759 if let Some(variant_ev) = self.get(variant.def_id.expect_local()) {
760 if let Some(ctor_def_id) = variant.ctor_def_id() {
761 self.update(ctor_def_id.expect_local(), variant_ev, Level::Reachable);
762 }
763
764 for field in &variant.fields {
765 let field = field.did.expect_local();
766 self.update(field, variant_ev, Level::Reachable);
767 self.reach(field, variant_ev).ty();
768 }
769 self.reach(owner_id.def_id, variant_ev).ty();
772 }
773 if let Some(ctor_def_id) = variant.ctor_def_id() {
774 if let Some(ctor_ev) = self.get(ctor_def_id.expect_local()) {
775 self.reach(owner_id.def_id, ctor_ev).ty();
776 }
777 }
778 }
779 }
780 DefKind::Struct | DefKind::Union => {
781 let def = self.tcx.adt_def(owner_id).non_enum_variant();
782 if let Some(item_ev) = item_ev {
783 self.reach(owner_id.def_id, item_ev).generics().predicates();
784 for field in &def.fields {
785 let field = field.did.expect_local();
786 self.update(field, item_ev, Level::Reachable);
787 if let Some(field_ev) = self.get(field) {
788 self.reach(field, field_ev).ty();
789 }
790 }
791 }
792 if let Some(ctor_def_id) = def.ctor_def_id() {
793 if let Some(item_ev) = item_ev {
794 self.update(ctor_def_id.expect_local(), item_ev, Level::Reachable);
795 }
796 if let Some(ctor_ev) = self.get(ctor_def_id.expect_local()) {
797 self.reach(owner_id.def_id, ctor_ev).ty();
798 }
799 }
800 }
801 DefKind::ForeignMod => {}
803 DefKind::Field
804 | DefKind::Variant
805 | DefKind::AssocFn
806 | DefKind::AssocTy
807 | DefKind::AssocConst { .. }
808 | DefKind::TyParam
809 | DefKind::AnonConst
810 | DefKind::InlineConst
811 | DefKind::OpaqueTy
812 | DefKind::Closure
813 | DefKind::SyntheticCoroutineBody
814 | DefKind::ConstParam
815 | DefKind::LifetimeParam
816 | DefKind::Ctor(..) => {
817 ::rustc_middle::util::bug::bug_fmt(format_args!("should be checked while checking parent"))bug!("should be checked while checking parent")
818 }
819 }
820 }
821}
822
823impl ReachEverythingInTheInterfaceVisitor<'_, '_> {
824 fn generics(&mut self) -> &mut Self {
825 for param in &self.ev.tcx.generics_of(self.item_def_id).own_params {
826 if let GenericParamDefKind::Const { .. } = param.kind {
827 self.visit(self.ev.tcx.type_of(param.def_id).instantiate_identity());
828 }
829 if let Some(default) = param.default_value(self.ev.tcx) {
830 self.visit(default.instantiate_identity());
831 }
832 }
833 self
834 }
835
836 fn predicates(&mut self) -> &mut Self {
837 self.visit_predicates(self.ev.tcx.explicit_predicates_of(self.item_def_id));
838 self
839 }
840
841 fn bounds(&mut self) -> &mut Self {
842 self.visit_clauses(self.ev.tcx.explicit_item_bounds(self.item_def_id).skip_binder());
843 self
844 }
845
846 fn ty(&mut self) -> &mut Self {
847 self.visit(self.ev.tcx.type_of(self.item_def_id).instantiate_identity());
848 self
849 }
850
851 fn trait_ref(&mut self) -> &mut Self {
852 self.visit_trait(self.ev.tcx.impl_trait_ref(self.item_def_id).instantiate_identity());
853 self
854 }
855}
856
857impl<'tcx> DefIdVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
858 fn tcx(&self) -> TyCtxt<'tcx> {
859 self.ev.tcx
860 }
861 fn visit_def_id(&mut self, def_id: DefId, _kind: &str, _descr: &dyn fmt::Display) {
862 if let Some(def_id) = def_id.as_local() {
863 let max_vis = (self.level != Level::ReachableThroughImplTrait)
867 .then(|| self.ev.tcx.local_visibility(def_id));
868 self.ev.update_eff_vis(def_id, self.effective_vis, max_vis, self.level);
869 }
870 }
871}
872
873pub struct TestReachabilityVisitor<'a, 'tcx> {
875 tcx: TyCtxt<'tcx>,
876 effective_visibilities: &'a EffectiveVisibilities,
877}
878
879impl<'a, 'tcx> TestReachabilityVisitor<'a, 'tcx> {
880 fn effective_visibility_diagnostic(&self, def_id: LocalDefId) {
881 if {
#[allow(deprecated)]
{
{
'done:
{
for i in self.tcx.get_all_attrs(def_id) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcEffectiveVisibility) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}
}.is_some()find_attr!(self.tcx, def_id, RustcEffectiveVisibility) {
882 let mut error_msg = String::new();
883 let span = self.tcx.def_span(def_id.to_def_id());
884 if let Some(effective_vis) = self.effective_visibilities.effective_vis(def_id) {
885 for level in Level::all_levels() {
886 let vis_str = effective_vis.at_level(level).to_string(def_id, self.tcx);
887 if level != Level::Direct {
888 error_msg.push_str(", ");
889 }
890 error_msg.push_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}: {1}", level, vis_str))
})format!("{level:?}: {vis_str}"));
891 }
892 } else {
893 error_msg.push_str("not in the table");
894 }
895 self.tcx.dcx().emit_err(ReportEffectiveVisibility { span, descr: error_msg });
896 }
897 }
898}
899
900impl<'a, 'tcx> TestReachabilityVisitor<'a, 'tcx> {
901 fn check_def_id(&self, owner_id: OwnerId) {
902 self.effective_visibility_diagnostic(owner_id.def_id);
903
904 match self.tcx.def_kind(owner_id) {
905 DefKind::Enum => {
906 let def = self.tcx.adt_def(owner_id.def_id);
907 for variant in def.variants() {
908 self.effective_visibility_diagnostic(variant.def_id.expect_local());
909 if let Some(ctor_def_id) = variant.ctor_def_id() {
910 self.effective_visibility_diagnostic(ctor_def_id.expect_local());
911 }
912 for field in &variant.fields {
913 self.effective_visibility_diagnostic(field.did.expect_local());
914 }
915 }
916 }
917 DefKind::Struct | DefKind::Union => {
918 let def = self.tcx.adt_def(owner_id.def_id).non_enum_variant();
919 if let Some(ctor_def_id) = def.ctor_def_id() {
920 self.effective_visibility_diagnostic(ctor_def_id.expect_local());
921 }
922 for field in &def.fields {
923 self.effective_visibility_diagnostic(field.did.expect_local());
924 }
925 }
926 _ => {}
927 }
928 }
929}
930
931struct NamePrivacyVisitor<'tcx> {
937 tcx: TyCtxt<'tcx>,
938 maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
939}
940
941impl<'tcx> NamePrivacyVisitor<'tcx> {
942 #[track_caller]
946 fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
947 self.maybe_typeck_results
948 .expect("`NamePrivacyVisitor::typeck_results` called outside of body")
949 }
950
951 fn check_field(
953 &self,
954 hir_id: hir::HirId, use_ctxt: Span, def: ty::AdtDef<'tcx>, field: &'tcx ty::FieldDef,
958 ) -> bool {
959 if def.is_enum() {
960 return true;
961 }
962
963 let ident = Ident::new(sym::dummy, use_ctxt);
965 let (_, def_id) = self.tcx.adjust_ident_and_get_scope(ident, def.did(), hir_id);
966 !field.vis.is_accessible_from(def_id, self.tcx)
967 }
968
969 fn emit_unreachable_field_error(
971 &self,
972 fields: Vec<(Symbol, Span, bool )>,
973 def: ty::AdtDef<'tcx>, update_syntax: Option<Span>,
975 struct_span: Span,
976 ) {
977 if def.is_enum() || fields.is_empty() {
978 return;
979 }
980
981 let Some(field_names) = listify(&fields[..], |(n, _, _)| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", n))
})format!("`{n}`")) else { return };
993 let span: MultiSpan = fields.iter().map(|(_, span, _)| *span).collect::<Vec<Span>>().into();
994
995 let rest_field_names: Vec<_> =
997 fields.iter().filter(|(_, _, is_present)| !is_present).map(|(n, _, _)| n).collect();
998 let rest_len = rest_field_names.len();
999 let rest_field_names =
1000 listify(&rest_field_names[..], |n| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", n))
})format!("`{n}`")).unwrap_or_default();
1001 let labels = fields
1003 .iter()
1004 .filter(|(_, _, is_present)| *is_present)
1005 .map(|(_, span, _)| FieldIsPrivateLabel::Other { span: *span })
1006 .chain(update_syntax.iter().map(|span| FieldIsPrivateLabel::IsUpdateSyntax {
1007 span: *span,
1008 rest_field_names: rest_field_names.clone(),
1009 rest_len,
1010 }))
1011 .collect();
1012
1013 self.tcx.dcx().emit_err(FieldIsPrivate {
1014 span,
1015 struct_span: if self
1016 .tcx
1017 .sess
1018 .source_map()
1019 .is_multiline(fields[0].1.between(struct_span))
1020 {
1021 Some(struct_span)
1022 } else {
1023 None
1024 },
1025 field_names,
1026 variant_descr: def.variant_descr(),
1027 def_path_str: self.tcx.def_path_str(def.did()),
1028 labels,
1029 len: fields.len(),
1030 });
1031 }
1032
1033 fn check_expanded_fields(
1034 &self,
1035 adt: ty::AdtDef<'tcx>,
1036 variant: &'tcx ty::VariantDef,
1037 fields: &[hir::ExprField<'tcx>],
1038 hir_id: hir::HirId,
1039 span: Span,
1040 struct_span: Span,
1041 ) {
1042 let mut failed_fields = ::alloc::vec::Vec::new()vec![];
1043 for (vf_index, variant_field) in variant.fields.iter_enumerated() {
1044 let field =
1045 fields.iter().find(|f| self.typeck_results().field_index(f.hir_id) == vf_index);
1046 let (hir_id, use_ctxt, span) = match field {
1047 Some(field) => (field.hir_id, field.ident.span, field.span),
1048 None => (hir_id, span, span),
1049 };
1050 if self.check_field(hir_id, use_ctxt, adt, variant_field) {
1051 let name = match field {
1052 Some(field) => field.ident.name,
1053 None => variant_field.name,
1054 };
1055 failed_fields.push((name, span, field.is_some()));
1056 }
1057 }
1058 self.emit_unreachable_field_error(failed_fields, adt, Some(span), struct_span);
1059 }
1060}
1061
1062impl<'tcx> Visitor<'tcx> for NamePrivacyVisitor<'tcx> {
1063 fn visit_nested_body(&mut self, body_id: hir::BodyId) {
1064 let new_typeck_results = self.tcx.typeck_body(body_id);
1065 if new_typeck_results.tainted_by_errors.is_some() {
1067 return;
1068 }
1069 let old_maybe_typeck_results = self.maybe_typeck_results.replace(new_typeck_results);
1070 self.visit_body(self.tcx.hir_body(body_id));
1071 self.maybe_typeck_results = old_maybe_typeck_results;
1072 }
1073
1074 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1075 if let hir::ExprKind::Struct(qpath, fields, ref base) = expr.kind {
1076 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
1077 let adt = self.typeck_results().expr_ty(expr).ty_adt_def().unwrap();
1078 let variant = adt.variant_of_res(res);
1079 match *base {
1080 hir::StructTailExpr::Base(base) => {
1081 self.check_expanded_fields(
1085 adt,
1086 variant,
1087 fields,
1088 base.hir_id,
1089 base.span,
1090 qpath.span(),
1091 );
1092 }
1093 hir::StructTailExpr::DefaultFields(span) => {
1094 self.check_expanded_fields(
1095 adt,
1096 variant,
1097 fields,
1098 expr.hir_id,
1099 span,
1100 qpath.span(),
1101 );
1102 }
1103 hir::StructTailExpr::None | hir::StructTailExpr::NoneWithError(_) => {
1104 let mut failed_fields = ::alloc::vec::Vec::new()vec![];
1105 for field in fields {
1106 let (hir_id, use_ctxt) = (field.hir_id, field.ident.span);
1107 let index = self.typeck_results().field_index(field.hir_id);
1108 if self.check_field(hir_id, use_ctxt, adt, &variant.fields[index]) {
1109 failed_fields.push((field.ident.name, field.ident.span, true));
1110 }
1111 }
1112 self.emit_unreachable_field_error(failed_fields, adt, None, qpath.span());
1113 }
1114 }
1115 }
1116
1117 intravisit::walk_expr(self, expr);
1118 }
1119
1120 fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
1121 if let PatKind::Struct(ref qpath, fields, _) = pat.kind {
1122 let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
1123 let adt = self.typeck_results().pat_ty(pat).ty_adt_def().unwrap();
1124 let variant = adt.variant_of_res(res);
1125 let mut failed_fields = ::alloc::vec::Vec::new()vec![];
1126 for field in fields {
1127 let (hir_id, use_ctxt) = (field.hir_id, field.ident.span);
1128 let index = self.typeck_results().field_index(field.hir_id);
1129 if self.check_field(hir_id, use_ctxt, adt, &variant.fields[index]) {
1130 failed_fields.push((field.ident.name, field.ident.span, true));
1131 }
1132 }
1133 self.emit_unreachable_field_error(failed_fields, adt, None, qpath.span());
1134 }
1135
1136 intravisit::walk_pat(self, pat);
1137 }
1138}
1139
1140struct TypePrivacyVisitor<'tcx> {
1145 tcx: TyCtxt<'tcx>,
1146 module_def_id: LocalModDefId,
1147 maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
1148 span: Span,
1149}
1150
1151impl<'tcx> TypePrivacyVisitor<'tcx> {
1152 fn item_is_accessible(&self, did: DefId) -> bool {
1153 self.tcx.visibility(did).is_accessible_from(self.module_def_id, self.tcx)
1154 }
1155
1156 fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
1158 self.span = span;
1159 let typeck_results = self
1160 .maybe_typeck_results
1161 .unwrap_or_else(|| ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("`hir::Expr` or `hir::Pat` outside of a body"))span_bug!(span, "`hir::Expr` or `hir::Pat` outside of a body"));
1162 try {
1163 self.visit(typeck_results.node_type(id))?;
1164 self.visit(typeck_results.node_args(id))?;
1165 if let Some(adjustments) = typeck_results.adjustments().get(id) {
1166 adjustments.iter().try_for_each(|adjustment| self.visit(adjustment.target))?;
1167 }
1168 }
1169 .is_break()
1170 }
1171
1172 fn check_def_id(&self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1173 let is_error = !self.item_is_accessible(def_id);
1174 if is_error {
1175 self.tcx.dcx().emit_err(ItemIsPrivate { span: self.span, kind, descr: descr.into() });
1176 }
1177 is_error
1178 }
1179}
1180
1181impl<'tcx> rustc_ty_utils::sig_types::SpannedTypeVisitor<'tcx> for TypePrivacyVisitor<'tcx> {
1182 type Result = ControlFlow<()>;
1183 fn visit(&mut self, span: Span, value: impl TypeVisitable<TyCtxt<'tcx>>) -> Self::Result {
1184 self.span = span;
1185 value.visit_with(&mut self.skeleton())
1186 }
1187}
1188
1189impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> {
1190 fn visit_nested_body(&mut self, body_id: hir::BodyId) {
1191 let old_maybe_typeck_results =
1192 self.maybe_typeck_results.replace(self.tcx.typeck_body(body_id));
1193 self.visit_body(self.tcx.hir_body(body_id));
1194 self.maybe_typeck_results = old_maybe_typeck_results;
1195 }
1196
1197 fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx, AmbigArg>) {
1198 self.span = hir_ty.span;
1199 if self
1200 .visit(
1201 self.maybe_typeck_results
1202 .unwrap_or_else(|| ::rustc_middle::util::bug::span_bug_fmt(hir_ty.span,
format_args!("`hir::Ty` outside of a body"))span_bug!(hir_ty.span, "`hir::Ty` outside of a body"))
1203 .node_type(hir_ty.hir_id),
1204 )
1205 .is_break()
1206 {
1207 return;
1208 }
1209
1210 intravisit::walk_ty(self, hir_ty);
1211 }
1212
1213 fn visit_infer(
1214 &mut self,
1215 inf_id: rustc_hir::HirId,
1216 inf_span: Span,
1217 _kind: InferKind<'tcx>,
1218 ) -> Self::Result {
1219 self.span = inf_span;
1220 if let Some(ty) = self
1221 .maybe_typeck_results
1222 .unwrap_or_else(|| ::rustc_middle::util::bug::span_bug_fmt(inf_span,
format_args!("Inference variable outside of a body"))span_bug!(inf_span, "Inference variable outside of a body"))
1223 .node_type_opt(inf_id)
1224 {
1225 if self.visit(ty).is_break() {
1226 return;
1227 }
1228 } else {
1229 }
1231
1232 self.visit_id(inf_id)
1233 }
1234
1235 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1237 if self.check_expr_pat_type(expr.hir_id, expr.span) {
1238 return;
1240 }
1241 match expr.kind {
1242 hir::ExprKind::Assign(_, rhs, _) | hir::ExprKind::Match(rhs, ..) => {
1243 if self.check_expr_pat_type(rhs.hir_id, rhs.span) {
1245 return;
1246 }
1247 }
1248 hir::ExprKind::MethodCall(segment, ..) => {
1249 self.span = segment.ident.span;
1251 let typeck_results = self
1252 .maybe_typeck_results
1253 .unwrap_or_else(|| ::rustc_middle::util::bug::span_bug_fmt(self.span,
format_args!("`hir::Expr` outside of a body"))span_bug!(self.span, "`hir::Expr` outside of a body"));
1254 if let Some(def_id) = typeck_results.type_dependent_def_id(expr.hir_id) {
1255 if self.visit(self.tcx.type_of(def_id).instantiate_identity()).is_break() {
1256 return;
1257 }
1258 } else {
1259 self.tcx
1260 .dcx()
1261 .span_delayed_bug(expr.span, "no type-dependent def for method call");
1262 }
1263 }
1264 _ => {}
1265 }
1266
1267 intravisit::walk_expr(self, expr);
1268 }
1269
1270 fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: hir::HirId, span: Span) {
1277 let def = match qpath {
1278 hir::QPath::Resolved(_, path) => match path.res {
1279 Res::Def(kind, def_id) => Some((kind, def_id)),
1280 _ => None,
1281 },
1282 hir::QPath::TypeRelative(..) => {
1283 match self.maybe_typeck_results {
1284 Some(typeck_results) => typeck_results.type_dependent_def(id),
1285 None => None,
1287 }
1288 }
1289 };
1290 let def = def.filter(|(kind, _)| {
1291 #[allow(non_exhaustive_omitted_patterns)] match kind {
DefKind::AssocFn | DefKind::AssocConst { .. } | DefKind::AssocTy |
DefKind::Static { .. } => true,
_ => false,
}matches!(
1292 kind,
1293 DefKind::AssocFn
1294 | DefKind::AssocConst { .. }
1295 | DefKind::AssocTy
1296 | DefKind::Static { .. }
1297 )
1298 });
1299 if let Some((kind, def_id)) = def {
1300 let is_local_static =
1301 if let DefKind::Static { .. } = kind { def_id.is_local() } else { false };
1302 if !self.item_is_accessible(def_id) && !is_local_static {
1303 let name = match *qpath {
1304 hir::QPath::Resolved(_, path) => Some(self.tcx.def_path_str(path.res.def_id())),
1305 hir::QPath::TypeRelative(_, segment) => Some(segment.ident.to_string()),
1306 };
1307 let kind = self.tcx.def_descr(def_id);
1308 let sess = self.tcx.sess;
1309 let _ = match name {
1310 Some(name) => {
1311 sess.dcx().emit_err(ItemIsPrivate { span, kind, descr: (&name).into() })
1312 }
1313 None => sess.dcx().emit_err(UnnamedItemIsPrivate { span, kind }),
1314 };
1315 return;
1316 }
1317 }
1318
1319 intravisit::walk_qpath(self, qpath, id);
1320 }
1321
1322 fn visit_pat(&mut self, pattern: &'tcx hir::Pat<'tcx>) {
1324 if self.check_expr_pat_type(pattern.hir_id, pattern.span) {
1325 return;
1327 }
1328
1329 intravisit::walk_pat(self, pattern);
1330 }
1331
1332 fn visit_local(&mut self, local: &'tcx hir::LetStmt<'tcx>) {
1333 if let Some(init) = local.init {
1334 if self.check_expr_pat_type(init.hir_id, init.span) {
1335 return;
1337 }
1338 }
1339
1340 intravisit::walk_local(self, local);
1341 }
1342}
1343
1344impl<'tcx> DefIdVisitor<'tcx> for TypePrivacyVisitor<'tcx> {
1345 type Result = ControlFlow<()>;
1346 fn tcx(&self) -> TyCtxt<'tcx> {
1347 self.tcx
1348 }
1349 fn visit_def_id(
1350 &mut self,
1351 def_id: DefId,
1352 kind: &str,
1353 descr: &dyn fmt::Display,
1354 ) -> Self::Result {
1355 if self.check_def_id(def_id, kind, descr) {
1356 ControlFlow::Break(())
1357 } else {
1358 ControlFlow::Continue(())
1359 }
1360 }
1361}
1362
1363struct SearchInterfaceForPrivateItemsVisitor<'tcx> {
1369 tcx: TyCtxt<'tcx>,
1370 item_def_id: LocalDefId,
1371 required_visibility: ty::Visibility,
1373 required_effective_vis: Option<EffectiveVisibility>,
1374 hard_error: bool = false,
1375 in_primary_interface: bool = true,
1376 skip_assoc_tys: bool = false,
1377}
1378
1379impl SearchInterfaceForPrivateItemsVisitor<'_> {
1380 fn generics(&mut self) -> &mut Self {
1381 self.in_primary_interface = true;
1382 for param in &self.tcx.generics_of(self.item_def_id).own_params {
1383 if let GenericParamDefKind::Const { .. } = param.kind {
1384 let _ = self.visit(self.tcx.type_of(param.def_id).instantiate_identity());
1385 }
1386 if let Some(default) = param.default_value(self.tcx) {
1387 let _ = self.visit(default.instantiate_identity());
1388 }
1389 }
1390 self
1391 }
1392
1393 fn predicates(&mut self) -> &mut Self {
1394 self.in_primary_interface = false;
1395 let _ = self.visit_predicates(self.tcx.explicit_predicates_of(self.item_def_id));
1402 self
1403 }
1404
1405 fn bounds(&mut self) -> &mut Self {
1406 self.in_primary_interface = false;
1407 let _ = self.visit_clauses(self.tcx.explicit_item_bounds(self.item_def_id).skip_binder());
1408 self
1409 }
1410
1411 fn ty(&mut self) -> &mut Self {
1412 self.in_primary_interface = true;
1413 let _ = self.visit(self.tcx.type_of(self.item_def_id).instantiate_identity());
1414 self
1415 }
1416
1417 fn trait_ref(&mut self) -> &mut Self {
1418 self.in_primary_interface = true;
1419 let _ = self.visit_trait(self.tcx.impl_trait_ref(self.item_def_id).instantiate_identity());
1420 self
1421 }
1422
1423 fn check_def_id(&self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1424 if self.leaks_private_dep(def_id) {
1425 self.tcx.emit_node_span_lint(
1426 lint::builtin::EXPORTED_PRIVATE_DEPENDENCIES,
1427 self.tcx.local_def_id_to_hir_id(self.item_def_id),
1428 self.tcx.def_span(self.item_def_id.to_def_id()),
1429 FromPrivateDependencyInPublicInterface {
1430 kind,
1431 descr: descr.into(),
1432 krate: self.tcx.crate_name(def_id.krate),
1433 },
1434 );
1435 }
1436
1437 let Some(local_def_id) = def_id.as_local() else {
1438 return false;
1439 };
1440
1441 let vis = self.tcx.local_visibility(local_def_id);
1442 if self.hard_error && !vis.is_at_least(self.required_visibility, self.tcx) {
1443 let vis_descr = match vis {
1444 ty::Visibility::Public => "public",
1445 ty::Visibility::Restricted(vis_def_id) => {
1446 if vis_def_id
1447 == self.tcx.parent_module_from_def_id(local_def_id).to_local_def_id()
1448 {
1449 "private"
1450 } else if vis_def_id.is_top_level_module() {
1451 "crate-private"
1452 } else {
1453 "restricted"
1454 }
1455 }
1456 };
1457
1458 let span = self.tcx.def_span(self.item_def_id.to_def_id());
1459 let vis_span = self.tcx.def_span(def_id);
1460 self.tcx.dcx().emit_err(InPublicInterface {
1461 span,
1462 vis_descr,
1463 kind,
1464 descr: descr.into(),
1465 vis_span,
1466 });
1467 return false;
1468 }
1469
1470 let Some(effective_vis) = self.required_effective_vis else {
1471 return false;
1472 };
1473
1474 let reachable_at_vis = *effective_vis.at_level(Level::Reachable);
1475
1476 if !vis.is_at_least(reachable_at_vis, self.tcx) {
1477 let lint = if self.in_primary_interface {
1478 lint::builtin::PRIVATE_INTERFACES
1479 } else {
1480 lint::builtin::PRIVATE_BOUNDS
1481 };
1482 let span = self.tcx.def_span(self.item_def_id.to_def_id());
1483 let vis_span = self.tcx.def_span(def_id);
1484 self.tcx.emit_node_span_lint(
1485 lint,
1486 self.tcx.local_def_id_to_hir_id(self.item_def_id),
1487 span,
1488 PrivateInterfacesOrBoundsLint {
1489 item_span: span,
1490 item_kind: self.tcx.def_descr(self.item_def_id.to_def_id()),
1491 item_descr: (&LazyDefPathStr {
1492 def_id: self.item_def_id.to_def_id(),
1493 tcx: self.tcx,
1494 })
1495 .into(),
1496 item_vis_descr: &reachable_at_vis.to_string(self.item_def_id, self.tcx),
1497 ty_span: vis_span,
1498 ty_kind: kind,
1499 ty_descr: descr.into(),
1500 ty_vis_descr: &vis.to_string(local_def_id, self.tcx),
1501 },
1502 );
1503 }
1504
1505 false
1506 }
1507
1508 fn leaks_private_dep(&self, item_id: DefId) -> bool {
1513 let ret = self.required_visibility.is_public() && self.tcx.is_private_dep(item_id.krate);
1514
1515 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_privacy/src/lib.rs:1515",
"rustc_privacy", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_privacy/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1515u32),
::tracing_core::__macro_support::Option::Some("rustc_privacy"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("leaks_private_dep(item_id={0:?})={1}",
item_id, ret) as &dyn Value))])
});
} else { ; }
};debug!("leaks_private_dep(item_id={:?})={}", item_id, ret);
1516 ret
1517 }
1518}
1519
1520impl<'tcx> DefIdVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'tcx> {
1521 type Result = ControlFlow<()>;
1522 fn skip_assoc_tys(&self) -> bool {
1523 self.skip_assoc_tys
1524 }
1525 fn tcx(&self) -> TyCtxt<'tcx> {
1526 self.tcx
1527 }
1528 fn visit_def_id(
1529 &mut self,
1530 def_id: DefId,
1531 kind: &str,
1532 descr: &dyn fmt::Display,
1533 ) -> Self::Result {
1534 if self.check_def_id(def_id, kind, descr) {
1535 ControlFlow::Break(())
1536 } else {
1537 ControlFlow::Continue(())
1538 }
1539 }
1540}
1541
1542struct PrivateItemsInPublicInterfacesChecker<'a, 'tcx> {
1543 tcx: TyCtxt<'tcx>,
1544 effective_visibilities: &'a EffectiveVisibilities,
1545}
1546
1547impl<'tcx> PrivateItemsInPublicInterfacesChecker<'_, 'tcx> {
1548 fn check(
1549 &self,
1550 def_id: LocalDefId,
1551 required_visibility: ty::Visibility,
1552 required_effective_vis: Option<EffectiveVisibility>,
1553 ) -> SearchInterfaceForPrivateItemsVisitor<'tcx> {
1554 SearchInterfaceForPrivateItemsVisitor {
1555 tcx: self.tcx,
1556 item_def_id: def_id,
1557 required_visibility,
1558 required_effective_vis,
1559 ..
1560 }
1561 }
1562
1563 fn check_unnameable(&self, def_id: LocalDefId, effective_vis: Option<EffectiveVisibility>) {
1564 let Some(effective_vis) = effective_vis else {
1565 return;
1566 };
1567
1568 let reexported_at_vis = effective_vis.at_level(Level::Reexported);
1569 let reachable_at_vis = effective_vis.at_level(Level::Reachable);
1570
1571 if reachable_at_vis.is_public() && reexported_at_vis != reachable_at_vis {
1572 let hir_id = self.tcx.local_def_id_to_hir_id(def_id);
1573 let span = self.tcx.def_span(def_id.to_def_id());
1574 self.tcx.emit_node_span_lint(
1575 lint::builtin::UNNAMEABLE_TYPES,
1576 hir_id,
1577 span,
1578 UnnameableTypesLint {
1579 span,
1580 kind: self.tcx.def_descr(def_id.to_def_id()),
1581 descr: (&LazyDefPathStr { def_id: def_id.to_def_id(), tcx: self.tcx }).into(),
1582 reachable_vis: &reachable_at_vis.to_string(def_id, self.tcx),
1583 reexported_vis: &reexported_at_vis.to_string(def_id, self.tcx),
1584 },
1585 );
1586 }
1587 }
1588
1589 fn check_assoc_item(
1590 &self,
1591 item: &ty::AssocItem,
1592 vis: ty::Visibility,
1593 effective_vis: Option<EffectiveVisibility>,
1594 ) {
1595 let mut check = self.check(item.def_id.expect_local(), vis, effective_vis);
1596
1597 let is_assoc_ty = item.is_type();
1598 check.hard_error = is_assoc_ty && !item.is_impl_trait_in_trait();
1599 check.generics().predicates();
1600 if assoc_has_type_of(self.tcx, item) {
1601 check.hard_error = check.hard_error && item.defaultness(self.tcx).has_value();
1602 check.ty();
1603 }
1604 if is_assoc_ty && item.container == AssocContainer::Trait {
1605 check.hard_error = false;
1606 check.bounds();
1607 }
1608 }
1609
1610 fn get(&self, def_id: LocalDefId) -> Option<EffectiveVisibility> {
1611 self.effective_visibilities.effective_vis(def_id).copied()
1612 }
1613
1614 fn check_item(&self, id: ItemId) {
1615 let tcx = self.tcx;
1616 let def_id = id.owner_id.def_id;
1617 let item_visibility = tcx.local_visibility(def_id);
1618 let effective_vis = self.get(def_id);
1619 let def_kind = tcx.def_kind(def_id);
1620
1621 match def_kind {
1622 DefKind::Const { .. } | DefKind::Static { .. } | DefKind::Fn | DefKind::TyAlias => {
1623 if let DefKind::TyAlias = def_kind {
1624 self.check_unnameable(def_id, effective_vis);
1625 }
1626 self.check(def_id, item_visibility, effective_vis).generics().predicates().ty();
1627 }
1628 DefKind::OpaqueTy => {
1629 self.check(def_id, item_visibility, effective_vis).generics().bounds();
1632 }
1633 DefKind::Trait => {
1634 self.check_unnameable(def_id, effective_vis);
1635
1636 self.check(def_id, item_visibility, effective_vis).generics().predicates();
1637
1638 for assoc_item in tcx.associated_items(id.owner_id).in_definition_order() {
1639 self.check_assoc_item(assoc_item, item_visibility, effective_vis);
1640 }
1641 }
1642 DefKind::TraitAlias => {
1643 self.check(def_id, item_visibility, effective_vis).generics().predicates();
1644 }
1645 DefKind::Enum => {
1646 self.check_unnameable(def_id, effective_vis);
1647 self.check(def_id, item_visibility, effective_vis).generics().predicates();
1648
1649 let adt = tcx.adt_def(id.owner_id);
1650 for field in adt.all_fields() {
1651 self.check(field.did.expect_local(), item_visibility, effective_vis).ty();
1652 }
1653 }
1654 DefKind::Struct | DefKind::Union => {
1656 self.check_unnameable(def_id, effective_vis);
1657 self.check(def_id, item_visibility, effective_vis).generics().predicates();
1658
1659 let adt = tcx.adt_def(id.owner_id);
1660 for field in adt.all_fields() {
1661 let visibility = min(item_visibility, field.vis.expect_local(), tcx);
1662 let field_ev = self.get(field.did.expect_local());
1663
1664 self.check(field.did.expect_local(), visibility, field_ev).ty();
1665 }
1666 }
1667 DefKind::ForeignMod => {}
1669 DefKind::Impl { of_trait } => {
1674 let impl_vis =
1675 ty::Visibility::of_impl::<false>(def_id, of_trait, tcx, &Default::default());
1676
1677 let impl_ev = EffectiveVisibility::of_impl::<false>(
1689 def_id,
1690 of_trait,
1691 tcx,
1692 self.effective_visibilities,
1693 );
1694
1695 let mut check = self.check(def_id, impl_vis, Some(impl_ev));
1696
1697 if !of_trait {
1700 check.generics().predicates();
1701 }
1702
1703 check.skip_assoc_tys = true;
1707 check.ty();
1708 if of_trait {
1709 check.trait_ref();
1710 }
1711
1712 for assoc_item in tcx.associated_items(id.owner_id).in_definition_order() {
1713 let impl_item_vis = if !of_trait {
1714 min(tcx.local_visibility(assoc_item.def_id.expect_local()), impl_vis, tcx)
1715 } else {
1716 impl_vis
1717 };
1718
1719 let impl_item_ev = if !of_trait {
1720 self.get(assoc_item.def_id.expect_local())
1721 .map(|ev| ev.min(impl_ev, self.tcx))
1722 } else {
1723 Some(impl_ev)
1724 };
1725
1726 self.check_assoc_item(assoc_item, impl_item_vis, impl_item_ev);
1727 }
1728 }
1729 _ => {}
1730 }
1731 }
1732
1733 fn check_foreign_item(&self, id: ForeignItemId) {
1734 let tcx = self.tcx;
1735 let def_id = id.owner_id.def_id;
1736 let item_visibility = tcx.local_visibility(def_id);
1737 let effective_vis = self.get(def_id);
1738
1739 if let DefKind::ForeignTy = self.tcx.def_kind(def_id) {
1740 self.check_unnameable(def_id, effective_vis);
1741 }
1742
1743 self.check(def_id, item_visibility, effective_vis).generics().predicates().ty();
1744 }
1745}
1746
1747pub fn provide(providers: &mut Providers) {
1748 *providers = Providers {
1749 effective_visibilities,
1750 check_private_in_public,
1751 check_mod_privacy,
1752 ..*providers
1753 };
1754}
1755
1756fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
1757 let mut visitor = NamePrivacyVisitor { tcx, maybe_typeck_results: None };
1759 tcx.hir_visit_item_likes_in_module(module_def_id, &mut visitor);
1760
1761 let span = tcx.def_span(module_def_id);
1764 let mut visitor = TypePrivacyVisitor { tcx, module_def_id, maybe_typeck_results: None, span };
1765
1766 let module = tcx.hir_module_items(module_def_id);
1767 for def_id in module.definitions() {
1768 let _ = rustc_ty_utils::sig_types::walk_types(tcx, def_id, &mut visitor);
1769
1770 if let Some(body_id) = tcx.hir_maybe_body_owned_by(def_id) {
1771 visitor.visit_nested_body(body_id.id());
1772 }
1773
1774 if let DefKind::Impl { of_trait: true } = tcx.def_kind(def_id) {
1775 let trait_ref = tcx.impl_trait_ref(def_id);
1776 let trait_ref = trait_ref.instantiate_identity();
1777 visitor.span =
1778 tcx.hir_expect_item(def_id).expect_impl().of_trait.unwrap().trait_ref.path.span;
1779 let _ =
1780 visitor.visit_def_id(trait_ref.def_id, "trait", &trait_ref.print_only_trait_path());
1781 }
1782 }
1783}
1784
1785fn effective_visibilities(tcx: TyCtxt<'_>, (): ()) -> &EffectiveVisibilities {
1786 let mut visitor = EmbargoVisitor {
1789 tcx,
1790 effective_visibilities: tcx.resolutions(()).effective_visibilities.clone(),
1791 macro_reachable: Default::default(),
1792 changed: false,
1793 };
1794
1795 visitor.effective_visibilities.check_invariants(tcx);
1796
1797 let impl_trait_pass = !tcx.sess.opts.actually_rustdoc;
1801 if impl_trait_pass {
1802 let krate = tcx.hir_crate_items(());
1805 for id in krate.opaques() {
1806 let opaque = tcx.hir_node_by_def_id(id).expect_opaque_ty();
1807 let should_visit = match opaque.origin {
1808 hir::OpaqueTyOrigin::FnReturn {
1809 parent,
1810 in_trait_or_impl: Some(hir::RpitContext::Trait),
1811 }
1812 | hir::OpaqueTyOrigin::AsyncFn {
1813 parent,
1814 in_trait_or_impl: Some(hir::RpitContext::Trait),
1815 } => match tcx.hir_node_by_def_id(parent).expect_trait_item().expect_fn().1 {
1816 hir::TraitFn::Required(_) => false,
1817 hir::TraitFn::Provided(..) => true,
1818 },
1819
1820 hir::OpaqueTyOrigin::FnReturn {
1823 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
1824 ..
1825 }
1826 | hir::OpaqueTyOrigin::AsyncFn {
1827 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
1828 ..
1829 }
1830 | hir::OpaqueTyOrigin::TyAlias { .. } => true,
1831 };
1832 if should_visit {
1833 let pub_ev = EffectiveVisibility::from_vis(ty::Visibility::Public);
1837 visitor
1838 .reach_through_impl_trait(opaque.def_id, pub_ev)
1839 .generics()
1840 .predicates()
1841 .ty();
1842 }
1843 }
1844
1845 visitor.changed = false;
1846 }
1847
1848 let crate_items = tcx.hir_crate_items(());
1849 loop {
1850 for id in crate_items.free_items() {
1851 visitor.check_def_id(id.owner_id);
1852 }
1853 for id in crate_items.foreign_items() {
1854 visitor.check_def_id(id.owner_id);
1855 }
1856 if visitor.changed {
1857 visitor.changed = false;
1858 } else {
1859 break;
1860 }
1861 }
1862 visitor.effective_visibilities.check_invariants(tcx);
1863
1864 let check_visitor =
1865 TestReachabilityVisitor { tcx, effective_visibilities: &visitor.effective_visibilities };
1866 for id in crate_items.owners() {
1867 check_visitor.check_def_id(id);
1868 }
1869
1870 tcx.arena.alloc(visitor.effective_visibilities)
1871}
1872
1873fn check_private_in_public(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
1874 let effective_visibilities = tcx.effective_visibilities(());
1875 let checker = PrivateItemsInPublicInterfacesChecker { tcx, effective_visibilities };
1877
1878 let crate_items = tcx.hir_module_items(module_def_id);
1879 let _ = crate_items.par_items(|id| Ok(checker.check_item(id)));
1880 let _ = crate_items.par_foreign_items(|id| Ok(checker.check_foreign_item(id)));
1881}