aboutsummaryrefslogtreecommitdiff
path: root/src/parse_attrs.rs
blob: 06a51230e3eafa98c6a97d088fe3488279781dde (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
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
use std::{
    collections::{HashMap, HashSet},
    rc::Rc,
};

use proc_macro2::{Group, TokenStream};
use quote::quote;
use syn::{
    braced, parenthesized, parse::Parse, spanned::Spanned, Attribute, Error, Ident, LitInt, Token,
    Type,
};

struct Collection {
    pub id: Ident,
    pub count: usize,
}

impl Parse for Collection {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let inner;
        parenthesized!(inner in input);

        let id: Ident = inner.parse()?;
        let _: Token![,] = inner.parse()?;
        let count_lit: LitInt = inner.parse()?;
        let count: usize = count_lit.base10_parse()?;
        if count < 1 {
            return Err(Error::new(
                count_lit.span(),
                "number of type parameters must be >= 1",
            ));
        }
        Ok(Self { id, count })
    }
}

#[derive(Default)]
pub struct TraitAttrs {
    pub blanket_impl_attrs: Vec<TokenStream>,
    pub dyn_trait_attrs: Vec<TokenStream>,
    pub dynamized_supertraits: HashSet<Ident>,
    pub collections: HashMap<Ident, usize>,
    pub type_conversions: HashMap<Type, Rc<Convert>>,
}

struct Dynamized {
    ident: Ident,
}

impl Parse for Dynamized {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let inner;
        parenthesized!(inner in input);
        Ok(Self {
            ident: inner.parse()?,
        })
    }
}

impl TraitAttrs {
    pub fn parse(attrs: &mut Vec<Attribute>) -> Result<Self, Error> {
        let mut parsed = TraitAttrs::default();
        // FUTURE: use Vec::drain_filter once it's stable
        let mut i = 0;
        while i < attrs.len() {
            if attrs[i].path.is_ident("blanket_impl_attr") {
                let attr = attrs.remove(i);
                let group: Group = match syn::parse2(attr.tokens) {
                    Ok(g) => g,
                    Err(err) => {
                        return Err(Error::new(
                            err.span(),
                            "expected parenthesis: #[blanket_impl_attr(...)]",
                        ))
                    }
                };
                let tokens = group.stream();
                parsed.blanket_impl_attrs.push(quote! {#[#tokens]});
            } else if attrs[i].path.is_ident("dyn_trait_attr") {
                let attr = attrs.remove(i);
                let group: Group = match syn::parse2(attr.tokens) {
                    Ok(g) => g,
                    Err(err) => {
                        return Err(Error::new(
                            err.span(),
                            "expected parenthesis: #[dyn_trait_attr(...)]",
                        ))
                    }
                };
                let tokens = group.stream();
                parsed.dyn_trait_attrs.push(quote! {#[#tokens]});
            } else if attrs[i].path.is_ident("convert") {
                let attr = attrs.remove(i);
                let convert: Convert = syn::parse2(attr.tokens)?;
                let span = convert.original_type.span();

                if parsed
                    .type_conversions
                    .insert(convert.original_type.clone(), Rc::new(convert))
                    .is_some()
                {
                    return Err(Error::new(
                        span,
                        format_args!("conversion is defined multiple times for this type"),
                    ));
                }
            } else if attrs[i].path.is_ident("collection") {
                let attr = attrs.remove(i);
                let coll: Collection = syn::parse2(attr.tokens)?;

                if parsed
                    .collections
                    .insert(coll.id.clone(), coll.count)
                    .is_some()
                {
                    return Err(Error::new(
                        coll.id.span(),
                        format_args!(
                            "collection `{}` is defined multiple times for this trait",
                            coll.id
                        ),
                    ));
                }
            } else if attrs[i].path.is_ident("dynamized") {
                let attr = attrs.remove(i);
                let dynamized: Dynamized = syn::parse2(attr.tokens)?;
                let span = dynamized.ident.span();

                if !parsed.dynamized_supertraits.insert(dynamized.ident) {
                    // FUTURE: relax to warning once proc_macro::Diagnostic is stable
                    return Err(Error::new(
                        span,
                        format_args!("dynamized attribute is defined multiple times"),
                    ));
                }
            } else {
                i += 1;
            }
        }
        Ok(parsed)
    }
}

#[derive(Debug, Clone)]
pub struct Convert {
    pub ident: Ident,
    pub original_type: Type,
    pub dest_type: Type,
    pub block: TokenStream,
}

impl Parse for Convert {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let _: Token![=] = input.parse()?;
        let _: Token![|] = input.parse()?;
        let param: Ident = input.parse()?;
        let _: Token![:] = input.parse()?;
        let original_type: Type = input.parse()?;
        let _: Token![|] = input.parse()?;
        let _: Token![->] = input.parse()?;
        let dest_type: Type = input.parse()?;

        let inner;
        braced!(inner in input);

        Ok(Self {
            ident: param,
            original_type,
            dest_type,
            block: inner.parse()?,
        })
    }
}