1 // Copyright 2012-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.
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.
12 use feature_gate::{feature_err, EXPLAIN_STMT_ATTR_SYNTAX, Features, get_features, GateIssue};
19 use util::small_vector::SmallVector;
21 /// A folder that strips out items that do not belong in the current configuration.
22 pub struct StripUnconfigured<'a> {
23 pub should_test: bool,
24 pub sess: &'a ParseSess,
25 pub features: Option<&'a Features>,
28 // `cfg_attr`-process the crate's attributes and compute the crate's features.
29 pub fn features(mut krate: ast::Crate, sess: &ParseSess, should_test: bool)
30 -> (ast::Crate, Features) {
33 let mut strip_unconfigured = StripUnconfigured {
34 should_test: should_test,
39 let unconfigured_attrs = krate.attrs.clone();
40 let err_count = sess.span_diagnostic.err_count();
41 if let Some(attrs) = strip_unconfigured.configure(krate.attrs) {
43 } else { // the entire crate is unconfigured
44 krate.attrs = Vec::new();
45 krate.module.items = Vec::new();
46 return (krate, Features::new());
49 features = get_features(&sess.span_diagnostic, &krate.attrs);
51 // Avoid reconfiguring malformed `cfg_attr`s
52 if err_count == sess.span_diagnostic.err_count() {
53 strip_unconfigured.features = Some(&features);
54 strip_unconfigured.configure(unconfigured_attrs);
61 macro_rules! configure {
62 ($this:ident, $node:ident) => {
63 match $this.configure($node) {
65 None => return Default::default(),
70 impl<'a> StripUnconfigured<'a> {
71 pub fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
72 let node = self.process_cfg_attrs(node);
73 if self.in_cfg(node.attrs()) { Some(node) } else { None }
76 pub fn process_cfg_attrs<T: HasAttrs>(&mut self, node: T) -> T {
77 node.map_attrs(|attrs| {
78 attrs.into_iter().filter_map(|attr| self.process_cfg_attr(attr)).collect()
82 fn process_cfg_attr(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> {
83 if !attr.check_name("cfg_attr") {
87 let attr_list = match attr.meta_item_list() {
88 Some(attr_list) => attr_list,
90 let msg = "expected `#[cfg_attr(<cfg pattern>, <attr>)]`";
91 self.sess.span_diagnostic.span_err(attr.span, msg);
96 let (cfg, mi) = match (attr_list.len(), attr_list.get(0), attr_list.get(1)) {
97 (2, Some(cfg), Some(mi)) => (cfg, mi),
99 let msg = "expected `#[cfg_attr(<cfg pattern>, <attr>)]`";
100 self.sess.span_diagnostic.span_err(attr.span, msg);
105 use attr::cfg_matches;
106 match (cfg.meta_item(), mi.meta_item()) {
107 (Some(cfg), Some(mi)) =>
108 if cfg_matches(&cfg, self.sess, self.features) {
109 self.process_cfg_attr(ast::Attribute {
110 id: attr::mk_attr_id(),
113 is_sugared_doc: false,
120 let msg = "unexpected literal(s) in `#[cfg_attr(<cfg pattern>, <attr>)]`";
121 self.sess.span_diagnostic.span_err(attr.span, msg);
127 // Determine if a node with the given attributes should be included in this configuation.
128 pub fn in_cfg(&mut self, attrs: &[ast::Attribute]) -> bool {
129 attrs.iter().all(|attr| {
130 // When not compiling with --test we should not compile the #[test] functions
131 if !self.should_test && is_test_or_bench(attr) {
135 let mis = match attr.value.node {
136 ast::MetaItemKind::List(ref mis) if is_cfg(&attr) => mis,
141 self.sess.span_diagnostic.span_err(attr.span, "expected 1 cfg-pattern");
145 if !mis[0].is_meta_item() {
146 self.sess.span_diagnostic.span_err(mis[0].span, "unexpected literal");
150 attr::cfg_matches(mis[0].meta_item().unwrap(), self.sess, self.features)
154 // Visit attributes on expression and statements (but not attributes on items in blocks).
155 fn visit_expr_attrs(&mut self, attrs: &[ast::Attribute]) {
156 // flag the offending attributes
157 for attr in attrs.iter() {
158 if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) {
159 let mut err = feature_err(&self.sess,
160 "stmt_expr_attributes",
163 EXPLAIN_STMT_ATTR_SYNTAX);
164 if attr.is_sugared_doc {
165 err.help("`///` is for documentation comments. For a plain comment, use `//`.");
172 pub fn configure_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
174 abi: foreign_mod.abi,
175 items: foreign_mod.items.into_iter().filter_map(|item| self.configure(item)).collect(),
179 fn configure_variant_data(&mut self, vdata: ast::VariantData) -> ast::VariantData {
181 ast::VariantData::Struct(fields, id) => {
182 let fields = fields.into_iter().filter_map(|field| self.configure(field));
183 ast::VariantData::Struct(fields.collect(), id)
185 ast::VariantData::Tuple(fields, id) => {
186 let fields = fields.into_iter().filter_map(|field| self.configure(field));
187 ast::VariantData::Tuple(fields.collect(), id)
189 ast::VariantData::Unit(id) => ast::VariantData::Unit(id)
193 pub fn configure_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind {
195 ast::ItemKind::Struct(def, generics) => {
196 ast::ItemKind::Struct(self.configure_variant_data(def), generics)
198 ast::ItemKind::Union(def, generics) => {
199 ast::ItemKind::Union(self.configure_variant_data(def), generics)
201 ast::ItemKind::Enum(def, generics) => {
202 let variants = def.variants.into_iter().filter_map(|v| {
203 self.configure(v).map(|v| {
205 node: ast::Variant_ {
208 data: self.configure_variant_data(v.node.data),
209 disr_expr: v.node.disr_expr,
215 ast::ItemKind::Enum(ast::EnumDef {
216 variants: variants.collect(),
223 pub fn configure_expr_kind(&mut self, expr_kind: ast::ExprKind) -> ast::ExprKind {
225 ast::ExprKind::Match(m, arms) => {
226 let arms = arms.into_iter().filter_map(|a| self.configure(a)).collect();
227 ast::ExprKind::Match(m, arms)
229 ast::ExprKind::Struct(path, fields, base) => {
230 let fields = fields.into_iter()
231 .filter_map(|field| {
232 self.visit_struct_field_attrs(field.attrs());
233 self.configure(field)
236 ast::ExprKind::Struct(path, fields, base)
242 pub fn configure_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
243 self.visit_expr_attrs(expr.attrs());
245 // If an expr is valid to cfg away it will have been removed by the
246 // outer stmt or expression folder before descending in here.
247 // Anything else is always required, and thus has to error out
248 // in case of a cfg attr.
250 // NB: This is intentionally not part of the fold_expr() function
251 // in order for fold_opt_expr() to be able to avoid this check
252 if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a) || is_test_or_bench(a)) {
253 let msg = "removing an expression is not supported in this position";
254 self.sess.span_diagnostic.span_err(attr.span, msg);
257 self.process_cfg_attrs(expr)
260 pub fn configure_stmt(&mut self, stmt: ast::Stmt) -> Option<ast::Stmt> {
264 pub fn configure_struct_expr_field(&mut self, field: ast::Field) -> Option<ast::Field> {
265 if !self.features.map(|features| features.struct_field_attributes).unwrap_or(true) {
266 if !field.attrs.is_empty() {
267 let mut err = feature_err(&self.sess,
268 "struct_field_attributes",
271 "attributes on struct literal fields are unstable");
276 self.configure(field)
279 pub fn configure_pat(&mut self, pattern: P<ast::Pat>) -> P<ast::Pat> {
280 pattern.map(|mut pattern| {
281 if let ast::PatKind::Struct(path, fields, etc) = pattern.node {
282 let fields = fields.into_iter()
283 .filter_map(|field| {
284 self.visit_struct_field_attrs(field.attrs());
285 self.configure(field)
288 pattern.node = ast::PatKind::Struct(path, fields, etc);
294 fn visit_struct_field_attrs(&mut self, attrs: &[ast::Attribute]) {
295 // flag the offending attributes
296 for attr in attrs.iter() {
297 if !self.features.map(|features| features.struct_field_attributes).unwrap_or(true) {
298 let mut err = feature_err(
300 "struct_field_attributes",
303 "attributes on struct pattern or literal fields are unstable");
310 impl<'a> fold::Folder for StripUnconfigured<'a> {
311 fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
312 let foreign_mod = self.configure_foreign_mod(foreign_mod);
313 fold::noop_fold_foreign_mod(foreign_mod, self)
316 fn fold_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind {
317 let item = self.configure_item_kind(item);
318 fold::noop_fold_item_kind(item, self)
321 fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
322 let mut expr = self.configure_expr(expr).unwrap();
323 expr.node = self.configure_expr_kind(expr.node);
324 P(fold::noop_fold_expr(expr, self))
327 fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
328 let mut expr = configure!(self, expr).unwrap();
329 expr.node = self.configure_expr_kind(expr.node);
330 Some(P(fold::noop_fold_expr(expr, self)))
333 fn fold_stmt(&mut self, stmt: ast::Stmt) -> SmallVector<ast::Stmt> {
334 match self.configure_stmt(stmt) {
335 Some(stmt) => fold::noop_fold_stmt(stmt, self),
336 None => return SmallVector::new(),
340 fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> {
341 fold::noop_fold_item(configure!(self, item), self)
344 fn fold_impl_item(&mut self, item: ast::ImplItem) -> SmallVector<ast::ImplItem> {
345 fold::noop_fold_impl_item(configure!(self, item), self)
348 fn fold_trait_item(&mut self, item: ast::TraitItem) -> SmallVector<ast::TraitItem> {
349 fold::noop_fold_trait_item(configure!(self, item), self)
352 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
353 // Don't configure interpolated AST (c.f. #34171).
354 // Interpolated AST will get configured once the surrounding tokens are parsed.
358 fn fold_pat(&mut self, pattern: P<ast::Pat>) -> P<ast::Pat> {
359 fold::noop_fold_pat(self.configure_pat(pattern), self)
363 fn is_cfg(attr: &ast::Attribute) -> bool {
364 attr.check_name("cfg")
367 pub fn is_test_or_bench(attr: &ast::Attribute) -> bool {
368 attr.check_name("test") || attr.check_name("bench")