aboutsummaryrefslogtreecommitdiff
path: root/macros/src/test_utils.rs
blob: 471dc74a87fcf812781c78a9e459de3457248359 (plain)
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
use proc_macro2::{Ident, TokenStream};
use syn::punctuated::Punctuated;
use syn::token::{Colon, Gt, Lt, Paren, RArrow};
use syn::{
    AngleBracketedGenericArguments,
    Attribute,
    FnArg,
    GenericArgument,
    GenericParam,
    Generics,
    Pat,
    PatType,
    Path,
    PathArguments,
    PathSegment,
    Signature,
    Type,
    TypePath,
};

pub fn create_path(segments: &[PathSegment]) -> Path
{
    Path {
        leading_colon: None,
        segments: segments.iter().cloned().collect(),
    }
}

pub fn create_path_segment(ident: Ident, generic_arg_types: &[Type]) -> PathSegment
{
    PathSegment {
        ident,
        arguments: if generic_arg_types.is_empty() {
            PathArguments::None
        } else {
            PathArguments::AngleBracketed(AngleBracketedGenericArguments {
                colon2_token: None,
                lt_token: Lt::default(),
                args: generic_arg_types
                    .iter()
                    .map(|generic_arg_type| {
                        GenericArgument::Type(generic_arg_type.clone())
                    })
                    .collect(),
                gt_token: Gt::default(),
            })
        },
    }
}

pub fn create_type(path: Path) -> Type
{
    Type::Path(TypePath { qself: None, path })
}

pub fn create_generics<Params>(params: Params) -> Generics
where
    Params: IntoIterator<Item = GenericParam>,
{
    Generics {
        lt_token: None,
        params: Punctuated::from_iter(params),
        gt_token: None,
        where_clause: None,
    }
}

pub fn create_signature<ArgTypes>(
    ident: Ident,
    arg_types: ArgTypes,
    return_type: Type,
) -> Signature
where
    ArgTypes: IntoIterator<Item = (Type, Vec<Attribute>)>,
{
    Signature {
        constness: None,
        asyncness: None,
        unsafety: None,
        abi: None,
        fn_token: syn::token::Fn::default(),
        ident,
        generics: create_generics(vec![]),
        paren_token: Paren::default(),
        inputs: arg_types
            .into_iter()
            .map(|(arg_type, attrs)| {
                FnArg::Typed(PatType {
                    attrs,
                    pat: Box::new(Pat::Verbatim(TokenStream::new())),
                    colon_token: Colon::default(),
                    ty: Box::new(arg_type),
                })
            })
            .collect(),
        variadic: None,
        output: syn::ReturnType::Type(RArrow::default(), Box::new(return_type)),
    }
}