rune_macros/
macro_.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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
use proc_macro2::{Ident, TokenStream};
use quote::{quote, ToTokens};
use syn::parse::ParseStream;
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;

#[derive(Default)]
enum Path {
    #[default]
    None,
    Path(syn::Path),
}

#[derive(Default)]
pub(crate) struct Config {
    path: Path,
}

impl Config {
    /// Parse the given parse stream.
    pub(crate) fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut out = Self::default();

        while !input.is_empty() {
            let ident = input.parse::<syn::Ident>()?;

            if ident != "path" {
                return Err(syn::Error::new_spanned(ident, "Unsupported option"));
            }

            input.parse::<syn::Token![=]>()?;
            out.path = Path::Path(input.parse()?);

            if input.parse::<Option<syn::Token![,]>>()?.is_none() {
                break;
            }
        }

        let stream = input.parse::<TokenStream>()?;

        if !stream.is_empty() {
            return Err(syn::Error::new_spanned(stream, "Unexpected input"));
        }

        Ok(out)
    }
}

pub(crate) struct Macro {
    attributes: Vec<syn::Attribute>,
    vis: syn::Visibility,
    sig: syn::Signature,
    remainder: TokenStream,
    name_string: syn::LitStr,
    docs: syn::ExprArray,
    meta_vis: syn::Visibility,
    real_fn: syn::Ident,
    meta_fn: syn::Ident,
}

impl Macro {
    /// Parse the given parse stream.
    pub(crate) fn parse(input: ParseStream) -> syn::Result<Self> {
        let parsed_attributes = input.call(syn::Attribute::parse_outer)?;
        let vis = input.parse::<syn::Visibility>()?;
        let mut sig = input.parse::<syn::Signature>()?;
        let ident = sig.ident.clone();

        let mut attributes = Vec::new();

        let mut docs = syn::ExprArray {
            attrs: Vec::new(),
            bracket_token: syn::token::Bracket::default(),
            elems: Punctuated::default(),
        };

        for attr in parsed_attributes {
            if attr.path().is_ident("doc") {
                if let syn::Meta::NameValue(name_value) = &attr.meta {
                    docs.elems.push(name_value.value.clone());
                }
            }

            attributes.push(attr);
        }

        let name_string = syn::LitStr::new(&ident.to_string(), ident.span());

        let meta_vis = vis.clone();
        let meta_fn = sig.ident.clone();
        let real_fn = syn::Ident::new(&format!("__rune_macro__{}", sig.ident), sig.ident.span());
        sig.ident = real_fn.clone();

        let remainder = input.parse::<TokenStream>()?;

        Ok(Self {
            attributes,
            vis,
            sig,
            remainder,
            name_string,
            docs,
            meta_vis,
            real_fn,
            meta_fn,
        })
    }

    /// Expand the function declaration.
    pub(crate) fn expand(self, attrs: Config, macro_kind: Ident) -> syn::Result<TokenStream> {
        let real_fn_path = {
            let mut segments = Punctuated::default();

            segments.push(syn::PathSegment {
                ident: self.real_fn,
                arguments: syn::PathArguments::None,
            });

            syn::TypePath {
                qself: None,
                path: syn::Path {
                    leading_colon: None,
                    segments,
                },
            }
        };

        let meta_name = syn::Expr::Array({
            let mut meta_name = syn::ExprArray {
                attrs: Vec::new(),
                bracket_token: syn::token::Bracket::default(),
                elems: Punctuated::default(),
            };

            match attrs.path {
                Path::None => {
                    meta_name.elems.push(syn::Expr::Lit(syn::ExprLit {
                        attrs: Vec::new(),
                        lit: syn::Lit::Str(self.name_string.clone()),
                    }));
                }
                Path::Path(path) => {
                    for s in &path.segments {
                        let syn::PathArguments::None = s.arguments else {
                            return Err(syn::Error::new_spanned(
                                s,
                                "Expected simple ident path segment",
                            ));
                        };

                        let ident = syn::LitStr::new(&s.ident.to_string(), s.span());

                        meta_name.elems.push(syn::Expr::Lit(syn::ExprLit {
                            attrs: Vec::new(),
                            lit: syn::Lit::Str(ident),
                        }));
                    }
                }
            }

            meta_name
        });

        let mut stream = TokenStream::new();

        for attr in self.attributes {
            stream.extend(attr.into_token_stream());
        }

        stream.extend(quote!(#[allow(non_snake_case)]));
        stream.extend(self.vis.into_token_stream());
        stream.extend(self.sig.into_token_stream());
        stream.extend(self.remainder);

        let meta_vis = &self.meta_vis;
        let meta_fn = &self.meta_fn;
        let docs = &self.docs;
        let name_string = self.name_string;

        stream.extend(quote! {
            /// Get function metadata.
            #[automatically_derived]
            #meta_vis fn #meta_fn() -> rune::alloc::Result<rune::__private::MacroMetaData> {
                Ok(rune::__private::MacroMetaData {
                    kind: rune::__private::MacroMetaKind::#macro_kind(#meta_name, #real_fn_path)?,
                    name: #name_string,
                    docs: &#docs[..],
                })
            }
        });

        Ok(stream)
    }
}