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
use proc_macro::TokenStream;
use quote::{format_ident, quote, ToTokens};
use syn::{
    parse::{Parse, ParseStream},
    parse_macro_input,
    spanned::Spanned,
    Error, ExprClosure, GenericArgument, Ident, Pat, PatType, Result, Token, Type, TypePath,
    Visibility,
};

/// Convenience macro that defines a guarded type that promises to be
/// always valid. It may be used in different ways, see examples section for details.
#[proc_macro]
pub fn define(input: TokenStream) -> TokenStream {
    let Define {
        vis,
        ident,
        ty,
        adjust,
        guard,
    } = parse_macro_input!(input as Define);

    let adjust_fn = match adjust {
        None => quote! {
            fn adjust(v: &mut Self::Target) {}
        },
        Some(AdjustClosure(closure)) => quote! {
            fn adjust(v: &mut Self::Target) {
                let adjust: fn(&mut Self::Target) = #closure;
                adjust(v);
            }
        },
    };

    let output = match guard {
        GuardClosure::Ensure(EnsureClosure(ensure_closure)) => {
            let guard_ident = format_ident!("{}Guard", ident);
            quote! {
               #[derive(Debug)]
                #vis struct #guard_ident;
                impl prae::EnsureGuard for #guard_ident {
                    type Target = #ty;
                    #adjust_fn
                    fn ensure(v: &Self::Target) -> bool {
                        let f: fn(&Self::Target) -> bool = #ensure_closure;
                        f(v)
                    }
                }
                #vis type #ident = prae::EnsureGuarded<#ty, #guard_ident>;
            }
        }
        GuardClosure::Validate(ValidateClosure(validate_closure, err_type)) => {
            let guard_ident = format_ident!("{}Guard", ident);
            quote! {
               #[derive(Debug)]
                #vis struct #guard_ident;
                impl prae::ValidateGuard<#err_type> for #guard_ident {
                    type Target = #ty;
                    #adjust_fn
                    fn validate(v: &Self::Target) -> Option<#err_type> {
                        let f: fn(&Self::Target) -> Option<#err_type> = #validate_closure;
                        f(v)
                    }
                }
                #vis type #ident = prae::ValidateGuarded<#ty, #err_type, #guard_ident>;
            }
        }
    };

    TokenStream::from(output)
}

struct Define {
    vis: Visibility,
    ident: Ident,
    ty: Type,
    adjust: Option<AdjustClosure>,
    guard: GuardClosure,
}

impl Parse for Define {
    fn parse(input: ParseStream) -> Result<Self> {
        // Parse type definition.
        let vis: Visibility = input.parse()?;
        let ident: Ident = input.parse()?;
        input.parse::<Token![:]>()?;
        let ty: Type = input.parse()?;

        // Parse adjust closure (it may not exist).
        let adjust = parse_adjust_closure_for_ty(&ty, input)?;

        // Parse guard closure (it must exist).
        let guard = parse_guard_closure_for_ty(&ty, input)?;

        Ok(Define {
            vis,
            ident,
            ty,
            adjust,
            guard,
        })
    }
}

// Closure that takes one argument by mutable reference and returns nothing.
struct AdjustClosure(ExprClosure);

fn parse_adjust_closure_for_ty(ty: &Type, input: ParseStream) -> Result<Option<AdjustClosure>> {
    // If there's no `adjust` keyword, return None.
    if !input.lookahead1().peek(kw::adjust) {
        return Ok(None);
    }

    // Parse the closure.
    input.parse::<kw::adjust>()?;
    let closure: ExprClosure = input.parse()?;

    // Validate the input of the closure.
    // Valid variants (`v` is an arbitrary name):
    // 1)  |v| ...
    // 2)  |v: &mut #ty| ...
    if closure.inputs.len() != 1 {
        return Err(Error::new(
            closure.inputs.span(),
            "closure must take exactly 1 argument",
        ));
    }
    let ty = ty.to_token_stream().to_string();
    let arg = closure.inputs.first().unwrap();
    match arg {
        Pat::Ident(_) => {}
        Pat::Type(PatType { ty: pty, .. })
            if pty.to_token_stream().to_string() == format!("& mut {}", ty) => {}
        _ => {
            return Err(Error::new(
                arg.span(),
                format!("must be ither `v` or `v: &mut {}`", ty),
            ))
        }
    }

    // Validate the output of the closure. It should be empty.
    if let syn::ReturnType::Type(_, _) = &closure.output {
        return Err(Error::new(
            closure.output.span(),
            "closure must not return anything",
        ));
    }

    Ok(Some(AdjustClosure(closure)))
}

// Either `ensure` or `validate` guard closure.
enum GuardClosure {
    Ensure(EnsureClosure),
    Validate(ValidateClosure),
}

fn parse_guard_closure_for_ty(ty: &Type, input: ParseStream) -> Result<GuardClosure> {
    let lk = input.lookahead1();
    if lk.peek(kw::ensure) {
        Ok(GuardClosure::Ensure(parse_ensure_closure_for_ty(
            ty, input,
        )?))
    } else if lk.peek(kw::validate) {
        Ok(GuardClosure::Validate(parse_validate_closure_for_ty(
            ty, input,
        )?))
    } else {
        Err(Error::new(
            input.span(),
            "expected `ensure` or `validate` after `adjust`",
        ))
    }
}

// Closure that takes one argument by shared reference and returns
// true if the given argument holds it's invariants and false, if it
// doesn't.
struct EnsureClosure(ExprClosure);

fn parse_ensure_closure_for_ty(ty: &Type, input: ParseStream) -> Result<EnsureClosure> {
    // Parse the closure.
    input.parse::<kw::ensure>()?;
    let closure: ExprClosure = input.parse()?;

    // Validate the input of the closure.
    // Valid variants (`v` is an arbitrary name):
    // 1)  |v| ...
    // 2)  |v: &#ty| ...
    if closure.inputs.len() != 1 {
        return Err(Error::new(
            closure.inputs.span(),
            "closure must take exactly 1 argument",
        ));
    }
    let ty = ty.to_token_stream().to_string();
    let arg = closure.inputs.first().unwrap();
    match arg {
        Pat::Ident(_) => {}
        Pat::Type(PatType { ty: pty, .. })
            if pty.to_token_stream().to_string() == format!("& {}", ty) => {}
        _ => {
            return Err(Error::new(
                arg.span(),
                format!("must be ither `v` or `v: &{}`", ty),
            ))
        }
    }

    // Validate the output of the closure.
    // Valid variants:
    // 1)  |...|
    // 2)  |...| -> bool
    if let syn::ReturnType::Type(_, ret_type) = &closure.output {
        if ret_type.to_token_stream().to_string() != "bool" {
            return Err(Error::new(ret_type.span(), "must be `bool`"));
        }
    }

    Ok(EnsureClosure(closure))
}

// Closure that takes one argument by shared reference and returns
// None if the given argument holds it's invariants and Some(YourError), if it
// doesn't.
struct ValidateClosure(ExprClosure, GenericArgument);

fn parse_validate_closure_for_ty(ty: &Type, input: ParseStream) -> Result<ValidateClosure> {
    // Parse the closure.
    input.parse::<kw::validate>()?;
    let closure: ExprClosure = input.parse()?;

    // Validate the input of the closure.
    // Valid variants (`v` is an arbitrary name):
    // 1)  |v| ...
    // 2)  |v: &#ty| ...
    if closure.inputs.len() != 1 {
        return Err(Error::new(
            closure.inputs.span(),
            "closure must take exactly 1 argument",
        ));
    }
    let ty = ty.to_token_stream().to_string();
    let arg = closure.inputs.first().unwrap();
    match arg {
        Pat::Ident(_) => {}
        Pat::Type(PatType { ty: pty, .. })
            if pty.to_token_stream().to_string() == format!("& {}", ty) => {}
        _ => {
            return Err(Error::new(
                arg.span(),
                format!("must be ither `v` or `v: &{}`", ty),
            ))
        }
    }

    // Validate the output of the closure. It must return `Option<E>`.
    // Otherwise we won't be able to extract the error type `E`.
    let mut err_type: Option<GenericArgument> = None;
    if let syn::ReturnType::Type(_, ret_type) = &closure.output {
        if let Type::Path(TypePath { path, .. }) = ret_type.as_ref() {
            let seg = path.segments.first().unwrap(); // is it safe?
            if let "Option" | "std::option::Option" = seg.ident.to_string().as_str() {
                if let syn::PathArguments::AngleBracketed(ab) = &seg.arguments {
                    err_type = Some(ab.args.first().unwrap().clone())
                }
            }
        }
    }
    if err_type.is_none() {
        return Err(Error::new(
            closure.span(),
            "closure specify return type Option<...>",
        ));
    }

    Ok(ValidateClosure(closure, err_type.unwrap()))
}

mod kw {
    syn::custom_keyword!(adjust);
    syn::custom_keyword!(ensure);
    syn::custom_keyword!(validate);
}