naked_function_macro/
asm.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
use quote::ToTokens;
use syn::{
    ext::IdentExt,
    parenthesized,
    parse::{Parse, ParseStream},
    punctuated::Punctuated,
    token::Paren,
    Expr, Ident, ItemFn, Result, Stmt, Token,
};

pub mod kw {
    syn::custom_keyword!(sym);
    syn::custom_keyword!(options);
    syn::custom_keyword!(out);
    syn::custom_keyword!(lateout);
    syn::custom_keyword!(inout);
    syn::custom_keyword!(inlateout);
    syn::custom_keyword!(clobber_abi);
}

/// Representation of one argument of the `asm!` macro.
pub enum AsmOperand {
    Template(Expr),
    Const {
        name: Option<(Ident, Token![=])>,
        token: Token![const],
        expr: Expr,
    },
    Sym {
        name: Option<(Ident, Token![=])>,
        token: kw::sym,
        expr: Expr,
    },
    Options {
        token: kw::options,
        paren_token: Paren,
        options: Punctuated<Ident, Token![,]>,
    },
}

impl Parse for AsmOperand {
    fn parse(input: ParseStream) -> Result<Self> {
        if input.peek(kw::options) {
            let token = input.parse::<kw::options>()?;
            let content;
            let paren_token = parenthesized!(content in input);
            let options = content.parse_terminated(Ident::parse, Token![,])?;
            return Ok(Self::Options {
                token,
                paren_token,
                options,
            });
        }

        let mut name = None;
        if input.peek(Ident::peek_any) && input.peek2(Token![=]) {
            let ident = input.call(Ident::parse_any)?;
            let token = input.parse()?;
            name = Some((ident, token));
        }

        if input.peek(kw::sym) {
            let token = input.parse()?;
            let expr = input.parse()?;
            return Ok(Self::Sym { name, token, expr });
        }

        if input.peek(Token![const]) {
            let token = input.parse()?;
            let expr = input.parse()?;
            return Ok(Self::Const { name, token, expr });
        }

        if input.peek(Token![in])
            || input.peek(kw::out)
            || input.peek(kw::lateout)
            || input.peek(kw::inout)
            || input.peek(kw::inlateout)
        {
            return Err(syn::Error::new(
                input.span(),
                "only `const` and `sym` operands may be used in naked functions",
            ));
        }

        if input.peek(kw::clobber_abi) {
            return Err(syn::Error::new(
                input.span(),
                "`clobber_abi` cannot be used in naked functions",
            ));
        }

        // Assume anything else is a template string. global_asm! will properly
        // validate this for us later.
        if let Some((ident, _token)) = name {
            bail!(ident, "invalid asm! syntax");
        }
        Ok(Self::Template(input.parse()?))
    }
}

impl ToTokens for AsmOperand {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        match self {
            AsmOperand::Template(expr) => expr.to_tokens(tokens),
            AsmOperand::Const { name, token, expr } => {
                if let Some((ident, token)) = name {
                    ident.to_tokens(tokens);
                    token.to_tokens(tokens);
                }
                token.to_tokens(tokens);
                expr.to_tokens(tokens);
            }
            AsmOperand::Sym { name, token, expr } => {
                if let Some((ident, token)) = name {
                    ident.to_tokens(tokens);
                    token.to_tokens(tokens);
                }
                token.to_tokens(tokens);
                expr.to_tokens(tokens);
            }
            AsmOperand::Options {
                token,
                paren_token,
                options,
            } => {
                token.to_tokens(tokens);
                paren_token.surround(tokens, |tokens| {
                    options.to_tokens(tokens);
                })
            }
        }
    }
}

/// Extracts the `AsmOperand`s from the `asm!` in the body of the function.
pub fn extract_asm(func: &ItemFn) -> Result<Punctuated<AsmOperand, Token![,]>> {
    if func.block.stmts.len() != 1 {
        bail!(
            func,
            "naked functions may only contain a single asm! statement"
        );
    }
    let (mac, attrs) = match &func.block.stmts[0] {
        Stmt::Macro(macro_) => (&macro_.mac, &macro_.attrs),
        Stmt::Expr(Expr::Macro(macro_), _) => (&macro_.mac, &macro_.attrs),
        _ => bail!(
            func,
            "naked functions may only contain a single asm! statement"
        ),
    };
    if !attrs.is_empty() || !mac.path.is_ident("asm") {
        bail!(
            func,
            "naked functions may only contain a single asm! statement"
        );
    }
    mac.parse_body_with(Punctuated::parse_terminated)
}