//! Processes out #[cfg] and #[cfg_attr] attributes from the input for the derive macro use rustc_hash::FxHashSet; use syntax::{ ast::{self, Attr, HasAttrs, Meta, VariantList}, AstNode, SyntaxElement, SyntaxNode, T, }; use tracing::{debug, warn}; use crate::{db::ExpandDatabase, MacroCallKind, MacroCallLoc}; fn check_cfg_attr(attr: &Attr, loc: &MacroCallLoc, db: &dyn ExpandDatabase) -> Option { if !attr.simple_name().as_deref().map(|v| v == "cfg")? { return None; } debug!("Evaluating cfg {}", attr); let cfg = cfg::CfgExpr::parse_from_attr_meta(attr.meta()?)?; debug!("Checking cfg {:?}", cfg); let enabled = db.crate_graph()[loc.krate].cfg_options.check(&cfg) != Some(false); Some(enabled) } fn check_cfg_attr_attr(attr: &Attr, loc: &MacroCallLoc, db: &dyn ExpandDatabase) -> Option { if !attr.simple_name().as_deref().map(|v| v == "cfg_attr")? { return None; } debug!("Evaluating cfg_attr {}", attr); let cfg_expr = cfg::CfgExpr::parse_from_attr_meta(attr.meta()?)?; debug!("Checking cfg_attr {:?}", cfg_expr); let enabled = db.crate_graph()[loc.krate].cfg_options.check(&cfg_expr) != Some(false); Some(enabled) } fn process_has_attrs_with_possible_comma( items: impl Iterator, loc: &MacroCallLoc, db: &dyn ExpandDatabase, remove: &mut FxHashSet, ) -> Option<()> { for item in items { let field_attrs = item.attrs(); 'attrs: for attr in field_attrs { if check_cfg_attr(&attr, loc, db).map(|enabled| !enabled).unwrap_or_default() { debug!("censoring type {:?}", item.syntax()); remove.insert(item.syntax().clone().into()); // We need to remove the , as well add_comma(&item, remove); break 'attrs; } if let Some(enabled) = check_cfg_attr_attr(&attr, loc, db) { if enabled { debug!("Removing cfg_attr tokens {:?}", attr); let meta = attr.meta()?; let removes_from_cfg_attr = remove_tokens_within_cfg_attr(meta)?; remove.extend(removes_from_cfg_attr); } else { debug!("censoring type cfg_attr {:?}", item.syntax()); remove.insert(attr.syntax().clone().into()); continue; } } } } Some(()) } fn remove_tokens_within_cfg_attr(meta: Meta) -> Option> { let mut remove: FxHashSet = FxHashSet::default(); debug!("Enabling attribute {}", meta); let meta_path = meta.path()?; debug!("Removing {:?}", meta_path.syntax()); remove.insert(meta_path.syntax().clone().into()); let meta_tt = meta.token_tree()?; debug!("meta_tt {}", meta_tt); // Remove the left paren remove.insert(meta_tt.l_paren_token()?.into()); let mut found_comma = false; for tt in meta_tt.token_trees_and_tokens().skip(1) { debug!("Checking {:?}", tt); // Check if it is a subtree or a token. If it is a token check if it is a comma. If so, remove it and break. match tt { syntax::NodeOrToken::Node(node) => { // Remove the entire subtree remove.insert(node.syntax().clone().into()); } syntax::NodeOrToken::Token(token) => { if token.kind() == T![,] { found_comma = true; remove.insert(token.into()); break; } remove.insert(token.into()); } } } if !found_comma { warn!("No comma found in {}", meta_tt); return None; } // Remove the right paren remove.insert(meta_tt.r_paren_token()?.into()); Some(remove) } fn add_comma(item: &impl AstNode, res: &mut FxHashSet) { if let Some(comma) = item.syntax().next_sibling_or_token().filter(|it| it.kind() == T![,]) { res.insert(comma); } } fn process_enum( variants: VariantList, loc: &MacroCallLoc, db: &dyn ExpandDatabase, remove: &mut FxHashSet, ) -> Option<()> { 'variant: for variant in variants.variants() { for attr in variant.attrs() { if check_cfg_attr(&attr, loc, db).map(|enabled| !enabled).unwrap_or_default() { // Rustc does not strip the attribute if it is enabled. So we will will leave it debug!("censoring type {:?}", variant.syntax()); remove.insert(variant.syntax().clone().into()); // We need to remove the , as well add_comma(&variant, remove); continue 'variant; }; if let Some(enabled) = check_cfg_attr_attr(&attr, loc, db) { if enabled { debug!("Removing cfg_attr tokens {:?}", attr); let meta = attr.meta()?; let removes_from_cfg_attr = remove_tokens_within_cfg_attr(meta)?; remove.extend(removes_from_cfg_attr); } else { debug!("censoring type cfg_attr {:?}", variant.syntax()); remove.insert(attr.syntax().clone().into()); continue; } } } if let Some(fields) = variant.field_list() { match fields { ast::FieldList::RecordFieldList(fields) => { process_has_attrs_with_possible_comma(fields.fields(), loc, db, remove)?; } ast::FieldList::TupleFieldList(fields) => { process_has_attrs_with_possible_comma(fields.fields(), loc, db, remove)?; } } } } Some(()) } pub(crate) fn process_cfg_attrs( node: &SyntaxNode, loc: &MacroCallLoc, db: &dyn ExpandDatabase, ) -> Option> { // FIXME: #[cfg_eval] is not implemented. But it is not stable yet if !matches!(loc.kind, MacroCallKind::Derive { .. }) { return None; } let mut remove = FxHashSet::default(); let item = ast::Item::cast(node.clone())?; for attr in item.attrs() { if let Some(enabled) = check_cfg_attr_attr(&attr, loc, db) { if enabled { debug!("Removing cfg_attr tokens {:?}", attr); let meta = attr.meta()?; let removes_from_cfg_attr = remove_tokens_within_cfg_attr(meta)?; remove.extend(removes_from_cfg_attr); } else { debug!("censoring type cfg_attr {:?}", item.syntax()); remove.insert(attr.syntax().clone().into()); continue; } } } match item { ast::Item::Struct(it) => match it.field_list()? { ast::FieldList::RecordFieldList(fields) => { process_has_attrs_with_possible_comma(fields.fields(), loc, db, &mut remove)?; } ast::FieldList::TupleFieldList(fields) => { process_has_attrs_with_possible_comma(fields.fields(), loc, db, &mut remove)?; } }, ast::Item::Enum(it) => { process_enum(it.variant_list()?, loc, db, &mut remove)?; } ast::Item::Union(it) => { process_has_attrs_with_possible_comma( it.record_field_list()?.fields(), loc, db, &mut remove, )?; } // FIXME: Implement for other items if necessary. As we do not support #[cfg_eval] yet, we do not need to implement it for now _ => {} } Some(remove) }