]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/lib_features.rs
a1abfb704ec15fa692677d94fc910ad8f573bbf7
[rust.git] / src / librustc / middle / lib_features.rs
1 // Copyright 2018 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 // Detecting lib features (i.e. features that are not lang features).
12 //
13 // These are declared using stability attributes (e.g. `#[stable (..)]`
14 // and `#[unstable (..)]`), but are not declared in one single location
15 // (unlike lang features), which means we need to collect them instead.
16
17 use ty::TyCtxt;
18 use syntax::symbol::Symbol;
19 use syntax::ast::{Attribute, MetaItem, MetaItemKind};
20 use syntax_pos::{Span, DUMMY_SP};
21 use hir;
22 use hir::itemlikevisit::ItemLikeVisitor;
23 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
24 use errors::DiagnosticId;
25
26 pub struct LibFeatures {
27     // A map from feature to stabilisation version.
28     pub stable: FxHashMap<Symbol, Symbol>,
29     pub unstable: FxHashSet<Symbol>,
30 }
31
32 impl LibFeatures {
33     fn new() -> LibFeatures {
34         LibFeatures {
35             stable: FxHashMap(),
36             unstable: FxHashSet(),
37         }
38     }
39
40     pub fn iter(&self) -> Vec<(Symbol, Option<Symbol>)> {
41         self.stable.iter().map(|(f, s)| (*f, Some(*s)))
42             .chain(self.unstable.iter().map(|f| (*f, None)))
43             .collect()
44     }
45 }
46
47 pub struct LibFeatureCollector<'a, 'tcx: 'a> {
48     tcx: TyCtxt<'a, 'tcx, 'tcx>,
49     lib_features: LibFeatures,
50 }
51
52 impl<'a, 'tcx> LibFeatureCollector<'a, 'tcx> {
53     fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LibFeatureCollector<'a, 'tcx> {
54         LibFeatureCollector {
55             tcx,
56             lib_features: LibFeatures::new(),
57         }
58     }
59
60     fn extract(&self, attrs: &[Attribute]) -> Vec<(Symbol, Option<Symbol>, Span)> {
61         let stab_attrs = vec!["stable", "unstable", "rustc_const_unstable"];
62         let mut features = vec![];
63
64         for attr in attrs {
65             // FIXME(varkor): the stability attribute might be behind a `#[cfg]` attribute.
66
67             // Find a stability attribute (i.e. `#[stable (..)]`, `#[unstable (..)]`,
68             // `#[rustc_const_unstable (..)]`).
69             if let Some(stab_attr) = stab_attrs.iter().find(|stab_attr| {
70                 attr.check_name(stab_attr)
71             }) {
72                 let meta_item = attr.meta();
73                 if let Some(MetaItem { node: MetaItemKind::List(ref metas), .. }) = meta_item {
74                     let mut feature = None;
75                     let mut since = None;
76                     for meta in metas {
77                         if let Some(mi) = meta.meta_item() {
78                             // Find the `feature = ".."` meta-item.
79                             match (&*mi.name().as_str(), mi.value_str()) {
80                                 ("feature", val) => feature = val,
81                                 ("since", val) => since = val,
82                                 _ => {}
83                             }
84                         }
85                     }
86                     if let Some(feature) = feature {
87                         // This additional check for stability is to make sure we
88                         // don't emit additional, irrelevant errors for malformed
89                         // attributes.
90                         if *stab_attr != "stable" || since.is_some() {
91                             features.push((feature, since, attr.span));
92                         }
93                     }
94                     // We need to iterate over the other attributes, because
95                     // `rustc_const_unstable` is not mutually exclusive with
96                     // the other stability attributes, so we can't just `break`
97                     // here.
98                 }
99             }
100         }
101
102         features
103     }
104
105     fn collect_feature(&mut self, feature: Symbol, since: Option<Symbol>, span: Span) {
106         let already_in_stable = self.lib_features.stable.contains_key(&feature);
107         let already_in_unstable = self.lib_features.unstable.contains(&feature);
108
109         match (since, already_in_stable, already_in_unstable) {
110             (Some(since), _, false) => {
111                 if let Some(prev_since) = self.lib_features.stable.get(&feature) {
112                     if *prev_since != since {
113                         let msg = format!(
114                             "feature `{}` is declared stable since {}, \
115                              but was previously declared stable since {}",
116                             feature,
117                             since,
118                             prev_since,
119                         );
120                         self.tcx.sess.struct_span_err_with_code(span, &msg,
121                             DiagnosticId::Error("E0711".into())).emit();
122                         return;
123                     }
124                 }
125
126                 self.lib_features.stable.insert(feature, since);
127             }
128             (None, false, _) => {
129                 self.lib_features.unstable.insert(feature);
130             }
131             (Some(_), _, true) | (None, true, _) => {
132                 let msg = format!(
133                     "feature `{}` is declared {}, but was previously declared {}",
134                     feature,
135                     if since.is_some() { "stable"} else { "unstable" },
136                     if since.is_none() { "stable"} else { "unstable" },
137                 );
138                 self.tcx.sess.struct_span_err_with_code(span, &msg,
139                     DiagnosticId::Error("E0711".into())).emit();
140             }
141         }
142     }
143
144     fn collect_from_attrs(&mut self, attrs: &[Attribute]) {
145         for (feature, stable, span) in self.extract(attrs) {
146             self.collect_feature(feature, stable, span);
147         }
148     }
149 }
150
151 impl<'a, 'v, 'tcx> ItemLikeVisitor<'v> for LibFeatureCollector<'a, 'tcx> {
152     fn visit_item(&mut self, item: &hir::Item) {
153         self.collect_from_attrs(&item.attrs);
154     }
155
156     fn visit_trait_item(&mut self, trait_item: &hir::TraitItem) {
157         self.collect_from_attrs(&trait_item.attrs);
158     }
159
160     fn visit_impl_item(&mut self, impl_item: &hir::ImplItem) {
161         self.collect_from_attrs(&impl_item.attrs);
162     }
163 }
164
165 pub fn collect<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LibFeatures {
166     let mut collector = LibFeatureCollector::new(tcx);
167     for &cnum in tcx.crates().iter() {
168         for &(feature, since) in tcx.defined_lib_features(cnum).iter() {
169             collector.collect_feature(feature, since, DUMMY_SP);
170         }
171     }
172     collector.collect_from_attrs(&tcx.hir.krate().attrs);
173     tcx.hir.krate().visit_all_item_likes(&mut collector);
174     collector.lib_features
175 }