]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_passes/src/stability.rs
New upstream version 1.54.0+dfsg1
[rustc.git] / compiler / rustc_passes / src / stability.rs
1 //! A pass that annotates every item and method with its stability level,
2 //! propagating default levels lexically from parent to children ast nodes.
3
4 use rustc_ast::Attribute;
5 use rustc_attr::{self as attr, ConstStability, Stability};
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7 use rustc_errors::struct_span_err;
8 use rustc_hir as hir;
9 use rustc_hir::def::{DefKind, Res};
10 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
11 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
12 use rustc_hir::{FieldDef, Generics, HirId, Item, TraitRef, Ty, TyKind, Variant};
13 use rustc_middle::hir::map::Map;
14 use rustc_middle::middle::privacy::AccessLevels;
15 use rustc_middle::middle::stability::{DeprecationEntry, Index};
16 use rustc_middle::ty::{self, query::Providers, TyCtxt};
17 use rustc_session::lint;
18 use rustc_session::lint::builtin::{INEFFECTIVE_UNSTABLE_TRAIT_IMPL, USELESS_DEPRECATED};
19 use rustc_session::parse::feature_err;
20 use rustc_session::Session;
21 use rustc_span::symbol::{sym, Symbol};
22 use rustc_span::{Span, DUMMY_SP};
23
24 use std::cmp::Ordering;
25 use std::iter;
26 use std::mem::replace;
27 use std::num::NonZeroU32;
28
29 #[derive(PartialEq)]
30 enum AnnotationKind {
31 // Annotation is required if not inherited from unstable parents
32 Required,
33 // Annotation is useless, reject it
34 Prohibited,
35 // Deprecation annotation is useless, reject it. (Stability attribute is still required.)
36 DeprecationProhibited,
37 // Annotation itself is useless, but it can be propagated to children
38 Container,
39 }
40
41 /// Whether to inherit deprecation flags for nested items. In most cases, we do want to inherit
42 /// deprecation, because nested items rarely have individual deprecation attributes, and so
43 /// should be treated as deprecated if their parent is. However, default generic parameters
44 /// have separate deprecation attributes from their parents, so we do not wish to inherit
45 /// deprecation in this case. For example, inheriting deprecation for `T` in `Foo<T>`
46 /// would cause a duplicate warning arising from both `Foo` and `T` being deprecated.
47 #[derive(Clone)]
48 enum InheritDeprecation {
49 Yes,
50 No,
51 }
52
53 impl InheritDeprecation {
54 fn yes(&self) -> bool {
55 matches!(self, InheritDeprecation::Yes)
56 }
57 }
58
59 /// Whether to inherit const stability flags for nested items. In most cases, we do not want to
60 /// inherit const stability: just because an enclosing `fn` is const-stable does not mean
61 /// all `extern` imports declared in it should be const-stable! However, trait methods
62 /// inherit const stability attributes from their parent and do not have their own.
63 enum InheritConstStability {
64 Yes,
65 No,
66 }
67
68 impl InheritConstStability {
69 fn yes(&self) -> bool {
70 matches!(self, InheritConstStability::Yes)
71 }
72 }
73
74 enum InheritStability {
75 Yes,
76 No,
77 }
78
79 impl InheritStability {
80 fn yes(&self) -> bool {
81 matches!(self, InheritStability::Yes)
82 }
83 }
84
85 // A private tree-walker for producing an Index.
86 struct Annotator<'a, 'tcx> {
87 tcx: TyCtxt<'tcx>,
88 index: &'a mut Index<'tcx>,
89 parent_stab: Option<&'tcx Stability>,
90 parent_const_stab: Option<&'tcx ConstStability>,
91 parent_depr: Option<DeprecationEntry>,
92 in_trait_impl: bool,
93 }
94
95 impl<'a, 'tcx> Annotator<'a, 'tcx> {
96 // Determine the stability for a node based on its attributes and inherited
97 // stability. The stability is recorded in the index and used as the parent.
98 fn annotate<F>(
99 &mut self,
100 hir_id: HirId,
101 item_sp: Span,
102 kind: AnnotationKind,
103 inherit_deprecation: InheritDeprecation,
104 inherit_const_stability: InheritConstStability,
105 inherit_from_parent: InheritStability,
106 visit_children: F,
107 ) where
108 F: FnOnce(&mut Self),
109 {
110 let attrs = self.tcx.hir().attrs(hir_id);
111 debug!("annotate(id = {:?}, attrs = {:?})", hir_id, attrs);
112 let mut did_error = false;
113 if !self.tcx.features().staged_api {
114 did_error = self.forbid_staged_api_attrs(hir_id, attrs, inherit_deprecation.clone());
115 }
116
117 let depr = if did_error { None } else { attr::find_deprecation(&self.tcx.sess, attrs) };
118 let mut is_deprecated = false;
119 if let Some((depr, span)) = &depr {
120 is_deprecated = true;
121
122 if kind == AnnotationKind::Prohibited || kind == AnnotationKind::DeprecationProhibited {
123 self.tcx.struct_span_lint_hir(USELESS_DEPRECATED, hir_id, *span, |lint| {
124 lint.build("this `#[deprecated]` annotation has no effect")
125 .span_suggestion_short(
126 *span,
127 "remove the unnecessary deprecation attribute",
128 String::new(),
129 rustc_errors::Applicability::MachineApplicable,
130 )
131 .emit()
132 });
133 }
134
135 // `Deprecation` is just two pointers, no need to intern it
136 let depr_entry = DeprecationEntry::local(depr.clone(), hir_id);
137 self.index.depr_map.insert(hir_id, depr_entry);
138 } else if let Some(parent_depr) = self.parent_depr.clone() {
139 if inherit_deprecation.yes() {
140 is_deprecated = true;
141 info!("tagging child {:?} as deprecated from parent", hir_id);
142 self.index.depr_map.insert(hir_id, parent_depr);
143 }
144 }
145
146 if self.tcx.features().staged_api {
147 if let Some(a) = attrs.iter().find(|a| self.tcx.sess.check_name(a, sym::deprecated)) {
148 self.tcx
149 .sess
150 .struct_span_err(a.span, "`#[deprecated]` cannot be used in staged API")
151 .span_label(a.span, "use `#[rustc_deprecated]` instead")
152 .span_label(item_sp, "")
153 .emit();
154 }
155 } else {
156 self.recurse_with_stability_attrs(
157 depr.map(|(d, _)| DeprecationEntry::local(d, hir_id)),
158 None,
159 None,
160 visit_children,
161 );
162 return;
163 }
164
165 let (stab, const_stab) = attr::find_stability(&self.tcx.sess, attrs, item_sp);
166
167 let const_stab = const_stab.map(|(const_stab, _)| {
168 let const_stab = self.tcx.intern_const_stability(const_stab);
169 self.index.const_stab_map.insert(hir_id, const_stab);
170 const_stab
171 });
172
173 // `impl const Trait for Type` items forward their const stability to their
174 // immediate children.
175 if const_stab.is_none() {
176 debug!("annotate: const_stab not found, parent = {:?}", self.parent_const_stab);
177 if let Some(parent) = self.parent_const_stab {
178 if parent.level.is_unstable() {
179 self.index.const_stab_map.insert(hir_id, parent);
180 }
181 }
182 }
183
184 if let Some((rustc_attr::Deprecation { is_since_rustc_version: true, .. }, span)) = &depr {
185 if stab.is_none() {
186 struct_span_err!(
187 self.tcx.sess,
188 *span,
189 E0549,
190 "rustc_deprecated attribute must be paired with \
191 either stable or unstable attribute"
192 )
193 .emit();
194 }
195 }
196
197 let stab = stab.map(|(stab, span)| {
198 // Error if prohibited, or can't inherit anything from a container.
199 if kind == AnnotationKind::Prohibited
200 || (kind == AnnotationKind::Container && stab.level.is_stable() && is_deprecated)
201 {
202 self.tcx.sess.struct_span_err(span,"this stability annotation is useless")
203 .span_label(span, "useless stability annotation")
204 .span_label(item_sp, "the stability attribute annotates this item")
205 .emit();
206 }
207
208 debug!("annotate: found {:?}", stab);
209 let stab = self.tcx.intern_stability(stab);
210
211 // Check if deprecated_since < stable_since. If it is,
212 // this is *almost surely* an accident.
213 if let (&Some(dep_since), &attr::Stable { since: stab_since }) =
214 (&depr.as_ref().and_then(|(d, _)| d.since), &stab.level)
215 {
216 // Explicit version of iter::order::lt to handle parse errors properly
217 for (dep_v, stab_v) in
218 iter::zip(dep_since.as_str().split('.'), stab_since.as_str().split('.'))
219 {
220 match stab_v.parse::<u64>() {
221 Err(_) => {
222 self.tcx.sess.struct_span_err(span, "invalid stability version found")
223 .span_label(span, "invalid stability version")
224 .span_label(item_sp, "the stability attribute annotates this item")
225 .emit();
226 break;
227 }
228 Ok(stab_vp) => match dep_v.parse::<u64>() {
229 Ok(dep_vp) => match dep_vp.cmp(&stab_vp) {
230 Ordering::Less => {
231 self.tcx.sess.struct_span_err(span, "an API can't be stabilized after it is deprecated")
232 .span_label(span, "invalid version")
233 .span_label(item_sp, "the stability attribute annotates this item")
234 .emit();
235 break;
236 }
237 Ordering::Equal => continue,
238 Ordering::Greater => break,
239 },
240 Err(_) => {
241 if dep_v != "TBD" {
242 self.tcx.sess.struct_span_err(span, "invalid deprecation version found")
243 .span_label(span, "invalid deprecation version")
244 .span_label(item_sp, "the stability attribute annotates this item")
245 .emit();
246 }
247 break;
248 }
249 },
250 }
251 }
252 }
253
254 self.index.stab_map.insert(hir_id, stab);
255 stab
256 });
257
258 if stab.is_none() {
259 debug!("annotate: stab not found, parent = {:?}", self.parent_stab);
260 if let Some(stab) = self.parent_stab {
261 if inherit_deprecation.yes() && stab.level.is_unstable()
262 || inherit_from_parent.yes()
263 {
264 self.index.stab_map.insert(hir_id, stab);
265 }
266 }
267 }
268
269 self.recurse_with_stability_attrs(
270 depr.map(|(d, _)| DeprecationEntry::local(d, hir_id)),
271 stab,
272 if inherit_const_stability.yes() { const_stab } else { None },
273 visit_children,
274 );
275 }
276
277 fn recurse_with_stability_attrs(
278 &mut self,
279 depr: Option<DeprecationEntry>,
280 stab: Option<&'tcx Stability>,
281 const_stab: Option<&'tcx ConstStability>,
282 f: impl FnOnce(&mut Self),
283 ) {
284 // These will be `Some` if this item changes the corresponding stability attribute.
285 let mut replaced_parent_depr = None;
286 let mut replaced_parent_stab = None;
287 let mut replaced_parent_const_stab = None;
288
289 if let Some(depr) = depr {
290 replaced_parent_depr = Some(replace(&mut self.parent_depr, Some(depr)));
291 }
292 if let Some(stab) = stab {
293 replaced_parent_stab = Some(replace(&mut self.parent_stab, Some(stab)));
294 }
295 if let Some(const_stab) = const_stab {
296 replaced_parent_const_stab =
297 Some(replace(&mut self.parent_const_stab, Some(const_stab)));
298 }
299
300 f(self);
301
302 if let Some(orig_parent_depr) = replaced_parent_depr {
303 self.parent_depr = orig_parent_depr;
304 }
305 if let Some(orig_parent_stab) = replaced_parent_stab {
306 self.parent_stab = orig_parent_stab;
307 }
308 if let Some(orig_parent_const_stab) = replaced_parent_const_stab {
309 self.parent_const_stab = orig_parent_const_stab;
310 }
311 }
312
313 // returns true if an error occurred, used to suppress some spurious errors
314 fn forbid_staged_api_attrs(
315 &mut self,
316 hir_id: HirId,
317 attrs: &[Attribute],
318 inherit_deprecation: InheritDeprecation,
319 ) -> bool {
320 // Emit errors for non-staged-api crates.
321 let unstable_attrs = [
322 sym::unstable,
323 sym::stable,
324 sym::rustc_deprecated,
325 sym::rustc_const_unstable,
326 sym::rustc_const_stable,
327 ];
328 let mut has_error = false;
329 for attr in attrs {
330 let name = attr.name_or_empty();
331 if unstable_attrs.contains(&name) {
332 self.tcx.sess.mark_attr_used(attr);
333 struct_span_err!(
334 self.tcx.sess,
335 attr.span,
336 E0734,
337 "stability attributes may not be used outside of the standard library",
338 )
339 .emit();
340 has_error = true;
341 }
342 }
343
344 // Propagate unstability. This can happen even for non-staged-api crates in case
345 // -Zforce-unstable-if-unmarked is set.
346 if let Some(stab) = self.parent_stab {
347 if inherit_deprecation.yes() && stab.level.is_unstable() {
348 self.index.stab_map.insert(hir_id, stab);
349 }
350 }
351
352 has_error
353 }
354 }
355
356 impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> {
357 /// Because stability levels are scoped lexically, we want to walk
358 /// nested items in the context of the outer item, so enable
359 /// deep-walking.
360 type Map = Map<'tcx>;
361
362 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
363 NestedVisitorMap::All(self.tcx.hir())
364 }
365
366 fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
367 let orig_in_trait_impl = self.in_trait_impl;
368 let mut kind = AnnotationKind::Required;
369 let mut const_stab_inherit = InheritConstStability::No;
370 match i.kind {
371 // Inherent impls and foreign modules serve only as containers for other items,
372 // they don't have their own stability. They still can be annotated as unstable
373 // and propagate this unstability to children, but this annotation is completely
374 // optional. They inherit stability from their parents when unannotated.
375 hir::ItemKind::Impl(hir::Impl { of_trait: None, .. })
376 | hir::ItemKind::ForeignMod { .. } => {
377 self.in_trait_impl = false;
378 kind = AnnotationKind::Container;
379 }
380 hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => {
381 self.in_trait_impl = true;
382 kind = AnnotationKind::DeprecationProhibited;
383 const_stab_inherit = InheritConstStability::Yes;
384 }
385 hir::ItemKind::Struct(ref sd, _) => {
386 if let Some(ctor_hir_id) = sd.ctor_hir_id() {
387 self.annotate(
388 ctor_hir_id,
389 i.span,
390 AnnotationKind::Required,
391 InheritDeprecation::Yes,
392 InheritConstStability::No,
393 InheritStability::Yes,
394 |_| {},
395 )
396 }
397 }
398 _ => {}
399 }
400
401 self.annotate(
402 i.hir_id(),
403 i.span,
404 kind,
405 InheritDeprecation::Yes,
406 const_stab_inherit,
407 InheritStability::No,
408 |v| intravisit::walk_item(v, i),
409 );
410 self.in_trait_impl = orig_in_trait_impl;
411 }
412
413 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
414 self.annotate(
415 ti.hir_id(),
416 ti.span,
417 AnnotationKind::Required,
418 InheritDeprecation::Yes,
419 InheritConstStability::No,
420 InheritStability::No,
421 |v| {
422 intravisit::walk_trait_item(v, ti);
423 },
424 );
425 }
426
427 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
428 let kind =
429 if self.in_trait_impl { AnnotationKind::Prohibited } else { AnnotationKind::Required };
430 self.annotate(
431 ii.hir_id(),
432 ii.span,
433 kind,
434 InheritDeprecation::Yes,
435 InheritConstStability::No,
436 InheritStability::No,
437 |v| {
438 intravisit::walk_impl_item(v, ii);
439 },
440 );
441 }
442
443 fn visit_variant(&mut self, var: &'tcx Variant<'tcx>, g: &'tcx Generics<'tcx>, item_id: HirId) {
444 self.annotate(
445 var.id,
446 var.span,
447 AnnotationKind::Required,
448 InheritDeprecation::Yes,
449 InheritConstStability::No,
450 InheritStability::Yes,
451 |v| {
452 if let Some(ctor_hir_id) = var.data.ctor_hir_id() {
453 v.annotate(
454 ctor_hir_id,
455 var.span,
456 AnnotationKind::Required,
457 InheritDeprecation::Yes,
458 InheritConstStability::No,
459 InheritStability::No,
460 |_| {},
461 );
462 }
463
464 intravisit::walk_variant(v, var, g, item_id)
465 },
466 )
467 }
468
469 fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) {
470 self.annotate(
471 s.hir_id,
472 s.span,
473 AnnotationKind::Required,
474 InheritDeprecation::Yes,
475 InheritConstStability::No,
476 InheritStability::Yes,
477 |v| {
478 intravisit::walk_field_def(v, s);
479 },
480 );
481 }
482
483 fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
484 self.annotate(
485 i.hir_id(),
486 i.span,
487 AnnotationKind::Required,
488 InheritDeprecation::Yes,
489 InheritConstStability::No,
490 InheritStability::No,
491 |v| {
492 intravisit::walk_foreign_item(v, i);
493 },
494 );
495 }
496
497 fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef<'tcx>) {
498 self.annotate(
499 md.hir_id(),
500 md.span,
501 AnnotationKind::Required,
502 InheritDeprecation::Yes,
503 InheritConstStability::No,
504 InheritStability::No,
505 |_| {},
506 );
507 }
508
509 fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
510 let kind = match &p.kind {
511 // Allow stability attributes on default generic arguments.
512 hir::GenericParamKind::Type { default: Some(_), .. }
513 | hir::GenericParamKind::Const { default: Some(_), .. } => AnnotationKind::Container,
514 _ => AnnotationKind::Prohibited,
515 };
516
517 self.annotate(
518 p.hir_id,
519 p.span,
520 kind,
521 InheritDeprecation::No,
522 InheritConstStability::No,
523 InheritStability::No,
524 |v| {
525 intravisit::walk_generic_param(v, p);
526 },
527 );
528 }
529 }
530
531 struct MissingStabilityAnnotations<'tcx> {
532 tcx: TyCtxt<'tcx>,
533 access_levels: &'tcx AccessLevels,
534 }
535
536 impl<'tcx> MissingStabilityAnnotations<'tcx> {
537 fn check_missing_stability(&self, hir_id: HirId, span: Span) {
538 let stab = self.tcx.stability().local_stability(hir_id);
539 let is_error =
540 !self.tcx.sess.opts.test && stab.is_none() && self.access_levels.is_reachable(hir_id);
541 if is_error {
542 let def_id = self.tcx.hir().local_def_id(hir_id);
543 let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id());
544 self.tcx.sess.span_err(span, &format!("{} has missing stability attribute", descr));
545 }
546 }
547
548 fn check_missing_const_stability(&self, hir_id: HirId, span: Span) {
549 let stab_map = self.tcx.stability();
550 let stab = stab_map.local_stability(hir_id);
551 if stab.map_or(false, |stab| stab.level.is_stable()) {
552 let const_stab = stab_map.local_const_stability(hir_id);
553 if const_stab.is_none() {
554 self.tcx.sess.span_err(
555 span,
556 "`#[stable]` const functions must also be either \
557 `#[rustc_const_stable]` or `#[rustc_const_unstable]`",
558 );
559 }
560 }
561 }
562 }
563
564 impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> {
565 type Map = Map<'tcx>;
566
567 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
568 NestedVisitorMap::OnlyBodies(self.tcx.hir())
569 }
570
571 fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
572 // Inherent impls and foreign modules serve only as containers for other items,
573 // they don't have their own stability. They still can be annotated as unstable
574 // and propagate this unstability to children, but this annotation is completely
575 // optional. They inherit stability from their parents when unannotated.
576 if !matches!(
577 i.kind,
578 hir::ItemKind::Impl(hir::Impl { of_trait: None, .. })
579 | hir::ItemKind::ForeignMod { .. }
580 ) {
581 self.check_missing_stability(i.hir_id(), i.span);
582 }
583
584 // Ensure `const fn` that are `stable` have one of `rustc_const_unstable` or
585 // `rustc_const_stable`.
586 if self.tcx.features().staged_api
587 && matches!(&i.kind, hir::ItemKind::Fn(sig, ..) if sig.header.is_const())
588 {
589 self.check_missing_const_stability(i.hir_id(), i.span);
590 }
591
592 intravisit::walk_item(self, i)
593 }
594
595 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
596 self.check_missing_stability(ti.hir_id(), ti.span);
597 intravisit::walk_trait_item(self, ti);
598 }
599
600 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
601 let impl_def_id = self.tcx.hir().local_def_id(self.tcx.hir().get_parent_item(ii.hir_id()));
602 if self.tcx.impl_trait_ref(impl_def_id).is_none() {
603 self.check_missing_stability(ii.hir_id(), ii.span);
604 }
605 intravisit::walk_impl_item(self, ii);
606 }
607
608 fn visit_variant(&mut self, var: &'tcx Variant<'tcx>, g: &'tcx Generics<'tcx>, item_id: HirId) {
609 self.check_missing_stability(var.id, var.span);
610 intravisit::walk_variant(self, var, g, item_id);
611 }
612
613 fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) {
614 self.check_missing_stability(s.hir_id, s.span);
615 intravisit::walk_field_def(self, s);
616 }
617
618 fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
619 self.check_missing_stability(i.hir_id(), i.span);
620 intravisit::walk_foreign_item(self, i);
621 }
622
623 fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef<'tcx>) {
624 self.check_missing_stability(md.hir_id(), md.span);
625 }
626
627 // Note that we don't need to `check_missing_stability` for default generic parameters,
628 // as we assume that any default generic parameters without attributes are automatically
629 // stable (assuming they have not inherited instability from their parent).
630 }
631
632 fn stability_index(tcx: TyCtxt<'tcx>, (): ()) -> Index<'tcx> {
633 let is_staged_api =
634 tcx.sess.opts.debugging_opts.force_unstable_if_unmarked || tcx.features().staged_api;
635 let mut staged_api = FxHashMap::default();
636 staged_api.insert(LOCAL_CRATE, is_staged_api);
637 let mut index = Index {
638 staged_api,
639 stab_map: Default::default(),
640 const_stab_map: Default::default(),
641 depr_map: Default::default(),
642 active_features: Default::default(),
643 };
644
645 let active_lib_features = &tcx.features().declared_lib_features;
646 let active_lang_features = &tcx.features().declared_lang_features;
647
648 // Put the active features into a map for quick lookup.
649 index.active_features = active_lib_features
650 .iter()
651 .map(|&(s, ..)| s)
652 .chain(active_lang_features.iter().map(|&(s, ..)| s))
653 .collect();
654
655 {
656 let krate = tcx.hir().krate();
657 let mut annotator = Annotator {
658 tcx,
659 index: &mut index,
660 parent_stab: None,
661 parent_const_stab: None,
662 parent_depr: None,
663 in_trait_impl: false,
664 };
665
666 // If the `-Z force-unstable-if-unmarked` flag is passed then we provide
667 // a parent stability annotation which indicates that this is private
668 // with the `rustc_private` feature. This is intended for use when
669 // compiling `librustc_*` crates themselves so we can leverage crates.io
670 // while maintaining the invariant that all sysroot crates are unstable
671 // by default and are unable to be used.
672 if tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
673 let reason = "this crate is being loaded from the sysroot, an \
674 unstable location; did you mean to load this crate \
675 from crates.io via `Cargo.toml` instead?";
676 let stability = tcx.intern_stability(Stability {
677 level: attr::StabilityLevel::Unstable {
678 reason: Some(Symbol::intern(reason)),
679 issue: NonZeroU32::new(27812),
680 is_soft: false,
681 },
682 feature: sym::rustc_private,
683 });
684 annotator.parent_stab = Some(stability);
685 }
686
687 annotator.annotate(
688 hir::CRATE_HIR_ID,
689 krate.item.inner,
690 AnnotationKind::Required,
691 InheritDeprecation::Yes,
692 InheritConstStability::No,
693 InheritStability::No,
694 |v| intravisit::walk_crate(v, krate),
695 );
696 }
697 index
698 }
699
700 /// Cross-references the feature names of unstable APIs with enabled
701 /// features and possibly prints errors.
702 fn check_mod_unstable_api_usage(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
703 tcx.hir().visit_item_likes_in_module(module_def_id, &mut Checker { tcx }.as_deep_visitor());
704 }
705
706 pub(crate) fn provide(providers: &mut Providers) {
707 *providers = Providers { check_mod_unstable_api_usage, stability_index, ..*providers };
708 }
709
710 struct Checker<'tcx> {
711 tcx: TyCtxt<'tcx>,
712 }
713
714 impl Visitor<'tcx> for Checker<'tcx> {
715 type Map = Map<'tcx>;
716
717 /// Because stability levels are scoped lexically, we want to walk
718 /// nested items in the context of the outer item, so enable
719 /// deep-walking.
720 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
721 NestedVisitorMap::OnlyBodies(self.tcx.hir())
722 }
723
724 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
725 match item.kind {
726 hir::ItemKind::ExternCrate(_) => {
727 // compiler-generated `extern crate` items have a dummy span.
728 // `std` is still checked for the `restricted-std` feature.
729 if item.span.is_dummy() && item.ident.as_str() != "std" {
730 return;
731 }
732
733 let cnum = match self.tcx.extern_mod_stmt_cnum(item.def_id) {
734 Some(cnum) => cnum,
735 None => return,
736 };
737 let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
738 self.tcx.check_stability(def_id, Some(item.hir_id()), item.span, None);
739 }
740
741 // For implementations of traits, check the stability of each item
742 // individually as it's possible to have a stable trait with unstable
743 // items.
744 hir::ItemKind::Impl(hir::Impl { of_trait: Some(ref t), self_ty, items, .. }) => {
745 if self.tcx.features().staged_api {
746 // If this impl block has an #[unstable] attribute, give an
747 // error if all involved types and traits are stable, because
748 // it will have no effect.
749 // See: https://github.com/rust-lang/rust/issues/55436
750 let attrs = self.tcx.hir().attrs(item.hir_id());
751 if let (Some((Stability { level: attr::Unstable { .. }, .. }, span)), _) =
752 attr::find_stability(&self.tcx.sess, attrs, item.span)
753 {
754 let mut c = CheckTraitImplStable { tcx: self.tcx, fully_stable: true };
755 c.visit_ty(self_ty);
756 c.visit_trait_ref(t);
757 if c.fully_stable {
758 self.tcx.struct_span_lint_hir(
759 INEFFECTIVE_UNSTABLE_TRAIT_IMPL,
760 item.hir_id(),
761 span,
762 |lint| lint
763 .build("an `#[unstable]` annotation here has no effect")
764 .note("see issue #55436 <https://github.com/rust-lang/rust/issues/55436> for more information")
765 .emit()
766 );
767 }
768 }
769 }
770
771 if let Res::Def(DefKind::Trait, trait_did) = t.path.res {
772 for impl_item_ref in items {
773 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
774 let trait_item_def_id = self
775 .tcx
776 .associated_items(trait_did)
777 .filter_by_name_unhygienic(impl_item.ident.name)
778 .next()
779 .map(|item| item.def_id);
780 if let Some(def_id) = trait_item_def_id {
781 // Pass `None` to skip deprecation warnings.
782 self.tcx.check_stability(def_id, None, impl_item.span, None);
783 }
784 }
785 }
786 }
787
788 // There's no good place to insert stability check for non-Copy unions,
789 // so semi-randomly perform it here in stability.rs
790 hir::ItemKind::Union(..) if !self.tcx.features().untagged_unions => {
791 let ty = self.tcx.type_of(item.def_id);
792 let (adt_def, substs) = match ty.kind() {
793 ty::Adt(adt_def, substs) => (adt_def, substs),
794 _ => bug!(),
795 };
796
797 // Non-`Copy` fields are unstable, except for `ManuallyDrop`.
798 let param_env = self.tcx.param_env(item.def_id);
799 for field in &adt_def.non_enum_variant().fields {
800 let field_ty = field.ty(self.tcx, substs);
801 if !field_ty.ty_adt_def().map_or(false, |adt_def| adt_def.is_manually_drop())
802 && !field_ty.is_copy_modulo_regions(self.tcx.at(DUMMY_SP), param_env)
803 {
804 if field_ty.needs_drop(self.tcx, param_env) {
805 // Avoid duplicate error: This will error later anyway because fields
806 // that need drop are not allowed.
807 self.tcx.sess.delay_span_bug(
808 item.span,
809 "union should have been rejected due to potentially dropping field",
810 );
811 } else {
812 feature_err(
813 &self.tcx.sess.parse_sess,
814 sym::untagged_unions,
815 self.tcx.def_span(field.did),
816 "unions with non-`Copy` fields other than `ManuallyDrop<T>` are unstable",
817 )
818 .emit();
819 }
820 }
821 }
822 }
823
824 _ => (/* pass */),
825 }
826 intravisit::walk_item(self, item);
827 }
828
829 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, id: hir::HirId) {
830 if let Some(def_id) = path.res.opt_def_id() {
831 self.tcx.check_stability(def_id, Some(id), path.span, None)
832 }
833 intravisit::walk_path(self, path)
834 }
835 }
836
837 struct CheckTraitImplStable<'tcx> {
838 tcx: TyCtxt<'tcx>,
839 fully_stable: bool,
840 }
841
842 impl Visitor<'tcx> for CheckTraitImplStable<'tcx> {
843 type Map = Map<'tcx>;
844
845 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
846 NestedVisitorMap::None
847 }
848
849 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _id: hir::HirId) {
850 if let Some(def_id) = path.res.opt_def_id() {
851 if let Some(stab) = self.tcx.lookup_stability(def_id) {
852 self.fully_stable &= stab.level.is_stable();
853 }
854 }
855 intravisit::walk_path(self, path)
856 }
857
858 fn visit_trait_ref(&mut self, t: &'tcx TraitRef<'tcx>) {
859 if let Res::Def(DefKind::Trait, trait_did) = t.path.res {
860 if let Some(stab) = self.tcx.lookup_stability(trait_did) {
861 self.fully_stable &= stab.level.is_stable();
862 }
863 }
864 intravisit::walk_trait_ref(self, t)
865 }
866
867 fn visit_ty(&mut self, t: &'tcx Ty<'tcx>) {
868 if let TyKind::Never = t.kind {
869 self.fully_stable = false;
870 }
871 intravisit::walk_ty(self, t)
872 }
873 }
874
875 /// Given the list of enabled features that were not language features (i.e., that
876 /// were expected to be library features), and the list of features used from
877 /// libraries, identify activated features that don't exist and error about them.
878 pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) {
879 let access_levels = &tcx.privacy_access_levels(());
880
881 if tcx.stability().staged_api[&LOCAL_CRATE] {
882 let krate = tcx.hir().krate();
883 let mut missing = MissingStabilityAnnotations { tcx, access_levels };
884 missing.check_missing_stability(hir::CRATE_HIR_ID, krate.item.inner);
885 intravisit::walk_crate(&mut missing, krate);
886 krate.visit_all_item_likes(&mut missing.as_deep_visitor());
887 }
888
889 let declared_lang_features = &tcx.features().declared_lang_features;
890 let mut lang_features = FxHashSet::default();
891 for &(feature, span, since) in declared_lang_features {
892 if let Some(since) = since {
893 // Warn if the user has enabled an already-stable lang feature.
894 unnecessary_stable_feature_lint(tcx, span, feature, since);
895 }
896 if !lang_features.insert(feature) {
897 // Warn if the user enables a lang feature multiple times.
898 duplicate_feature_err(tcx.sess, span, feature);
899 }
900 }
901
902 let declared_lib_features = &tcx.features().declared_lib_features;
903 let mut remaining_lib_features = FxHashMap::default();
904 for (feature, span) in declared_lib_features {
905 if remaining_lib_features.contains_key(&feature) {
906 // Warn if the user enables a lib feature multiple times.
907 duplicate_feature_err(tcx.sess, *span, *feature);
908 }
909 remaining_lib_features.insert(feature, *span);
910 }
911 // `stdbuild` has special handling for `libc`, so we need to
912 // recognise the feature when building std.
913 // Likewise, libtest is handled specially, so `test` isn't
914 // available as we'd like it to be.
915 // FIXME: only remove `libc` when `stdbuild` is active.
916 // FIXME: remove special casing for `test`.
917 remaining_lib_features.remove(&sym::libc);
918 remaining_lib_features.remove(&sym::test);
919
920 let check_features = |remaining_lib_features: &mut FxHashMap<_, _>, defined_features: &[_]| {
921 for &(feature, since) in defined_features {
922 if let Some(since) = since {
923 if let Some(span) = remaining_lib_features.get(&feature) {
924 // Warn if the user has enabled an already-stable lib feature.
925 unnecessary_stable_feature_lint(tcx, *span, feature, since);
926 }
927 }
928 remaining_lib_features.remove(&feature);
929 if remaining_lib_features.is_empty() {
930 break;
931 }
932 }
933 };
934
935 // We always collect the lib features declared in the current crate, even if there are
936 // no unknown features, because the collection also does feature attribute validation.
937 let local_defined_features = tcx.lib_features().to_vec();
938 if !remaining_lib_features.is_empty() {
939 check_features(&mut remaining_lib_features, &local_defined_features);
940
941 for &cnum in &*tcx.crates() {
942 if remaining_lib_features.is_empty() {
943 break;
944 }
945 check_features(&mut remaining_lib_features, tcx.defined_lib_features(cnum));
946 }
947 }
948
949 for (feature, span) in remaining_lib_features {
950 struct_span_err!(tcx.sess, span, E0635, "unknown feature `{}`", feature).emit();
951 }
952
953 // FIXME(#44232): the `used_features` table no longer exists, so we
954 // don't lint about unused features. We should re-enable this one day!
955 }
956
957 fn unnecessary_stable_feature_lint(tcx: TyCtxt<'_>, span: Span, feature: Symbol, since: Symbol) {
958 tcx.struct_span_lint_hir(lint::builtin::STABLE_FEATURES, hir::CRATE_HIR_ID, span, |lint| {
959 lint.build(&format!(
960 "the feature `{}` has been stable since {} and no longer requires \
961 an attribute to enable",
962 feature, since
963 ))
964 .emit();
965 });
966 }
967
968 fn duplicate_feature_err(sess: &Session, span: Span, feature: Symbol) {
969 struct_span_err!(sess, span, E0636, "the feature `{}` has already been declared", feature)
970 .emit();
971 }