]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/lib_features.rs
Various minor/cosmetic improvements to code
[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;
21 use hir::intravisit::{self, NestedVisitorMap, Visitor};
22 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
23 use errors::DiagnosticId;
24
25 pub struct LibFeatures {
26     // A map from feature to stabilisation version.
27     pub stable: FxHashMap<Symbol, Symbol>,
28     pub unstable: FxHashSet<Symbol>,
29 }
30
31 impl LibFeatures {
32     fn new() -> LibFeatures {
33         LibFeatures {
34             stable: Default::default(),
35             unstable: Default::default(),
36         }
37     }
38
39     pub fn to_vec(&self) -> Vec<(Symbol, Option<Symbol>)> {
40         let mut all_features: Vec<_> = self.stable.iter().map(|(f, s)| (*f, Some(*s)))
41             .chain(self.unstable.iter().map(|f| (*f, None)))
42             .collect();
43         all_features.sort_unstable_by_key(|f| f.0.as_str());
44         all_features
45     }
46 }
47
48 pub struct LibFeatureCollector<'a, 'tcx: 'a> {
49     tcx: TyCtxt<'a, 'tcx, 'tcx>,
50     lib_features: LibFeatures,
51 }
52
53 impl<'a, 'tcx> LibFeatureCollector<'a, 'tcx> {
54     fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LibFeatureCollector<'a, 'tcx> {
55         LibFeatureCollector {
56             tcx,
57             lib_features: LibFeatures::new(),
58         }
59     }
60
61     fn extract(&self, attr: &Attribute) -> Option<(Symbol, Option<Symbol>, Span)> {
62         let stab_attrs = vec!["stable", "unstable", "rustc_const_unstable"];
63
64         // Find a stability attribute (i.e., `#[stable (..)]`, `#[unstable (..)]`,
65         // `#[rustc_const_unstable (..)]`).
66         if let Some(stab_attr) = stab_attrs.iter().find(|stab_attr| {
67             attr.check_name(stab_attr)
68         }) {
69             let meta_item = attr.meta();
70             if let Some(MetaItem { node: MetaItemKind::List(ref metas), .. }) = meta_item {
71                 let mut feature = None;
72                 let mut since = None;
73                 for meta in metas {
74                     if let Some(mi) = meta.meta_item() {
75                         // Find the `feature = ".."` meta-item.
76                         match (&*mi.name().as_str(), mi.value_str()) {
77                             ("feature", val) => feature = val,
78                             ("since", val) => since = val,
79                             _ => {}
80                         }
81                     }
82                 }
83                 if let Some(feature) = feature {
84                     // This additional check for stability is to make sure we
85                     // don't emit additional, irrelevant errors for malformed
86                     // attributes.
87                     if *stab_attr != "stable" || since.is_some() {
88                         return Some((feature, since, attr.span));
89                     }
90                 }
91                 // We need to iterate over the other attributes, because
92                 // `rustc_const_unstable` is not mutually exclusive with
93                 // the other stability attributes, so we can't just `break`
94                 // here.
95             }
96         }
97
98         None
99     }
100
101     fn collect_feature(&mut self, feature: Symbol, since: Option<Symbol>, span: Span) {
102         let already_in_stable = self.lib_features.stable.contains_key(&feature);
103         let already_in_unstable = self.lib_features.unstable.contains(&feature);
104
105         match (since, already_in_stable, already_in_unstable) {
106             (Some(since), _, false) => {
107                 if let Some(prev_since) = self.lib_features.stable.get(&feature) {
108                     if *prev_since != since {
109                         let msg = format!(
110                             "feature `{}` is declared stable since {}, \
111                              but was previously declared stable since {}",
112                             feature,
113                             since,
114                             prev_since,
115                         );
116                         self.tcx.sess.struct_span_err_with_code(span, &msg,
117                             DiagnosticId::Error("E0711".into())).emit();
118                         return;
119                     }
120                 }
121
122                 self.lib_features.stable.insert(feature, since);
123             }
124             (None, false, _) => {
125                 self.lib_features.unstable.insert(feature);
126             }
127             (Some(_), _, true) | (None, true, _) => {
128                 let msg = format!(
129                     "feature `{}` is declared {}, but was previously declared {}",
130                     feature,
131                     if since.is_some() { "stable" } else { "unstable" },
132                     if since.is_none() { "stable" } else { "unstable" },
133                 );
134                 self.tcx.sess.struct_span_err_with_code(span, &msg,
135                     DiagnosticId::Error("E0711".into())).emit();
136             }
137         }
138     }
139 }
140
141 impl<'a, 'tcx> Visitor<'tcx> for LibFeatureCollector<'a, 'tcx> {
142     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
143         NestedVisitorMap::All(&self.tcx.hir())
144     }
145
146     fn visit_attribute(&mut self, attr: &'tcx Attribute) {
147         if let Some((feature, stable, span)) = self.extract(attr) {
148             self.collect_feature(feature, stable, span);
149         }
150     }
151 }
152
153 pub fn collect<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LibFeatures {
154     let mut collector = LibFeatureCollector::new(tcx);
155     intravisit::walk_crate(&mut collector, tcx.hir().krate());
156     collector.lib_features
157 }