| 
 | 1 | +use either::Either;  | 
 | 2 | +use rustc_ast::token::Token;  | 
 | 3 | +use rustc_ast::tokenstream::{TokenStream, TokenTree};  | 
 | 4 | +use rustc_ast::{MetaItemInner, token};  | 
 | 5 | +use rustc_attr_parsing as attr;  | 
 | 6 | +use rustc_errors::PResult;  | 
 | 7 | +use rustc_expand::base::{ExtCtxt, MacroExpanderResult, *};  | 
 | 8 | +use rustc_parse::exp;  | 
 | 9 | +use rustc_parse::parser::Parser;  | 
 | 10 | +use rustc_span::{Ident, Span, kw, sym};  | 
 | 11 | + | 
 | 12 | +use crate::errors::{CfgSelectNoMatches, CfgSelectUnreachable};  | 
 | 13 | + | 
 | 14 | +#[derive(Default)]  | 
 | 15 | +struct SelectBranches {  | 
 | 16 | +    reachable: Vec<(MetaItemInner, TokenStream, Span)>,  | 
 | 17 | +    wildcard: Option<(Token, TokenStream, Span)>,  | 
 | 18 | +    unreachable: Vec<(Either<Token, MetaItemInner>, TokenStream, Span)>,  | 
 | 19 | +}  | 
 | 20 | + | 
 | 21 | +impl SelectBranches {  | 
 | 22 | +    /// Selects the first arm whose rule evaluates to true.  | 
 | 23 | +    fn select_arm(self, cx: &ExtCtxt<'_>) -> Option<(TokenStream, Span)> {  | 
 | 24 | +        for (cfg, tt, arm_span) in self.reachable {  | 
 | 25 | +            if attr::cfg_matches(  | 
 | 26 | +                &cfg,  | 
 | 27 | +                &cx.sess,  | 
 | 28 | +                cx.current_expansion.lint_node_id,  | 
 | 29 | +                Some(cx.ecfg.features),  | 
 | 30 | +            ) {  | 
 | 31 | +                return Some((tt, arm_span));  | 
 | 32 | +            }  | 
 | 33 | +        }  | 
 | 34 | + | 
 | 35 | +        self.wildcard.map(|(_, tt, span)| (tt, span))  | 
 | 36 | +    }  | 
 | 37 | +}  | 
 | 38 | + | 
 | 39 | +/// Parses a `TokenTree` that must be of the form `{ /* ... */ }`, and returns a `TokenStream` where  | 
 | 40 | +/// the the surrounding braces are stripped.  | 
 | 41 | +fn parse_token_tree<'a>(p: &mut Parser<'a>) -> PResult<'a, TokenStream> {  | 
 | 42 | +    // generate an error if the `=>` is not followed by `{`  | 
 | 43 | +    if p.token != token::OpenBrace {  | 
 | 44 | +        p.expect(exp!(OpenBrace))?;  | 
 | 45 | +    }  | 
 | 46 | + | 
 | 47 | +    // Strip the outer '{' and '}'  | 
 | 48 | +    match p.parse_token_tree() {  | 
 | 49 | +        TokenTree::Token(..) => unreachable!("because of the expect above"),  | 
 | 50 | +        TokenTree::Delimited(.., tts) => Ok(tts),  | 
 | 51 | +    }  | 
 | 52 | +}  | 
 | 53 | + | 
 | 54 | +fn parse_args<'a>(p: &mut Parser<'a>) -> PResult<'a, SelectBranches> {  | 
 | 55 | +    let mut branches = SelectBranches::default();  | 
 | 56 | + | 
 | 57 | +    while p.token != token::Eof {  | 
 | 58 | +        if p.token.is_keyword(kw::Underscore) {  | 
 | 59 | +            let underscore = p.token;  | 
 | 60 | +            p.bump();  | 
 | 61 | +            p.expect(exp!(FatArrow))?;  | 
 | 62 | + | 
 | 63 | +            let tts = parse_token_tree(p)?;  | 
 | 64 | +            let span = underscore.span.to(p.token.span);  | 
 | 65 | + | 
 | 66 | +            match branches.wildcard {  | 
 | 67 | +                None => branches.wildcard = Some((underscore, tts, span)),  | 
 | 68 | +                Some(_) => branches.unreachable.push((Either::Left(underscore), tts, span)),  | 
 | 69 | +            }  | 
 | 70 | +        } else {  | 
 | 71 | +            let meta_item = p.parse_meta_item_inner()?;  | 
 | 72 | +            p.expect(exp!(FatArrow))?;  | 
 | 73 | + | 
 | 74 | +            let tts = parse_token_tree(p)?;  | 
 | 75 | +            let span = meta_item.span().to(p.token.span);  | 
 | 76 | + | 
 | 77 | +            match branches.wildcard {  | 
 | 78 | +                None => branches.reachable.push((meta_item, tts, span)),  | 
 | 79 | +                Some(_) => branches.unreachable.push((Either::Right(meta_item), tts, span)),  | 
 | 80 | +            }  | 
 | 81 | +        }  | 
 | 82 | +    }  | 
 | 83 | + | 
 | 84 | +    Ok(branches)  | 
 | 85 | +}  | 
 | 86 | + | 
 | 87 | +pub(super) fn expand_cfg_select<'cx>(  | 
 | 88 | +    ecx: &'cx mut ExtCtxt<'_>,  | 
 | 89 | +    sp: Span,  | 
 | 90 | +    tts: TokenStream,  | 
 | 91 | +) -> MacroExpanderResult<'cx> {  | 
 | 92 | +    ExpandResult::Ready(match parse_args(&mut ecx.new_parser_from_tts(tts)) {  | 
 | 93 | +        Ok(branches) => {  | 
 | 94 | +            if let Some((underscore, _, _)) = branches.wildcard {  | 
 | 95 | +                // Warn for every unreachable rule.  | 
 | 96 | +                for (rule, _, _) in &branches.unreachable {  | 
 | 97 | +                    let span = match rule {  | 
 | 98 | +                        Either::Left(underscore) => underscore.span,  | 
 | 99 | +                        Either::Right(rule) => rule.span(),  | 
 | 100 | +                    };  | 
 | 101 | +                    let err = CfgSelectUnreachable { span, wildcard_span: underscore.span };  | 
 | 102 | +                    ecx.dcx().emit_warn(err);  | 
 | 103 | +                }  | 
 | 104 | +            }  | 
 | 105 | + | 
 | 106 | +            if let Some((tts, arm_span)) = branches.select_arm(ecx) {  | 
 | 107 | +                rustc_expand::expand_token_stream(  | 
 | 108 | +                    ecx,  | 
 | 109 | +                    sp,  | 
 | 110 | +                    arm_span,  | 
 | 111 | +                    ecx.current_expansion.lint_node_id,  | 
 | 112 | +                    Ident::with_dummy_span(sym::cfg_select),  | 
 | 113 | +                    tts,  | 
 | 114 | +                )  | 
 | 115 | +            } else {  | 
 | 116 | +                // Emit a compiler error when none of the rules matched.  | 
 | 117 | +                let guar = ecx.dcx().emit_err(CfgSelectNoMatches { span: sp });  | 
 | 118 | +                DummyResult::any(sp, guar)  | 
 | 119 | +            }  | 
 | 120 | +        }  | 
 | 121 | +        Err(err) => {  | 
 | 122 | +            let guar = err.emit();  | 
 | 123 | +            DummyResult::any(sp, guar)  | 
 | 124 | +        }  | 
 | 125 | +    })  | 
 | 126 | +}  | 
0 commit comments