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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
//! Providing the features between "full" and "derive" of syn.
//!
//! This crate provides the following two unique data structures.
//!
//! * [`syn_mid::ItemFn`] -- A function whose body is not parsed.
//!
//!   ```text
//!   fn process(n: usize) -> Result<()> { ... }
//!   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^     ^
//!   ```
//!
//! * [`syn_mid::Block`] -- A block whose body is not parsed.
//!
//!   ```text
//!   { ... }
//!   ^     ^
//!   ```
//!
//! Other data structures are the same as data structures of [syn]. Also, if
//! the "full" feature is enabled, those items are reexported from [syn].
//!
//! Note that if you use [syn] with "full" feature and use syn-mid without
//! "full" feature at the same time, errors due to type mismatch may occur.
//!
//! ## Optional features
//!
//! syn-mid in the default features aims to provide the features between "full"
//! and "derive" of [syn].
//!
//! * **`derive`** *(enabled by default)* — Data structures for representing the
//!   possible input to a custom derive, including structs and enums and types.
//! * **`full`** — Data structures for representing the syntax tree of all valid
//!   Rust source code, including items and expressions.
//! * **`clone-impls`** *(enabled by default)* — Clone impls for all syntax tree
//!   types.
//! * **`extra-traits`** — Debug, Eq, PartialEq, Hash impls for all syntax tree
//!   types.
//!
//! Note that if both "derive" and "full" features are disabled, a compile error
//! occurs.
//!
//! [`syn_mid::ItemFn`]: struct.ItemFn.html
//! [`syn_mid::Block`]: struct.Block.html
//! [syn]: https://github.com/dtolnay/syn
//!

#![doc(html_root_url = "https://docs.rs/syn-mid/0.1.0")]
#![deny(unsafe_code)]
#![cfg_attr(
    feature = "cargo-clippy",
    allow(
        renamed_and_removed_lints,
        redundant_field_names, // Rust 1.17+ => remove
        const_static_lifetime, // Rust 1.17+ => remove
        deprecated_cfg_attr, // Rust 1.30+ => remove
        map_clone,
        large_enum_variant
    )
)]

#[cfg(not(any(feature = "full", feature = "derive")))]
compile_error!("To use this crate you need to enable \"derive\" or \"full\" feature");

// Many of the code contained in this crate are copies from https://github.com/dtolnay/syn.

extern crate proc_macro2;
extern crate quote;
#[allow(unused_imports)]
#[macro_use]
extern crate syn;

#[macro_use]
mod macros;

mod expr;
mod item;
#[cfg(not(feature = "full"))]
mod path;
#[cfg(not(feature = "full"))]
mod print;
#[cfg(feature = "extra-traits")]
mod tt;

pub use self::expr::*;
pub use self::item::*;

use proc_macro2::TokenStream;
#[cfg(not(feature = "full"))]
use syn::punctuated::Punctuated;
use syn::{token, Abi, AttrStyle, Attribute, Ident, Visibility};

#[cfg(feature = "extra-traits")]
use std::hash::{Hash, Hasher};
#[cfg(feature = "extra-traits")]
use tt::TokenStreamHelper;

ast_struct! {
    /// A braced block containing Rust statements.
    pub struct Block #manual_extra_traits {
        pub brace_token: token::Brace,
        /// Statements in a block
        pub stmts: TokenStream,
    }
}

#[cfg(feature = "extra-traits")]
impl Eq for Block {}

#[cfg(feature = "extra-traits")]
impl PartialEq for Block {
    fn eq(&self, other: &Self) -> bool {
        self.brace_token == other.brace_token
            && TokenStreamHelper(&self.stmts) == TokenStreamHelper(&other.stmts)
    }
}

#[cfg(feature = "extra-traits")]
impl Hash for Block {
    fn hash<H>(&self, state: &mut H)
    where
        H: Hasher,
    {
        self.brace_token.hash(state);
        TokenStreamHelper(&self.stmts).hash(state);
    }
}

ast_struct! {
    /// A free-standing function: `fn process(n: usize) -> Result<()> { ...
    /// }`.
    pub struct ItemFn {
        pub attrs: Vec<Attribute>,
        pub vis: Visibility,
        pub constness: Option<Token![const]>,
        pub unsafety: Option<Token![unsafe]>,
        pub asyncness: Option<Token![async]>,
        pub abi: Option<Abi>,
        pub ident: Ident,
        pub decl: Box<FnDecl>,
        pub block: Block,
    }
}

mod parsing {
    use syn::parse::{Parse, ParseStream, Result};
    use syn::{Abi, Attribute, Generics, Ident, ReturnType, Visibility, WhereClause};

    use super::*;

    fn attrs(outer: Vec<Attribute>, inner: Vec<Attribute>) -> Vec<Attribute> {
        let mut attrs = outer;
        attrs.extend(inner);
        attrs
    }

    impl Parse for ItemFn {
        fn parse(input: ParseStream) -> Result<Self> {
            let outer_attrs = input.call(Attribute::parse_outer)?;
            let vis: Visibility = input.parse()?;
            let constness: Option<Token![const]> = input.parse()?;
            let unsafety: Option<Token![unsafe]> = input.parse()?;
            let asyncness: Option<Token![async]> = input.parse()?;
            let abi: Option<Abi> = input.parse()?;
            let fn_token: Token![fn] = input.parse()?;
            let ident: Ident = input.parse()?;
            let generics: Generics = input.parse()?;

            let content;
            let paren_token = parenthesized!(content in input);
            let inputs = content.parse_terminated(FnArg::parse)?;

            let output: ReturnType = input.parse()?;
            let where_clause: Option<WhereClause> = input.parse()?;

            let content;
            let brace_token = braced!(content in input);
            let inner_attrs = content.call(Attribute::parse_inner)?;
            let stmts = content.parse()?;

            Ok(ItemFn {
                attrs: attrs(outer_attrs, inner_attrs),
                vis: vis,
                constness: constness,
                unsafety: unsafety,
                asyncness: asyncness,
                abi: abi,
                ident: ident,
                decl: Box::new(FnDecl {
                    fn_token: fn_token,
                    paren_token: paren_token,
                    inputs: inputs,
                    output: output,
                    variadic: None,
                    generics: Generics {
                        where_clause: where_clause,
                        ..generics
                    },
                }),
                block: Block {
                    brace_token: brace_token,
                    stmts: stmts,
                },
            })
        }
    }
}

mod printing {
    use proc_macro2::TokenStream;
    use quote::{ToTokens, TokenStreamExt};
    use std::iter;

    use super::*;

    impl ToTokens for Block {
        fn to_tokens(&self, tokens: &mut TokenStream) {
            self.brace_token.surround(tokens, |tokens| {
                tokens.append_all(self.stmts.clone());
            });
        }
    }

    trait FilterAttrs<'a> {
        type Ret: Iterator<Item = &'a Attribute>;

        fn outer(self) -> Self::Ret;
        fn inner(self) -> Self::Ret;
    }

    impl<'a, T> FilterAttrs<'a> for T
    where
        T: IntoIterator<Item = &'a Attribute>,
    {
        type Ret = iter::Filter<T::IntoIter, fn(&&Attribute) -> bool>;

        fn outer(self) -> Self::Ret {
            #[cfg_attr(feature = "cargo-clippy", allow(trivially_copy_pass_by_ref))]
            fn is_outer(attr: &&Attribute) -> bool {
                match attr.style {
                    AttrStyle::Outer => true,
                    _ => false,
                }
            }
            self.into_iter().filter(is_outer)
        }

        fn inner(self) -> Self::Ret {
            #[cfg_attr(feature = "cargo-clippy", allow(trivially_copy_pass_by_ref))]
            fn is_inner(attr: &&Attribute) -> bool {
                match attr.style {
                    AttrStyle::Inner(_) => true,
                    _ => false,
                }
            }
            self.into_iter().filter(is_inner)
        }
    }

    impl ToTokens for ItemFn {
        fn to_tokens(&self, tokens: &mut TokenStream) {
            tokens.append_all(self.attrs.outer());
            self.vis.to_tokens(tokens);
            self.constness.to_tokens(tokens);
            self.unsafety.to_tokens(tokens);
            self.asyncness.to_tokens(tokens);
            self.abi.to_tokens(tokens);
            NamedDecl(&self.decl, &self.ident).to_tokens(tokens);
            self.block.brace_token.surround(tokens, |tokens| {
                tokens.append_all(self.attrs.inner());
                tokens.append_all(self.block.stmts.clone());
            });
        }
    }

    struct NamedDecl<'a>(&'a FnDecl, &'a Ident);

    impl<'a> ToTokens for NamedDecl<'a> {
        fn to_tokens(&self, tokens: &mut TokenStream) {
            self.0.fn_token.to_tokens(tokens);
            self.1.to_tokens(tokens);
            self.0.generics.to_tokens(tokens);
            self.0.paren_token.surround(tokens, |tokens| {
                self.0.inputs.to_tokens(tokens);
                if self.0.variadic.is_some() && !self.0.inputs.empty_or_trailing() {
                    <Token![,]>::default().to_tokens(tokens);
                }
                self.0.variadic.to_tokens(tokens);
            });
            self.0.output.to_tokens(tokens);
            self.0.generics.where_clause.to_tokens(tokens);
        }
    }
}

#[cfg(feature = "full")]
mod convert {
    use quote::ToTokens;
    use syn;
    use syn::parse::{Parse, ParseStream, Result};

    use super::*;

    struct Parser(Vec<syn::Stmt>);

    impl Parse for Parser {
        fn parse(input: ParseStream) -> Result<Self> {
            input.call(syn::Block::parse_within).map(Parser)
        }
    }

    impl Into<syn::Block> for Block {
        fn into(self) -> syn::Block {
            syn::Block {
                brace_token: self.brace_token,
                stmts: syn::parse2::<Parser>(self.stmts)
                    .unwrap_or_else(|err| panic!("{}", err)) // https://github.com/dtolnay/syn/blob/0.15.26/src/parse_quote.rs#L102
                    .0,
            }
        }
    }

    impl From<syn::Block> for Block {
        fn from(other: ::syn::Block) -> Block {
            Block {
                brace_token: other.brace_token,
                stmts: other
                    .stmts
                    .into_iter()
                    .map(ToTokens::into_token_stream)
                    .collect(),
            }
        }
    }

    impl Into<syn::ItemFn> for ItemFn {
        fn into(self) -> ::syn::ItemFn {
            syn::ItemFn {
                attrs: self.attrs,
                vis: self.vis,
                constness: self.constness,
                unsafety: self.unsafety,
                asyncness: self.asyncness,
                abi: self.abi,
                ident: self.ident,
                decl: self.decl,
                block: Box::new(self.block.into()),
            }
        }
    }

    impl From<syn::ItemFn> for ItemFn {
        fn from(other: ::syn::ItemFn) -> ItemFn {
            ItemFn {
                attrs: other.attrs,
                vis: other.vis,
                constness: other.constness,
                unsafety: other.unsafety,
                asyncness: other.asyncness,
                abi: other.abi,
                ident: other.ident,
                decl: other.decl,
                block: (*other.block).into(),
            }
        }
    }

}