|
| 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 | +use ast; |
| 12 | +use attr; |
| 13 | +use codemap::Span; |
| 14 | +use ext::base::ExtCtxt; |
| 15 | +use ext::build::AstBuilder; |
| 16 | +use ptr::P; |
| 17 | + |
| 18 | +pub fn expand(cx: &mut ExtCtxt, sp: Span, mi: &ast::MetaItem, it: P<ast::Item>) -> P<ast::Item> { |
| 19 | + let (cfg, attr) = match mi.node { |
| 20 | + ast::MetaList(_, ref mis) if mis.len() == 2 => (&mis[0], &mis[1]), |
| 21 | + _ => { |
| 22 | + cx.span_err(sp, "expected `#[cfg_attr(<cfg pattern>, <attr>)]`"); |
| 23 | + return it; |
| 24 | + } |
| 25 | + }; |
| 26 | + |
| 27 | + let mut out = (*it).clone(); |
| 28 | + if cfg_matches(cx, &**cfg) { |
| 29 | + out.attrs.push(cx.attribute(attr.span, attr.clone())); |
| 30 | + } |
| 31 | + |
| 32 | + P(out) |
| 33 | +} |
| 34 | + |
| 35 | +fn cfg_matches(cx: &mut ExtCtxt, cfg: &ast::MetaItem) -> bool { |
| 36 | + match cfg.node { |
| 37 | + ast::MetaList(ref pred, ref mis) if pred.get() == "any" => |
| 38 | + mis.iter().any(|mi| cfg_matches(cx, &**mi)), |
| 39 | + ast::MetaList(ref pred, ref mis) if pred.get() == "all" => |
| 40 | + mis.iter().all(|mi| cfg_matches(cx, &**mi)), |
| 41 | + ast::MetaList(ref pred, ref mis) if pred.get() == "not" => { |
| 42 | + if mis.len() != 1 { |
| 43 | + cx.span_err(cfg.span, format!("expected 1 value, got {}", |
| 44 | + mis.len()).as_slice()); |
| 45 | + return false; |
| 46 | + } |
| 47 | + !cfg_matches(cx, &*mis[0]) |
| 48 | + } |
| 49 | + ast::MetaList(ref pred, _) => { |
| 50 | + cx.span_err(cfg.span, |
| 51 | + format!("invalid predicate `{}`", pred).as_slice()); |
| 52 | + false |
| 53 | + }, |
| 54 | + ast::MetaWord(_) | ast::MetaNameValue(..) => |
| 55 | + attr::contains(cx.cfg.as_slice(), cfg), |
| 56 | + } |
| 57 | +} |
0 commit comments