]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/stability.rs
Rollup merge of #54811 - pnkfelix:issue-24840-separate-bootstrap-default-for-optimize...
[rust.git] / src / librustc / middle / stability.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! A pass that annotates every item and method with its stability level,
12 //! propagating default levels lexically from parent to children ast nodes.
13
14 pub use self::StabilityLevel::*;
15
16 use lint;
17 use hir::def::Def;
18 use hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId, LOCAL_CRATE};
19 use ty::{self, TyCtxt};
20 use middle::privacy::AccessLevels;
21 use session::{DiagnosticMessageId, Session};
22 use syntax::symbol::Symbol;
23 use syntax_pos::{Span, MultiSpan};
24 use syntax::ast;
25 use syntax::ast::{NodeId, Attribute};
26 use syntax::feature_gate::{GateIssue, emit_feature_err};
27 use syntax::attr::{self, Stability, Deprecation};
28 use util::nodemap::{FxHashSet, FxHashMap};
29
30 use hir;
31 use hir::{Item, Generics, StructField, Variant, HirId};
32 use hir::intravisit::{self, Visitor, NestedVisitorMap};
33
34 use std::mem::replace;
35 use std::cmp::Ordering;
36
37 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Copy, Debug, Eq, Hash)]
38 pub enum StabilityLevel {
39     Unstable,
40     Stable,
41 }
42
43 impl StabilityLevel {
44     pub fn from_attr_level(level: &attr::StabilityLevel) -> Self {
45         if level.is_stable() { Stable } else { Unstable }
46     }
47 }
48
49 #[derive(PartialEq)]
50 enum AnnotationKind {
51     // Annotation is required if not inherited from unstable parents
52     Required,
53     // Annotation is useless, reject it
54     Prohibited,
55     // Annotation itself is useless, but it can be propagated to children
56     Container,
57 }
58
59 /// An entry in the `depr_map`.
60 #[derive(Clone)]
61 pub struct DeprecationEntry {
62     /// The metadata of the attribute associated with this entry.
63     pub attr: Deprecation,
64     /// The def id where the attr was originally attached. `None` for non-local
65     /// `DefId`'s.
66     origin: Option<HirId>,
67 }
68
69 impl_stable_hash_for!(struct self::DeprecationEntry {
70     attr,
71     origin
72 });
73
74 impl DeprecationEntry {
75     fn local(attr: Deprecation, id: HirId) -> DeprecationEntry {
76         DeprecationEntry {
77             attr,
78             origin: Some(id),
79         }
80     }
81
82     pub fn external(attr: Deprecation) -> DeprecationEntry {
83         DeprecationEntry {
84             attr,
85             origin: None,
86         }
87     }
88
89     pub fn same_origin(&self, other: &DeprecationEntry) -> bool {
90         match (self.origin, other.origin) {
91             (Some(o1), Some(o2)) => o1 == o2,
92             _ => false
93         }
94     }
95 }
96
97 /// A stability index, giving the stability level for items and methods.
98 pub struct Index<'tcx> {
99     /// This is mostly a cache, except the stabilities of local items
100     /// are filled by the annotator.
101     stab_map: FxHashMap<HirId, &'tcx Stability>,
102     depr_map: FxHashMap<HirId, DeprecationEntry>,
103
104     /// Maps for each crate whether it is part of the staged API.
105     staged_api: FxHashMap<CrateNum, bool>,
106
107     /// Features enabled for this crate.
108     active_features: FxHashSet<Symbol>,
109 }
110
111 impl_stable_hash_for!(struct self::Index<'tcx> {
112     stab_map,
113     depr_map,
114     staged_api,
115     active_features
116 });
117
118 // A private tree-walker for producing an Index.
119 struct Annotator<'a, 'tcx: 'a> {
120     tcx: TyCtxt<'a, 'tcx, 'tcx>,
121     index: &'a mut Index<'tcx>,
122     parent_stab: Option<&'tcx Stability>,
123     parent_depr: Option<DeprecationEntry>,
124     in_trait_impl: bool,
125 }
126
127 impl<'a, 'tcx: 'a> Annotator<'a, 'tcx> {
128     // Determine the stability for a node based on its attributes and inherited
129     // stability. The stability is recorded in the index and used as the parent.
130     fn annotate<F>(&mut self, id: NodeId, attrs: &[Attribute],
131                    item_sp: Span, kind: AnnotationKind, visit_children: F)
132         where F: FnOnce(&mut Self)
133     {
134         if self.tcx.features().staged_api {
135             // This crate explicitly wants staged API.
136             debug!("annotate(id = {:?}, attrs = {:?})", id, attrs);
137             if let Some(..) = attr::find_deprecation(self.tcx.sess.diagnostic(), attrs, item_sp) {
138                 self.tcx.sess.span_err(item_sp, "`#[deprecated]` cannot be used in staged api, \
139                                                  use `#[rustc_deprecated]` instead");
140             }
141             if let Some(mut stab) = attr::find_stability(self.tcx.sess.diagnostic(),
142                                                          attrs, item_sp) {
143                 // Error if prohibited, or can't inherit anything from a container
144                 if kind == AnnotationKind::Prohibited ||
145                    (kind == AnnotationKind::Container &&
146                     stab.level.is_stable() &&
147                     stab.rustc_depr.is_none()) {
148                     self.tcx.sess.span_err(item_sp, "This stability annotation is useless");
149                 }
150
151                 debug!("annotate: found {:?}", stab);
152                 // If parent is deprecated and we're not, inherit this by merging
153                 // deprecated_since and its reason.
154                 if let Some(parent_stab) = self.parent_stab {
155                     if parent_stab.rustc_depr.is_some() && stab.rustc_depr.is_none() {
156                         stab.rustc_depr = parent_stab.rustc_depr.clone()
157                     }
158                 }
159
160                 let stab = self.tcx.intern_stability(stab);
161
162                 // Check if deprecated_since < stable_since. If it is,
163                 // this is *almost surely* an accident.
164                 if let (&Some(attr::RustcDeprecation {since: dep_since, ..}),
165                         &attr::Stable {since: stab_since}) = (&stab.rustc_depr, &stab.level) {
166                     // Explicit version of iter::order::lt to handle parse errors properly
167                     for (dep_v, stab_v) in dep_since.as_str()
168                                                     .split('.')
169                                                     .zip(stab_since.as_str().split('.'))
170                     {
171                         if let (Ok(dep_v), Ok(stab_v)) = (dep_v.parse::<u64>(), stab_v.parse()) {
172                             match dep_v.cmp(&stab_v) {
173                                 Ordering::Less => {
174                                     self.tcx.sess.span_err(item_sp, "An API can't be stabilized \
175                                                                      after it is deprecated");
176                                     break
177                                 }
178                                 Ordering::Equal => continue,
179                                 Ordering::Greater => break,
180                             }
181                         } else {
182                             // Act like it isn't less because the question is now nonsensical,
183                             // and this makes us not do anything else interesting.
184                             self.tcx.sess.span_err(item_sp, "Invalid stability or deprecation \
185                                                              version found");
186                             break
187                         }
188                     }
189                 }
190
191                 let hir_id = self.tcx.hir.node_to_hir_id(id);
192                 self.index.stab_map.insert(hir_id, stab);
193
194                 let orig_parent_stab = replace(&mut self.parent_stab, Some(stab));
195                 visit_children(self);
196                 self.parent_stab = orig_parent_stab;
197             } else {
198                 debug!("annotate: not found, parent = {:?}", self.parent_stab);
199                 if let Some(stab) = self.parent_stab {
200                     if stab.level.is_unstable() {
201                         let hir_id = self.tcx.hir.node_to_hir_id(id);
202                         self.index.stab_map.insert(hir_id, stab);
203                     }
204                 }
205                 visit_children(self);
206             }
207         } else {
208             // Emit errors for non-staged-api crates.
209             for attr in attrs {
210                 let tag = attr.name();
211                 if tag == "unstable" || tag == "stable" || tag == "rustc_deprecated" {
212                     attr::mark_used(attr);
213                     self.tcx.sess.span_err(attr.span(), "stability attributes may not be used \
214                                                          outside of the standard library");
215                 }
216             }
217
218             // Propagate unstability.  This can happen even for non-staged-api crates in case
219             // -Zforce-unstable-if-unmarked is set.
220             if let Some(stab) = self.parent_stab {
221                 if stab.level.is_unstable() {
222                     let hir_id = self.tcx.hir.node_to_hir_id(id);
223                     self.index.stab_map.insert(hir_id, stab);
224                 }
225             }
226
227             if let Some(depr) = attr::find_deprecation(self.tcx.sess.diagnostic(), attrs, item_sp) {
228                 if kind == AnnotationKind::Prohibited {
229                     self.tcx.sess.span_err(item_sp, "This deprecation annotation is useless");
230                 }
231
232                 // `Deprecation` is just two pointers, no need to intern it
233                 let hir_id = self.tcx.hir.node_to_hir_id(id);
234                 let depr_entry = DeprecationEntry::local(depr, hir_id);
235                 self.index.depr_map.insert(hir_id, depr_entry.clone());
236
237                 let orig_parent_depr = replace(&mut self.parent_depr,
238                                                Some(depr_entry));
239                 visit_children(self);
240                 self.parent_depr = orig_parent_depr;
241             } else if let Some(parent_depr) = self.parent_depr.clone() {
242                 let hir_id = self.tcx.hir.node_to_hir_id(id);
243                 self.index.depr_map.insert(hir_id, parent_depr);
244                 visit_children(self);
245             } else {
246                 visit_children(self);
247             }
248         }
249     }
250 }
251
252 impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> {
253     /// Because stability levels are scoped lexically, we want to walk
254     /// nested items in the context of the outer item, so enable
255     /// deep-walking.
256     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
257         NestedVisitorMap::All(&self.tcx.hir)
258     }
259
260     fn visit_item(&mut self, i: &'tcx Item) {
261         let orig_in_trait_impl = self.in_trait_impl;
262         let mut kind = AnnotationKind::Required;
263         match i.node {
264             // Inherent impls and foreign modules serve only as containers for other items,
265             // they don't have their own stability. They still can be annotated as unstable
266             // and propagate this unstability to children, but this annotation is completely
267             // optional. They inherit stability from their parents when unannotated.
268             hir::ItemKind::Impl(.., None, _, _) | hir::ItemKind::ForeignMod(..) => {
269                 self.in_trait_impl = false;
270                 kind = AnnotationKind::Container;
271             }
272             hir::ItemKind::Impl(.., Some(_), _, _) => {
273                 self.in_trait_impl = true;
274             }
275             hir::ItemKind::Struct(ref sd, _) => {
276                 if !sd.is_struct() {
277                     self.annotate(sd.id(), &i.attrs, i.span, AnnotationKind::Required, |_| {})
278                 }
279             }
280             _ => {}
281         }
282
283         self.annotate(i.id, &i.attrs, i.span, kind, |v| {
284             intravisit::walk_item(v, i)
285         });
286         self.in_trait_impl = orig_in_trait_impl;
287     }
288
289     fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
290         self.annotate(ti.id, &ti.attrs, ti.span, AnnotationKind::Required, |v| {
291             intravisit::walk_trait_item(v, ti);
292         });
293     }
294
295     fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
296         let kind = if self.in_trait_impl {
297             AnnotationKind::Prohibited
298         } else {
299             AnnotationKind::Required
300         };
301         self.annotate(ii.id, &ii.attrs, ii.span, kind, |v| {
302             intravisit::walk_impl_item(v, ii);
303         });
304     }
305
306     fn visit_variant(&mut self, var: &'tcx Variant, g: &'tcx Generics, item_id: NodeId) {
307         self.annotate(var.node.data.id(), &var.node.attrs, var.span, AnnotationKind::Required, |v| {
308             intravisit::walk_variant(v, var, g, item_id);
309         })
310     }
311
312     fn visit_struct_field(&mut self, s: &'tcx StructField) {
313         self.annotate(s.id, &s.attrs, s.span, AnnotationKind::Required, |v| {
314             intravisit::walk_struct_field(v, s);
315         });
316     }
317
318     fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem) {
319         self.annotate(i.id, &i.attrs, i.span, AnnotationKind::Required, |v| {
320             intravisit::walk_foreign_item(v, i);
321         });
322     }
323
324     fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef) {
325         self.annotate(md.id, &md.attrs, md.span, AnnotationKind::Required, |_| {});
326     }
327 }
328
329 struct MissingStabilityAnnotations<'a, 'tcx: 'a> {
330     tcx: TyCtxt<'a, 'tcx, 'tcx>,
331     access_levels: &'a AccessLevels,
332 }
333
334 impl<'a, 'tcx: 'a> MissingStabilityAnnotations<'a, 'tcx> {
335     fn check_missing_stability(&self, id: NodeId, span: Span) {
336         let hir_id = self.tcx.hir.node_to_hir_id(id);
337         let stab = self.tcx.stability().local_stability(hir_id);
338         let is_error = !self.tcx.sess.opts.test &&
339                         stab.is_none() &&
340                         self.access_levels.is_reachable(id);
341         if is_error {
342             self.tcx.sess.span_err(span, "This node does not have a stability attribute");
343         }
344     }
345 }
346
347 impl<'a, 'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'a, 'tcx> {
348     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
349         NestedVisitorMap::OnlyBodies(&self.tcx.hir)
350     }
351
352     fn visit_item(&mut self, i: &'tcx Item) {
353         match i.node {
354             // Inherent impls and foreign modules serve only as containers for other items,
355             // they don't have their own stability. They still can be annotated as unstable
356             // and propagate this unstability to children, but this annotation is completely
357             // optional. They inherit stability from their parents when unannotated.
358             hir::ItemKind::Impl(.., None, _, _) | hir::ItemKind::ForeignMod(..) => {}
359
360             _ => self.check_missing_stability(i.id, i.span)
361         }
362
363         intravisit::walk_item(self, i)
364     }
365
366     fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
367         self.check_missing_stability(ti.id, ti.span);
368         intravisit::walk_trait_item(self, ti);
369     }
370
371     fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
372         let impl_def_id = self.tcx.hir.local_def_id(self.tcx.hir.get_parent(ii.id));
373         if self.tcx.impl_trait_ref(impl_def_id).is_none() {
374             self.check_missing_stability(ii.id, ii.span);
375         }
376         intravisit::walk_impl_item(self, ii);
377     }
378
379     fn visit_variant(&mut self, var: &'tcx Variant, g: &'tcx Generics, item_id: NodeId) {
380         self.check_missing_stability(var.node.data.id(), var.span);
381         intravisit::walk_variant(self, var, g, item_id);
382     }
383
384     fn visit_struct_field(&mut self, s: &'tcx StructField) {
385         self.check_missing_stability(s.id, s.span);
386         intravisit::walk_struct_field(self, s);
387     }
388
389     fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem) {
390         self.check_missing_stability(i.id, i.span);
391         intravisit::walk_foreign_item(self, i);
392     }
393
394     fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef) {
395         self.check_missing_stability(md.id, md.span);
396     }
397 }
398
399 impl<'a, 'tcx> Index<'tcx> {
400     pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Index<'tcx> {
401         let is_staged_api =
402             tcx.sess.opts.debugging_opts.force_unstable_if_unmarked ||
403             tcx.features().staged_api;
404         let mut staged_api = FxHashMap();
405         staged_api.insert(LOCAL_CRATE, is_staged_api);
406         let mut index = Index {
407             staged_api,
408             stab_map: FxHashMap(),
409             depr_map: FxHashMap(),
410             active_features: FxHashSet(),
411         };
412
413         let ref active_lib_features = tcx.features().declared_lib_features;
414
415         // Put the active features into a map for quick lookup
416         index.active_features = active_lib_features.iter().map(|&(ref s, _)| s.clone()).collect();
417
418         {
419             let krate = tcx.hir.krate();
420             let mut annotator = Annotator {
421                 tcx,
422                 index: &mut index,
423                 parent_stab: None,
424                 parent_depr: None,
425                 in_trait_impl: false,
426             };
427
428             // If the `-Z force-unstable-if-unmarked` flag is passed then we provide
429             // a parent stability annotation which indicates that this is private
430             // with the `rustc_private` feature. This is intended for use when
431             // compiling librustc crates themselves so we can leverage crates.io
432             // while maintaining the invariant that all sysroot crates are unstable
433             // by default and are unable to be used.
434             if tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
435                 let reason = "this crate is being loaded from the sysroot, an \
436                               unstable location; did you mean to load this crate \
437                               from crates.io via `Cargo.toml` instead?";
438                 let stability = tcx.intern_stability(Stability {
439                     level: attr::StabilityLevel::Unstable {
440                         reason: Some(Symbol::intern(reason)),
441                         issue: 27812,
442                     },
443                     feature: Symbol::intern("rustc_private"),
444                     rustc_depr: None,
445                     const_stability: None,
446                     promotable: false,
447                 });
448                 annotator.parent_stab = Some(stability);
449             }
450
451             annotator.annotate(ast::CRATE_NODE_ID,
452                                &krate.attrs,
453                                krate.span,
454                                AnnotationKind::Required,
455                                |v| intravisit::walk_crate(v, krate));
456         }
457         return index
458     }
459
460     pub fn local_stability(&self, id: HirId) -> Option<&'tcx Stability> {
461         self.stab_map.get(&id).cloned()
462     }
463
464     pub fn local_deprecation_entry(&self, id: HirId) -> Option<DeprecationEntry> {
465         self.depr_map.get(&id).cloned()
466     }
467 }
468
469 /// Cross-references the feature names of unstable APIs with enabled
470 /// features and possibly prints errors.
471 pub fn check_unstable_api_usage<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
472     let mut checker = Checker { tcx: tcx };
473     tcx.hir.krate().visit_all_item_likes(&mut checker.as_deep_visitor());
474 }
475
476 /// Check whether an item marked with `deprecated(since="X")` is currently
477 /// deprecated (i.e. whether X is not greater than the current rustc version).
478 pub fn deprecation_in_effect(since: &str) -> bool {
479     fn parse_version(ver: &str) -> Vec<u32> {
480         // We ignore non-integer components of the version (e.g. "nightly").
481         ver.split(|c| c == '.' || c == '-').flat_map(|s| s.parse()).collect()
482     }
483
484     if let Some(rustc) = option_env!("CFG_RELEASE") {
485         let since: Vec<u32> = parse_version(since);
486         let rustc: Vec<u32> = parse_version(rustc);
487         // We simply treat invalid `since` attributes as relating to a previous
488         // Rust version, thus always displaying the warning.
489         if since.len() != 3 {
490             return true;
491         }
492         since <= rustc
493     } else {
494         // By default, a deprecation warning applies to
495         // the current version of the compiler.
496         true
497     }
498 }
499
500 struct Checker<'a, 'tcx: 'a> {
501     tcx: TyCtxt<'a, 'tcx, 'tcx>,
502 }
503
504 /// Result of `TyCtxt::eval_stability`.
505 pub enum EvalResult {
506     /// We can use the item because it is stable or we provided the
507     /// corresponding feature gate.
508     Allow,
509     /// We cannot use the item because it is unstable and we did not provide the
510     /// corresponding feature gate.
511     Deny {
512         feature: Symbol,
513         reason: Option<Symbol>,
514         issue: u32,
515     },
516     /// The item does not have the `#[stable]` or `#[unstable]` marker assigned.
517     Unmarked,
518 }
519
520 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
521     // (See issue #38412)
522     fn skip_stability_check_due_to_privacy(self, mut def_id: DefId) -> bool {
523         // Check if `def_id` is a trait method.
524         match self.describe_def(def_id) {
525             Some(Def::Method(_)) |
526             Some(Def::AssociatedTy(_)) |
527             Some(Def::AssociatedConst(_)) => {
528                 if let ty::TraitContainer(trait_def_id) = self.associated_item(def_id).container {
529                     // Trait methods do not declare visibility (even
530                     // for visibility info in cstore). Use containing
531                     // trait instead, so methods of pub traits are
532                     // themselves considered pub.
533                     def_id = trait_def_id;
534                 }
535             }
536             _ => {}
537         }
538
539         let visibility = self.visibility(def_id);
540
541         match visibility {
542             // must check stability for pub items.
543             ty::Visibility::Public => false,
544
545             // these are not visible outside crate; therefore
546             // stability markers are irrelevant, if even present.
547             ty::Visibility::Restricted(..) |
548             ty::Visibility::Invisible => true,
549         }
550     }
551
552     /// Evaluates the stability of an item.
553     ///
554     /// Returns `EvalResult::Allow` if the item is stable, or unstable but the corresponding
555     /// `#![feature]` has been provided. Returns `EvalResult::Deny` which describes the offending
556     /// unstable feature otherwise.
557     ///
558     /// If `id` is `Some(_)`, this function will also check if the item at `def_id` has been
559     /// deprecated. If the item is indeed deprecated, we will emit a deprecation lint attached to
560     /// `id`.
561     pub fn eval_stability(self, def_id: DefId, id: Option<NodeId>, span: Span) -> EvalResult {
562         if span.allows_unstable() {
563             debug!("stability: skipping span={:?} since it is internal", span);
564             return EvalResult::Allow;
565         }
566
567         let lint_deprecated = |def_id: DefId, id: NodeId, note: Option<Symbol>| {
568             let path = self.item_path_str(def_id);
569
570             let msg = if let Some(note) = note {
571                 format!("use of deprecated item '{}': {}", path, note)
572             } else {
573                 format!("use of deprecated item '{}'", path)
574             };
575
576             self.lint_node(lint::builtin::DEPRECATED, id, span, &msg);
577             if id == ast::DUMMY_NODE_ID {
578                 span_bug!(span, "emitted a deprecated lint with dummy node id: {:?}", def_id);
579             }
580         };
581
582         // Deprecated attributes apply in-crate and cross-crate.
583         if let Some(id) = id {
584             if let Some(depr_entry) = self.lookup_deprecation_entry(def_id) {
585                 // If the deprecation is scheduled for a future Rust
586                 // version, then we should display no warning message.
587                 let deprecated_in_future_version = if let Some(sym) = depr_entry.attr.since {
588                     let since = sym.as_str();
589                     !deprecation_in_effect(&since)
590                 } else {
591                     false
592                 };
593
594                 let parent_def_id = self.hir.local_def_id(self.hir.get_parent(id));
595                 let skip = deprecated_in_future_version ||
596                            self.lookup_deprecation_entry(parent_def_id)
597                                .map_or(false, |parent_depr| parent_depr.same_origin(&depr_entry));
598                 if !skip {
599                     lint_deprecated(def_id, id, depr_entry.attr.note);
600                 }
601             };
602         }
603
604         let is_staged_api = self.lookup_stability(DefId {
605             index: CRATE_DEF_INDEX,
606             ..def_id
607         }).is_some();
608         if !is_staged_api {
609             return EvalResult::Allow;
610         }
611
612         let stability = self.lookup_stability(def_id);
613         debug!("stability: \
614                 inspecting def_id={:?} span={:?} of stability={:?}", def_id, span, stability);
615
616         if let Some(&Stability{rustc_depr: Some(attr::RustcDeprecation { reason, since }), ..})
617                 = stability {
618             if let Some(id) = id {
619                 if deprecation_in_effect(&since.as_str()) {
620                     lint_deprecated(def_id, id, Some(reason));
621                 }
622             }
623         }
624
625         // Only the cross-crate scenario matters when checking unstable APIs
626         let cross_crate = !def_id.is_local();
627         if !cross_crate {
628             return EvalResult::Allow;
629         }
630
631         // Issue 38412: private items lack stability markers.
632         if self.skip_stability_check_due_to_privacy(def_id) {
633             return EvalResult::Allow;
634         }
635
636         match stability {
637             Some(&Stability { level: attr::Unstable { reason, issue }, feature, .. }) => {
638                 if self.stability().active_features.contains(&feature) {
639                     return EvalResult::Allow;
640                 }
641
642                 // When we're compiling the compiler itself we may pull in
643                 // crates from crates.io, but those crates may depend on other
644                 // crates also pulled in from crates.io. We want to ideally be
645                 // able to compile everything without requiring upstream
646                 // modifications, so in the case that this looks like a
647                 // rustc_private crate (e.g. a compiler crate) and we also have
648                 // the `-Z force-unstable-if-unmarked` flag present (we're
649                 // compiling a compiler crate), then let this missing feature
650                 // annotation slide.
651                 if feature == "rustc_private" && issue == 27812 {
652                     if self.sess.opts.debugging_opts.force_unstable_if_unmarked {
653                         return EvalResult::Allow;
654                     }
655                 }
656
657                 EvalResult::Deny { feature, reason, issue }
658             }
659             Some(_) => {
660                 // Stable APIs are always ok to call and deprecated APIs are
661                 // handled by the lint emitting logic above.
662                 EvalResult::Allow
663             }
664             None => {
665                 EvalResult::Unmarked
666             }
667         }
668     }
669
670     /// Checks if an item is stable or error out.
671     ///
672     /// If the item defined by `def_id` is unstable and the corresponding `#![feature]` does not
673     /// exist, emits an error.
674     ///
675     /// Additionally, this function will also check if the item is deprecated. If so, and `id` is
676     /// not `None`, a deprecated lint attached to `id` will be emitted.
677     pub fn check_stability(self, def_id: DefId, id: Option<NodeId>, span: Span) {
678         match self.eval_stability(def_id, id, span) {
679             EvalResult::Allow => {}
680             EvalResult::Deny { feature, reason, issue } => {
681                 let msg = match reason {
682                     Some(r) => format!("use of unstable library feature '{}': {}", feature, r),
683                     None => format!("use of unstable library feature '{}'", &feature)
684                 };
685
686                 let msp: MultiSpan = span.into();
687                 let cm = &self.sess.parse_sess.source_map();
688                 let span_key = msp.primary_span().and_then(|sp: Span|
689                     if !sp.is_dummy() {
690                         let file = cm.lookup_char_pos(sp.lo()).file;
691                         if file.name.is_macros() {
692                             None
693                         } else {
694                             Some(span)
695                         }
696                     } else {
697                         None
698                     }
699                 );
700
701                 let error_id = (DiagnosticMessageId::StabilityId(issue), span_key, msg.clone());
702                 let fresh = self.sess.one_time_diagnostics.borrow_mut().insert(error_id);
703                 if fresh {
704                     emit_feature_err(&self.sess.parse_sess, &feature.as_str(), span,
705                                      GateIssue::Library(Some(issue)), &msg);
706                 }
707             }
708             EvalResult::Unmarked => {
709                 span_bug!(span, "encountered unmarked API: {:?}", def_id);
710             }
711         }
712     }
713 }
714
715 impl<'a, 'tcx> Visitor<'tcx> for Checker<'a, 'tcx> {
716     /// Because stability levels are scoped lexically, we want to walk
717     /// nested items in the context of the outer item, so enable
718     /// deep-walking.
719     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
720         NestedVisitorMap::OnlyBodies(&self.tcx.hir)
721     }
722
723     fn visit_item(&mut self, item: &'tcx hir::Item) {
724         match item.node {
725             hir::ItemKind::ExternCrate(_) => {
726                 // compiler-generated `extern crate` items have a dummy span.
727                 if item.span.is_dummy() { return }
728
729                 let def_id = self.tcx.hir.local_def_id(item.id);
730                 let cnum = match self.tcx.extern_mod_stmt_cnum(def_id) {
731                     Some(cnum) => cnum,
732                     None => return,
733                 };
734                 let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
735                 self.tcx.check_stability(def_id, Some(item.id), item.span);
736             }
737
738             // For implementations of traits, check the stability of each item
739             // individually as it's possible to have a stable trait with unstable
740             // items.
741             hir::ItemKind::Impl(.., Some(ref t), _, ref impl_item_refs) => {
742                 if let Def::Trait(trait_did) = t.path.def {
743                     for impl_item_ref in impl_item_refs {
744                         let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
745                         let trait_item_def_id = self.tcx.associated_items(trait_did)
746                             .find(|item| item.ident.name == impl_item.ident.name)
747                             .map(|item| item.def_id);
748                         if let Some(def_id) = trait_item_def_id {
749                             // Pass `None` to skip deprecation warnings.
750                             self.tcx.check_stability(def_id, None, impl_item.span);
751                         }
752                     }
753                 }
754             }
755
756             // There's no good place to insert stability check for non-Copy unions,
757             // so semi-randomly perform it here in stability.rs
758             hir::ItemKind::Union(..) if !self.tcx.features().untagged_unions => {
759                 let def_id = self.tcx.hir.local_def_id(item.id);
760                 let adt_def = self.tcx.adt_def(def_id);
761                 let ty = self.tcx.type_of(def_id);
762
763                 if adt_def.has_dtor(self.tcx) {
764                     emit_feature_err(&self.tcx.sess.parse_sess,
765                                      "untagged_unions", item.span, GateIssue::Language,
766                                      "unions with `Drop` implementations are unstable");
767                 } else {
768                     let param_env = self.tcx.param_env(def_id);
769                     if !param_env.can_type_implement_copy(self.tcx, ty).is_ok() {
770                         emit_feature_err(&self.tcx.sess.parse_sess,
771                                          "untagged_unions", item.span, GateIssue::Language,
772                                          "unions with non-`Copy` fields are unstable");
773                     }
774                 }
775             }
776
777             _ => (/* pass */)
778         }
779         intravisit::walk_item(self, item);
780     }
781
782     fn visit_path(&mut self, path: &'tcx hir::Path, id: hir::HirId) {
783         let id = self.tcx.hir.hir_to_node_id(id);
784         match path.def {
785             Def::Local(..) | Def::Upvar(..) | Def::SelfCtor(..) |
786             Def::PrimTy(..) | Def::SelfTy(..) | Def::Err => {}
787             _ => self.tcx.check_stability(path.def.def_id(), Some(id), path.span)
788         }
789         intravisit::walk_path(self, path)
790     }
791 }
792
793 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
794     pub fn lookup_deprecation(self, id: DefId) -> Option<Deprecation> {
795         self.lookup_deprecation_entry(id).map(|depr| depr.attr)
796     }
797 }
798
799 /// Given the list of enabled features that were not language features (i.e. that
800 /// were expected to be library features), and the list of features used from
801 /// libraries, identify activated features that don't exist and error about them.
802 pub fn check_unused_or_stable_features<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
803     let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
804
805     if tcx.stability().staged_api[&LOCAL_CRATE] {
806         let krate = tcx.hir.krate();
807         let mut missing = MissingStabilityAnnotations {
808             tcx,
809             access_levels,
810         };
811         missing.check_missing_stability(ast::CRATE_NODE_ID, krate.span);
812         intravisit::walk_crate(&mut missing, krate);
813         krate.visit_all_item_likes(&mut missing.as_deep_visitor());
814     }
815
816     let declared_lang_features = &tcx.features().declared_lang_features;
817     let mut lang_features = FxHashSet();
818     for &(feature, span, since) in declared_lang_features {
819         if let Some(since) = since {
820             // Warn if the user has enabled an already-stable lang feature.
821             unnecessary_stable_feature_lint(tcx, span, feature, since);
822         }
823         if lang_features.contains(&feature) {
824             // Warn if the user enables a lang feature multiple times.
825             duplicate_feature_err(tcx.sess, span, feature);
826         }
827         lang_features.insert(feature);
828     }
829
830     let declared_lib_features = &tcx.features().declared_lib_features;
831     let mut remaining_lib_features = FxHashMap();
832     for (feature, span) in declared_lib_features {
833         if remaining_lib_features.contains_key(&feature) {
834             // Warn if the user enables a lib feature multiple times.
835             duplicate_feature_err(tcx.sess, *span, *feature);
836         }
837         remaining_lib_features.insert(feature, span.clone());
838     }
839     // `stdbuild` has special handling for `libc`, so we need to
840     // recognise the feature when building std.
841     // Likewise, libtest is handled specially, so `test` isn't
842     // available as we'd like it to be.
843     // FIXME: only remove `libc` when `stdbuild` is active.
844     // FIXME: remove special casing for `test`.
845     remaining_lib_features.remove(&Symbol::intern("libc"));
846     remaining_lib_features.remove(&Symbol::intern("test"));
847
848     let check_features =
849         |remaining_lib_features: &mut FxHashMap<_, _>, defined_features: &Vec<_>| {
850             for &(feature, since) in defined_features {
851                 if let Some(since) = since {
852                     if let Some(span) = remaining_lib_features.get(&feature) {
853                         // Warn if the user has enabled an already-stable lib feature.
854                         unnecessary_stable_feature_lint(tcx, *span, feature, since);
855                     }
856                 }
857                 remaining_lib_features.remove(&feature);
858                 if remaining_lib_features.is_empty() {
859                     break;
860                 }
861             }
862         };
863
864     // We always collect the lib features declared in the current crate, even if there are
865     // no unknown features, because the collection also does feature attribute validation.
866     let local_defined_features = tcx.lib_features().to_vec();
867     if !remaining_lib_features.is_empty() {
868         check_features(&mut remaining_lib_features, &local_defined_features);
869
870         for &cnum in &*tcx.crates() {
871             if remaining_lib_features.is_empty() {
872                 break;
873             }
874             check_features(&mut remaining_lib_features, &tcx.defined_lib_features(cnum));
875         }
876     }
877
878     for (feature, span) in remaining_lib_features {
879         struct_span_err!(tcx.sess, span, E0635, "unknown feature `{}`", feature).emit();
880     }
881
882     // FIXME(#44232): the `used_features` table no longer exists, so we
883     // don't lint about unused features. We should reenable this one day!
884 }
885
886 fn unnecessary_stable_feature_lint<'a, 'tcx>(
887     tcx: TyCtxt<'a, 'tcx, 'tcx>,
888     span: Span,
889     feature: Symbol,
890     since: Symbol
891 ) {
892     tcx.lint_node(lint::builtin::STABLE_FEATURES,
893         ast::CRATE_NODE_ID,
894         span,
895         &format!("the feature `{}` has been stable since {} and no longer requires \
896                   an attribute to enable", feature, since));
897 }
898
899 fn duplicate_feature_err(sess: &Session, span: Span, feature: Symbol) {
900     struct_span_err!(sess, span, E0636, "the feature `{}` has already been declared", feature)
901         .emit();
902 }