Skip to main content

attribute_derive/
syn_impls.rs

1use proc_macro2::{Group, Literal, Punct, TokenStream, TokenTree};
2use syn::token::{
3    Abstract, And, AndAnd, AndEq, As, Async, At, Auto, Await, Become, Break, Caret, CaretEq, Colon,
4    Comma, Const, Continue, Crate, Do, Dollar, Dot, DotDot, DotDotDot, DotDotEq, Dyn, Else, Enum,
5    Eq, EqEq, Extern, FatArrow, Final, Fn, For, Ge, Gt, If, Impl, In, LArrow, Le, Let, Loop, Lt,
6    Match, Minus, MinusEq, Mod, Move, Mut, Ne, Not, Or, OrEq, OrOr, Override, PathSep, Percent,
7    PercentEq, Plus, PlusEq, Pound, Priv, Pub, Question, RArrow, Ref, Return, SelfType, SelfValue,
8    Semi, Shl, ShlEq, Shr, ShrEq, Slash, SlashEq, Star, StarEq, Static, Struct, Super, Tilde,
9    Trait, Try, Typeof, Underscore, Union, Unsafe, Unsized, Use, Virtual, Where, While, Yield,
10};
11use syn::{
12    Abi, AngleBracketedGenericArguments, BinOp, BoundLifetimes, ConstParam, DeriveInput, Expr,
13    FieldsNamed, FieldsUnnamed, GenericArgument, GenericParam, Generics, Ident, Index, Lifetime,
14    Lit, LitBool, LitByteStr, LitChar, LitFloat, LitInt, LitStr, Member, Meta, MetaList,
15    MetaNameValue, ParenthesizedGenericArguments, Path, PathSegment, ReturnType, TraitBound, Type,
16    TypeArray, TypeFnPtr, TypeGroup, TypeImplTrait, TypeInfer, TypeMacro, TypeNever, TypeParam,
17    TypeParamBound, TypeParen, TypePath, TypePtr, TypeReference, TypeSlice, TypeTraitObject,
18    TypeTuple, UnOp, Variant, Visibility, WhereClause, WherePredicate,
19};
20
21use crate::parsing::*;
22use crate::*;
23
24/// Macro to easily implement [`AttributeValue`] for types implementing
25/// [`Parse`] and [`ToTokens`].
26#[macro_export]
27macro_rules! impl_Attribute_for_Parse_and_ToTokens {
28    ($($type:ty),+ $(,)?) => {$(
29        impl $crate::parsing::AttributeBase for $type {
30            type Partial = Self;
31        }
32
33        impl $crate::parsing::AttributeValue for $type {
34            fn parse_value(input: $crate::__private::syn::parse::ParseStream) -> $crate::__private::syn::Result<$crate::parsing::SpannedValue<Self::Partial>> {
35                input.parse().map($crate::parsing::SpannedValue::from_to_tokens)
36            }
37        }
38
39        impl $crate::parsing::PositionalValue for $type {}
40
41    )*}
42}
43
44impl AttributeBase for TokenStream {
45    type Partial = Self;
46}
47
48impl AttributeMeta for TokenStream {
49    fn parse_inner(input: ParseStream) -> Result<Self::Partial> {
50        input.parse()
51    }
52}
53
54// /// Macro to easily implement [`ConvertParsed`] for syn types.
55// macro_rules! ParseToTokensAttribute {
56//     ($(#[$meta:meta])* $type:path) => {
57//         $(#[$meta])*
58//         impl ConvertParsed for $type {
59//             type Type = $type;
60//             fn convert(s: Self) -> Result<Self> {
61//                 Ok(s)
62//             }
63//         }
64//     };
65//     [$($type:path),* $(,)?] => {
66//         $(
67//         impl ConvertParsed for $type {
68//             type Type = $type;
69//             fn convert(s: Self) -> Result<Self> {
70//                 Ok(s)
71//             }
72//             }
73//         )*
74//     };
75//     ($from:path => $to:path) => {
76//         impl ConvertParsed<$from> for $to {
77//             fn convert(value: $from) -> Result<$to> {
78//                 Ok(value.into())
79//             }
80//         }
81//     };
82//     ($from:path => $($to:path),+ : $with:path ) => {
83//         $(
84//             impl ConvertParsed for $to {
85//                 type Type = $from;
86//                 fn convert(value: $from) -> Result<$to> {
87//                     Ok($with(&value))
88//                 }
89//             }
90//         )*
91//     };
92//     ($from:path => $($to:path),+ :? $with:path ) => {
93//         $(
94//             impl ConvertParsed for $to {
95//                 type Type = $from;
96//                 fn convert(value: $from) -> Result<$to> {
97//                     $with(&value)
98//                 }
99//             }
100//         )*
101//     };
102// }
103
104impl_Attribute_for_Parse_and_ToTokens!(Type);
105impl_Attribute_for_Parse_and_ToTokens!(Path);
106impl_Attribute_for_Parse_and_ToTokens!(Lit);
107impl_Attribute_for_Parse_and_ToTokens![LitStr, LitByteStr, LitChar, LitInt, LitFloat, LitBool];
108impl_Attribute_for_Parse_and_ToTokens!(Expr);
109impl_Attribute_for_Parse_and_ToTokens![TokenTree, Group, Punct, Literal];
110
111// // TODO make this warning better visable
112// ParseToTokensAttribute! {
113//     /// Try to avoid using this, as it will consume everything behind, so it
114// needs to be defined as the     /// last parameter.
115//     ///
116//     /// In the future there might be something to allow better handling of
117// this (maybe by putting it     /// into `()`)
118//     TokenStream
119// }
120
121// Some probably useless stuff
122impl_Attribute_for_Parse_and_ToTokens![
123    Abi,
124    Abstract,
125    Plus,
126    PlusEq,
127    And,
128    AndAnd,
129    AndEq,
130    AngleBracketedGenericArguments,
131    As,
132    Async,
133    At,
134    Auto,
135    Await,
136    Not,
137    Become,
138    BinOp,
139    BoundLifetimes,
140    Break,
141    Caret,
142    CaretEq,
143    Colon,
144    PathSep,
145    Comma,
146    Const,
147    ConstParam,
148    Continue,
149    Crate,
150    DeriveInput,
151    Slash,
152    SlashEq,
153    Do,
154    Dollar,
155    Dot,
156    DotDot,
157    DotDotDot,
158    DotDotEq,
159    Dyn,
160    Else,
161    Enum,
162    Eq,
163    EqEq,
164    Extern,
165    FatArrow,
166    FieldsNamed,
167    FieldsUnnamed,
168    Final,
169    Fn,
170    For,
171    Ge,
172    GenericArgument,
173    GenericParam,
174    Generics,
175    Gt,
176    Ident,
177    If,
178    Impl,
179    In,
180    Index,
181    LArrow,
182    Le,
183    Let,
184    Lifetime,
185    Loop,
186    Lt,
187    Match,
188    Member,
189    Meta,
190    MetaList,
191    MetaNameValue,
192    Mod,
193    Move,
194    StarEq,
195    Mut,
196    Ne,
197    Or,
198    OrEq,
199    OrOr,
200    Override,
201    ParenthesizedGenericArguments,
202    PathSegment,
203    Pound,
204    Priv,
205    Pub,
206    Question,
207    RArrow,
208    Ref,
209    Percent,
210    PercentEq,
211    Return,
212    ReturnType,
213    SelfType,
214    SelfValue,
215    Semi,
216    Shl,
217    ShlEq,
218    Shr,
219    ShrEq,
220    Star,
221    Static,
222    Struct,
223    Minus,
224    MinusEq,
225    Super,
226    Tilde,
227    Trait,
228    TraitBound,
229    Try,
230    TypeArray,
231    TypeFnPtr,
232    TypeGroup,
233    TypeImplTrait,
234    TypeInfer,
235    TypeMacro,
236    TypeNever,
237    TypeParam,
238    TypeParamBound,
239    TypeParen,
240    TypePath,
241    TypePtr,
242    TypeReference,
243    TypeSlice,
244    TypeTraitObject,
245    TypeTuple,
246    Typeof,
247    UnOp,
248    Underscore,
249    Union,
250    Unsafe,
251    Unsized,
252    Use,
253    Variant,
254    Virtual,
255    Visibility,
256    Where,
257    WhereClause,
258    WherePredicate,
259    While,
260    Yield,
261    syn::Macro,
262    syn::token::Box,
263    syn::token::Default,
264    syn::token::Macro,
265    syn::token::Type,
266];
267
268#[cfg(feature = "syn-full")]
269mod syn_full {
270    use syn::{
271        Arm, Block, ExprArray, ExprAssign, ExprAsync, ExprBinary, ExprBlock, ExprBreak, ExprCall,
272        ExprCast, ExprClosure, ExprContinue, ExprField, ExprForLoop, ExprIf, ExprIndex, ExprLet,
273        ExprLit, ExprLoop, ExprMacro, ExprMatch, ExprMethodCall, ExprParen, ExprPath, ExprRange,
274        ExprReference, ExprRepeat, ExprReturn, ExprStruct, ExprTry, ExprTryBlock, ExprTuple,
275        ExprUnary, ExprUnsafe, ExprWhile, ExprYield, FieldValue, File, FnArg, ForeignItem,
276        ForeignItemFn, ForeignItemMacro, ForeignItemStatic, ForeignItemType, ImplItem,
277        ImplItemConst, ImplItemMacro, ImplItemType, Item, ItemConst, ItemEnum, ItemExternCrate,
278        ItemFn, ItemForeignMod, ItemImpl, ItemMacro, ItemMod, ItemStatic, ItemStruct, ItemTrait,
279        ItemTraitAlias, ItemType, ItemUnion, ItemUse, Label, RangeLimits, Receiver, Signature,
280        Stmt, TraitItem, TraitItemConst, TraitItemMacro, TraitItemType, UseTree,
281    };
282
283    impl_Attribute_for_Parse_and_ToTokens![
284        Arm,
285        Block,
286        ExprArray,
287        ExprAssign,
288        ExprAsync,
289        ExprBinary,
290        ExprBlock,
291        ExprBreak,
292        ExprCall,
293        ExprCast,
294        ExprClosure,
295        ExprContinue,
296        ExprField,
297        ExprForLoop,
298        ExprIf,
299        ExprIndex,
300        ExprLet,
301        ExprLit,
302        ExprLoop,
303        ExprMacro,
304        ExprMatch,
305        ExprMethodCall,
306        ExprParen,
307        ExprPath,
308        ExprRange,
309        ExprReference,
310        ExprRepeat,
311        ExprReturn,
312        ExprStruct,
313        ExprTry,
314        ExprTryBlock,
315        ExprTuple,
316        ExprUnary,
317        ExprUnsafe,
318        ExprWhile,
319        ExprYield,
320        FieldValue,
321        File,
322        FnArg,
323        ForeignItem,
324        ForeignItemFn,
325        ForeignItemMacro,
326        ForeignItemStatic,
327        ForeignItemType,
328        ImplItem,
329        ImplItemConst,
330        ImplItemMacro,
331        ImplItemType,
332        Item,
333        ItemConst,
334        ItemEnum,
335        ItemExternCrate,
336        ItemFn,
337        ItemForeignMod,
338        ItemImpl,
339        ItemMacro,
340        ItemMod,
341        ItemStatic,
342        ItemStruct,
343        ItemTrait,
344        ItemTraitAlias,
345        ItemType,
346        ItemUnion,
347        ItemUse,
348        Label,
349        RangeLimits,
350        Receiver,
351        Signature,
352        Stmt,
353        TraitItem,
354        TraitItemConst,
355        TraitItemMacro,
356        TraitItemType,
357        UseTree,
358    ];
359}