Skip to content

Commit

Permalink
Added stmt_expr_attribute feature gate
Browse files Browse the repository at this point in the history
  • Loading branch information
Kimundi committed Nov 26, 2015
1 parent c56b47a commit 296c361
Show file tree
Hide file tree
Showing 11 changed files with 469 additions and 63 deletions.
3 changes: 3 additions & 0 deletions src/doc/reference.md
Expand Up @@ -2368,6 +2368,9 @@ The currently implemented features of the reference compiler are:
influence type inference.
* - `braced_empty_structs` - Allows use of empty structs and enum variants with braces.

* - `stmt_expr_attributes` - Allows attributes on expressions and
non-item statements.

If a feature is promoted to a language feature, then all existing programs will
start to receive compilation warnings about `#![feature]` directives which enabled
the new feature (because the directive is no longer necessary). However, if a
Expand Down
28 changes: 19 additions & 9 deletions src/libsyntax/attr.rs
Expand Up @@ -20,8 +20,9 @@ use ast::{Stmt, StmtDecl, StmtExpr, StmtMac, StmtSemi, DeclItem, DeclLocal};
use ast::{Expr, Item, Local, Decl};
use codemap::{Span, Spanned, spanned, dummy_spanned};
use codemap::BytePos;
use config::CfgDiag;
use diagnostic::SpanHandler;
use feature_gate::GatedCfg;
use feature_gate::{GatedCfg, GatedCfgAttr};
use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
use parse::token::{InternedString, intern_and_get_ident};
use parse::token;
Expand Down Expand Up @@ -358,26 +359,35 @@ pub fn requests_inline(attrs: &[Attribute]) -> bool {
}

/// Tests if a cfg-pattern matches the cfg set
pub fn cfg_matches(diagnostic: &SpanHandler, cfgs: &[P<MetaItem>], cfg: &ast::MetaItem,
feature_gated_cfgs: &mut Vec<GatedCfg>) -> bool {
pub fn cfg_matches<T: CfgDiag>(cfgs: &[P<MetaItem>],
cfg: &ast::MetaItem,
diag: &mut T) -> bool {
match cfg.node {
ast::MetaList(ref pred, ref mis) if &pred[..] == "any" =>
mis.iter().any(|mi| cfg_matches(diagnostic, cfgs, &**mi, feature_gated_cfgs)),
mis.iter().any(|mi| cfg_matches(cfgs, &**mi, diag)),
ast::MetaList(ref pred, ref mis) if &pred[..] == "all" =>
mis.iter().all(|mi| cfg_matches(diagnostic, cfgs, &**mi, feature_gated_cfgs)),
mis.iter().all(|mi| cfg_matches(cfgs, &**mi, diag)),
ast::MetaList(ref pred, ref mis) if &pred[..] == "not" => {
if mis.len() != 1 {
diagnostic.span_err(cfg.span, "expected 1 cfg-pattern");
diag.emit_error(|diagnostic| {
diagnostic.span_err(cfg.span, "expected 1 cfg-pattern");
});
return false;
}
!cfg_matches(diagnostic, cfgs, &*mis[0], feature_gated_cfgs)
!cfg_matches(cfgs, &*mis[0], diag)
}
ast::MetaList(ref pred, _) => {
diagnostic.span_err(cfg.span, &format!("invalid predicate `{}`", pred));
diag.emit_error(|diagnostic| {
diagnostic.span_err(cfg.span,
&format!("invalid predicate `{}`", pred));
});
false
},
ast::MetaWord(_) | ast::MetaNameValue(..) => {
feature_gated_cfgs.extend(GatedCfg::gate(cfg));
diag.flag_gated(|feature_gated_cfgs| {
feature_gated_cfgs.extend(
GatedCfg::gate(cfg).map(GatedCfgAttr::GatedCfg));
});
contains(cfgs, cfg)
}
}
Expand Down
249 changes: 210 additions & 39 deletions src/libsyntax/config.rs
Expand Up @@ -10,9 +10,10 @@

use attr::AttrMetaMethods;
use diagnostic::SpanHandler;
use feature_gate::GatedCfg;
use feature_gate::GatedCfgAttr;
use fold::Folder;
use {ast, fold, attr};
use visit;
use codemap::{Spanned, respan};
use ptr::P;

Expand All @@ -28,20 +29,26 @@ struct Context<'a, F> where F: FnMut(&[ast::Attribute]) -> bool {
// Support conditional compilation by transforming the AST, stripping out
// any items that do not belong in the current configuration
pub fn strip_unconfigured_items(diagnostic: &SpanHandler, krate: ast::Crate,
feature_gated_cfgs: &mut Vec<GatedCfg>)
feature_gated_cfgs: &mut Vec<GatedCfgAttr>)
-> ast::Crate
{
// Need to do this check here because cfg runs before feature_gates
check_for_gated_stmt_expr_attributes(&krate, feature_gated_cfgs);

let krate = process_cfg_attr(diagnostic, krate, feature_gated_cfgs);
let config = krate.config.clone();
strip_items(diagnostic,
krate,
|attrs| in_cfg(diagnostic, &config, attrs, feature_gated_cfgs))
|attrs| {
let mut diag = CfgDiagReal {
diag: diagnostic,
feature_gated_cfgs: feature_gated_cfgs,
};
in_cfg(&config, attrs, &mut diag)
})
}

impl<'a, F> fold::Folder for Context<'a, F> where F: FnMut(&[ast::Attribute]) -> bool {
fn fold_mod(&mut self, module: ast::Mod) -> ast::Mod {
fold_mod(self, module)
}
fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
fold_foreign_mod(self, foreign_mod)
}
Expand Down Expand Up @@ -87,19 +94,6 @@ pub fn strip_items<'a, F>(diagnostic: &'a SpanHandler,
ctxt.fold_crate(krate)
}

fn fold_mod<F>(cx: &mut Context<F>,
ast::Mod {inner, items}: ast::Mod)
-> ast::Mod where
F: FnMut(&[ast::Attribute]) -> bool
{
ast::Mod {
inner: inner,
items: items.into_iter().flat_map(|a| {
cx.fold_item(a).into_iter()
}).collect()
}
}

fn filter_foreign_item<F>(cx: &mut Context<F>,
item: P<ast::ForeignItem>)
-> Option<P<ast::ForeignItem>> where
Expand Down Expand Up @@ -271,44 +265,45 @@ fn is_cfg(attr: &ast::Attribute) -> bool {

// Determine if an item should be translated in the current crate
// configuration based on the item's attributes
fn in_cfg(diagnostic: &SpanHandler,
cfg: &[P<ast::MetaItem>],
attrs: &[ast::Attribute],
feature_gated_cfgs: &mut Vec<GatedCfg>) -> bool {
fn in_cfg<T: CfgDiag>(cfg: &[P<ast::MetaItem>],
attrs: &[ast::Attribute],
diag: &mut T) -> bool {
attrs.iter().all(|attr| {
let mis = match attr.node.value.node {
ast::MetaList(_, ref mis) if is_cfg(&attr) => mis,
_ => return true
};

if mis.len() != 1 {
diagnostic.span_err(attr.span, "expected 1 cfg-pattern");
diag.emit_error(|diagnostic| {
diagnostic.span_err(attr.span, "expected 1 cfg-pattern");
});
return true;
}

attr::cfg_matches(diagnostic, cfg, &mis[0],
feature_gated_cfgs)
attr::cfg_matches(cfg, &mis[0], diag)
})
}

struct CfgAttrFolder<'a, 'b> {
diag: &'a SpanHandler,
config: ast::CrateConfig,
feature_gated_cfgs: &'b mut Vec<GatedCfg>
struct CfgAttrFolder<'a, T> {
diag: T,
config: &'a ast::CrateConfig,
}

// Process `#[cfg_attr]`.
fn process_cfg_attr(diagnostic: &SpanHandler, krate: ast::Crate,
feature_gated_cfgs: &mut Vec<GatedCfg>) -> ast::Crate {
feature_gated_cfgs: &mut Vec<GatedCfgAttr>) -> ast::Crate {
let mut fld = CfgAttrFolder {
diag: diagnostic,
config: krate.config.clone(),
feature_gated_cfgs: feature_gated_cfgs,
diag: CfgDiagReal {
diag: diagnostic,
feature_gated_cfgs: feature_gated_cfgs,
},
config: &krate.config.clone(),
};
fld.fold_crate(krate)
}

impl<'a,'b> fold::Folder for CfgAttrFolder<'a,'b> {
impl<'a, T: CfgDiag> fold::Folder for CfgAttrFolder<'a, T> {
fn fold_attribute(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> {
if !attr.check_name("cfg_attr") {
return fold::noop_fold_attribute(attr, self);
Expand All @@ -317,20 +312,25 @@ impl<'a,'b> fold::Folder for CfgAttrFolder<'a,'b> {
let attr_list = match attr.meta_item_list() {
Some(attr_list) => attr_list,
None => {
self.diag.span_err(attr.span, "expected `#[cfg_attr(<cfg pattern>, <attr>)]`");
self.diag.emit_error(|diag| {
diag.span_err(attr.span,
"expected `#[cfg_attr(<cfg pattern>, <attr>)]`");
});
return None;
}
};
let (cfg, mi) = match (attr_list.len(), attr_list.get(0), attr_list.get(1)) {
(2, Some(cfg), Some(mi)) => (cfg, mi),
_ => {
self.diag.span_err(attr.span, "expected `#[cfg_attr(<cfg pattern>, <attr>)]`");
self.diag.emit_error(|diag| {
diag.span_err(attr.span,
"expected `#[cfg_attr(<cfg pattern>, <attr>)]`");
});
return None;
}
};

if attr::cfg_matches(self.diag, &self.config[..], &cfg,
self.feature_gated_cfgs) {
if attr::cfg_matches(&self.config[..], &cfg, &mut self.diag) {
Some(respan(mi.span, ast::Attribute_ {
id: attr::mk_attr_id(),
style: attr.node.style,
Expand All @@ -347,3 +347,174 @@ impl<'a,'b> fold::Folder for CfgAttrFolder<'a,'b> {
fold::noop_fold_mac(mac, self)
}
}

fn check_for_gated_stmt_expr_attributes(krate: &ast::Crate,
discovered: &mut Vec<GatedCfgAttr>) {
let mut v = StmtExprAttrFeatureVisitor {
config: &krate.config,
discovered: discovered,
};
visit::walk_crate(&mut v, krate);
}

/// To cover this feature, we need to discover all attributes
/// so we need to run before cfg.
struct StmtExprAttrFeatureVisitor<'a, 'b> {
config: &'a ast::CrateConfig,
discovered: &'b mut Vec<GatedCfgAttr>,
}

// Runs the cfg_attr and cfg folders locally in "silent" mode
// to discover attribute use on stmts or expressions ahead of time
impl<'v, 'a, 'b> visit::Visitor<'v> for StmtExprAttrFeatureVisitor<'a, 'b> {
fn visit_stmt(&mut self, s: &'v ast::Stmt) {
// check if there even are any attributes on this node
let stmt_attrs = s.node.attrs();
if stmt_attrs.len() > 0 {
// attributes on items are fine
if let ast::StmtDecl(ref decl, _) = s.node {
if let ast::DeclItem(_) = decl.node {
visit::walk_stmt(self, s);
return;
}
}

// flag the offending attributes
for attr in stmt_attrs {
self.discovered.push(GatedCfgAttr::GatedAttr(attr.span));
}

// if the node does not end up being cfg-d away, walk down
if node_survives_cfg(stmt_attrs, self.config) {
visit::walk_stmt(self, s);
}
} else {
visit::walk_stmt(self, s);
}
}

fn visit_expr(&mut self, ex: &'v ast::Expr) {
// check if there even are any attributes on this node
let expr_attrs = ex.attrs();
if expr_attrs.len() > 0 {

// flag the offending attributes
for attr in expr_attrs {
self.discovered.push(GatedCfgAttr::GatedAttr(attr.span));
}

// if the node does not end up being cfg-d away, walk down
if node_survives_cfg(expr_attrs, self.config) {
visit::walk_expr(self, ex);
}
} else {
visit::walk_expr(self, ex);
}
}

fn visit_foreign_item(&mut self, i: &'v ast::ForeignItem) {
if node_survives_cfg(&i.attrs, self.config) {
visit::walk_foreign_item(self, i);
}
}

fn visit_item(&mut self, i: &'v ast::Item) {
if node_survives_cfg(&i.attrs, self.config) {
visit::walk_item(self, i);
}
}

fn visit_impl_item(&mut self, ii: &'v ast::ImplItem) {
if node_survives_cfg(&ii.attrs, self.config) {
visit::walk_impl_item(self, ii);
}
}

fn visit_trait_item(&mut self, ti: &'v ast::TraitItem) {
if node_survives_cfg(&ti.attrs, self.config) {
visit::walk_trait_item(self, ti);
}
}

fn visit_struct_field(&mut self, s: &'v ast::StructField) {
if node_survives_cfg(&s.node.attrs, self.config) {
visit::walk_struct_field(self, s);
}
}

fn visit_variant(&mut self, v: &'v ast::Variant,
g: &'v ast::Generics, item_id: ast::NodeId) {
if node_survives_cfg(&v.node.attrs, self.config) {
visit::walk_variant(self, v, g, item_id);
}
}

fn visit_arm(&mut self, a: &'v ast::Arm) {
if node_survives_cfg(&a.attrs, self.config) {
visit::walk_arm(self, a);
}
}

// This visitor runs pre expansion, so we need to prevent
// the default panic here
fn visit_mac(&mut self, mac: &'v ast::Mac) {
visit::walk_mac(self, mac)
}
}

pub trait CfgDiag {
fn emit_error<F>(&mut self, f: F) where F: FnMut(&SpanHandler);
fn flag_gated<F>(&mut self, f: F) where F: FnMut(&mut Vec<GatedCfgAttr>);
}

pub struct CfgDiagReal<'a, 'b> {
pub diag: &'a SpanHandler,
pub feature_gated_cfgs: &'b mut Vec<GatedCfgAttr>,
}

impl<'a, 'b> CfgDiag for CfgDiagReal<'a, 'b> {
fn emit_error<F>(&mut self, mut f: F) where F: FnMut(&SpanHandler) {
f(self.diag)
}
fn flag_gated<F>(&mut self, mut f: F) where F: FnMut(&mut Vec<GatedCfgAttr>) {
f(self.feature_gated_cfgs)
}
}

struct CfgDiagSilent {
error: bool,
}

impl CfgDiag for CfgDiagSilent {
fn emit_error<F>(&mut self, _: F) where F: FnMut(&SpanHandler) {
self.error = true;
}
fn flag_gated<F>(&mut self, _: F) where F: FnMut(&mut Vec<GatedCfgAttr>) {}
}

fn node_survives_cfg(attrs: &[ast::Attribute],
config: &ast::CrateConfig) -> bool {
let mut survives_cfg = true;

for attr in attrs {
let mut fld = CfgAttrFolder {
diag: CfgDiagSilent { error: false },
config: config,
};
let attr = fld.fold_attribute(attr.clone());

// In case of error we can just return true,
// since the actual cfg folders will end compilation anyway.

if fld.diag.error { return true; }

survives_cfg &= attr.map(|attr| {
let mut diag = CfgDiagSilent { error: false };
let r = in_cfg(config, &[attr], &mut diag);
if diag.error { return true; }
r
}).unwrap_or(true)
}

survives_cfg
}

0 comments on commit 296c361

Please sign in to comment.