-
Notifications
You must be signed in to change notification settings - Fork 2.1k
feat: apply #[cfg] to proc macro inputs
#16789
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
f45b080
Starting Fix for cfg stripping
wyatt-herkamp 79f2651
Add cfg_attr and cleanup code
wyatt-herkamp 948a2de
Clippy Fix
wyatt-herkamp 0fb5d0d
Check for cfg_attr on the actual item and Debug instead of info in cf…
wyatt-herkamp 447de3d
Review Updates and added tests.
wyatt-herkamp File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,204 @@ | ||
| //! 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<bool> { | ||
| 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<bool> { | ||
| 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<I: HasAttrs>( | ||
| items: impl Iterator<Item = I>, | ||
| loc: &MacroCallLoc, | ||
| db: &dyn ExpandDatabase, | ||
| remove: &mut FxHashSet<SyntaxElement>, | ||
| ) -> 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<FxHashSet<SyntaxElement>> { | ||
|
wyatt-herkamp marked this conversation as resolved.
|
||
| let mut remove: FxHashSet<SyntaxElement> = 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<SyntaxElement>) { | ||
|
wyatt-herkamp marked this conversation as resolved.
Outdated
|
||
| 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<SyntaxElement>, | ||
| ) -> 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<FxHashSet<SyntaxElement>> { | ||
| // 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) | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.