hax_lib_protocol_macros/
lib.rs

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
use quote::quote;
use syn::{parse, parse_macro_input};

/// This macro takes an `fn` as the basis of an `InitialState` implementation
/// for the state type that is returned by the `fn` (on success).
///
/// The `fn` is expected to build the state type specified as a `Path` attribute
/// argument from a `Vec<u8>`, i.e. the signature should be compatible with
/// `TryFrom<Vec<u8>>` for the state type given as argument to the macro.
///
/// Example:
/// ```ignore
/// pub struct A0 {
///   data: u8,
/// }
///
/// #[hax_lib_protocol_macros::init(A0)]
/// fn init_a(prologue: Vec<u8>) -> ::hax_lib_protocol::ProtocolResult<A0> {
///     if prologue.len() < 1 {
///        return Err(::hax_lib_protocol::ProtocolError::InvalidPrologue);
///     }
///     Ok(A0 { data: prologue[0] })
/// }
///
/// // The following is generated by the macro:
/// #[hax_lib::exclude]
/// impl TryFrom<Vec<u8>> for A0 {
///     type Error = ::hax_lib_protocol::ProtocolError;
///     fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
///         init_a(value)
///     }
/// }
/// #[hax_lib::exclude]
/// impl InitialState for A0 {
///     fn init(prologue: Option<Vec<u8>>) -> ::hax_lib_protocol::ProtocolResult<Self> {
///         if let Some(prologue) = prologue {
///             prologue.try_into()
///         } else {
///             Err(::hax_lib_protocol::ProtocolError::InvalidPrologue)
///         }
///     }
/// }
/// ```
#[proc_macro_attribute]
pub fn init(
    attr: proc_macro::TokenStream,
    item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
    let mut output = quote!(#[hax_lib::process_init]);
    output.extend(proc_macro2::TokenStream::from(item.clone()));

    let input: syn::ItemFn = parse_macro_input!(item);
    let return_type: syn::Path = parse_macro_input!(attr);
    let name = input.sig.ident;

    let expanded = quote!(
        #[hax_lib::exclude]
        impl TryFrom<Vec<u8>> for #return_type {
            type Error = ::hax_lib_protocol::ProtocolError;

            fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
                #name(value)
            }
        }

        #[hax_lib::exclude]
        impl InitialState for #return_type {
            fn init(prologue: Option<Vec<u8>>) -> ::hax_lib_protocol::ProtocolResult<Self> {
                if let Some(prologue) = prologue {
                    prologue.try_into()
                } else {
                    Err(::hax_lib_protocol::ProtocolError::InvalidPrologue)
                }
            }
        }
    );
    output.extend(expanded);

    output.into()
}

/// This macro takes an `fn` as the basis of an `InitialState` implementation
/// for the state type that is returned by the `fn` (on success).
///
/// The `fn` is expected to build the state type specified as a `Path` attribute
/// argument without additional input.
/// Example:
/// ```ignore
/// pub struct B0 {}
///
/// #[hax_lib_protocol_macros::init_empty(B0)]
/// fn init_b() -> ::hax_lib_protocol::ProtocolResult<B0> {
///    Ok(B0 {})
/// }
///
/// // The following is generated by the macro:
/// #[hax_lib::exclude]
/// impl InitialState for B0 {
///     fn init(prologue: Option<Vec<u8>>) -> ::hax_lib_protocol::ProtocolResult<Self> {
///         if let Some(_) = prologue {
///             Err(::hax_lib_protocol::ProtocolError::InvalidPrologue)
///         } else {
///             init_b()
///         }
///     }
/// }
/// ```
#[proc_macro_error::proc_macro_error]
#[proc_macro_attribute]
pub fn init_empty(
    attr: proc_macro::TokenStream,
    item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
    let mut output = quote!(#[hax_lib::process_init]);
    output.extend(proc_macro2::TokenStream::from(item.clone()));

    let input: syn::ItemFn = parse_macro_input!(item);
    let return_type: syn::Path = parse_macro_input!(attr);
    let name = input.sig.ident;

    let expanded = quote!(
        #[hax_lib::exclude]
        impl InitialState for #return_type {
            fn init(prologue: Option<Vec<u8>>) -> ::hax_lib_protocol::ProtocolResult<Self> {
                if let Some(_) = prologue {
                    Err(::hax_lib_protocol::ProtocolError::InvalidPrologue)
                } else {
                    #name()
                }
            }
        }
    );
    output.extend(expanded);

    return output.into();
}

/// A structure to parse transition tuples from `read` and `write` macros.
struct Transition {
    /// `Path` to the current state type of the transition.
    pub current_state: syn::Path,
    /// `Path` to the destination state type of the transition.
    pub next_state: syn::Path,
    /// `Path` to the message type this transition is based on.
    pub message_type: syn::Path,
}

impl syn::parse::Parse for Transition {
    fn parse(input: parse::ParseStream) -> syn::Result<Self> {
        use syn::spanned::Spanned;
        let punctuated =
            syn::punctuated::Punctuated::<syn::Path, syn::Token![,]>::parse_terminated(input)?;
        if punctuated.len() != 3 {
            Err(syn::Error::new(
                punctuated.span(),
                "Insufficient number of arguments",
            ))
        } else {
            let mut args = punctuated.into_iter();
            Ok(Self {
                current_state: args.next().unwrap(),
                next_state: args.next().unwrap(),
                message_type: args.next().unwrap(),
            })
        }
    }
}

/// Macro deriving a `WriteState` implementation for the origin state type,
/// generating a message of `message_type` and a new state, as indicated by the
/// transition tuple.
///
/// Example:
/// ```ignore
/// #[hax_lib_protocol_macros::write(A0, A1, Message)]
/// fn write_ping(state: A0) -> ::hax_lib_protocol::ProtocolResult<(A1, Message)> {
///    Ok((A1 {}, Message::Ping(state.data)))
/// }
///
/// // The following is generated by the macro:
/// #[hax_lib::exclude]
/// impl TryFrom<A0> for (A1, Message) {
///    type Error = ::hax_lib_protocol::ProtocolError;
///
///    fn try_from(value: A0) -> Result<Self, Self::Error> {
///       write_ping(value)
///    }
/// }
///
/// #[hax_lib::exclude]
/// impl WriteState for A0 {
///    type NextState = A1;
///    type Message = Message;
///
///    fn write(self) -> ::hax_lib_protocol::ProtocolResult<(Self::NextState, Message)> {
///        self.try_into()
///    }
/// }
/// ```
#[proc_macro_attribute]
pub fn write(
    attr: proc_macro::TokenStream,
    item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
    let mut output = quote!(#[hax_lib::process_write]);
    output.extend(proc_macro2::TokenStream::from(item.clone()));

    let input: syn::ItemFn = parse_macro_input!(item);
    let Transition {
        current_state,
        next_state,
        message_type,
    } = parse_macro_input!(attr);

    let name = input.sig.ident;

    let expanded = quote!(
        #[hax_lib::exclude]
        impl TryFrom<#current_state> for (#next_state, #message_type) {
            type Error = ::hax_lib_protocol::ProtocolError;

            fn try_from(value: #current_state) -> Result<Self, Self::Error> {
                #name(value)
            }
        }

        #[hax_lib::exclude]
        impl WriteState for #current_state {
            type NextState = #next_state;
            type Message = #message_type;

            fn write(self) -> ::hax_lib_protocol::ProtocolResult<(Self::NextState, Self::Message)> {
                self.try_into()
            }
        }
    );
    output.extend(expanded);

    output.into()
}

/// Macro deriving a `ReadState` implementation for the destination state type,
/// consuming a message of `message_type` and the current state, as indicated by
/// the transition tuple.
///
/// Example:
/// ```ignore
/// #[hax_lib_protocol_macros::read(A1, A2, Message)]
/// fn read_pong(_state: A1, msg: Message) -> ::hax_lib_protocol::ProtocolResult<A2> {
///     match msg {
///         Message::Ping(_) => Err(::hax_lib_protocol::ProtocolError::InvalidMessage),
///         Message::Pong(received) => Ok(A2 { received }),
///     }
/// }
/// // The following is generated by the macro:
/// #[hax_lib::exclude]
/// impl TryFrom<(A1, Message)> for A2 {
///     type Error = ::hax_lib_protocol::ProtocolError;
///     fn try_from((state, msg): (A1, Message)) -> Result<Self, Self::Error> {
///         read_pong(state, msg)
///     }
/// }
/// #[hax_lib::exclude]
/// impl ReadState<A2> for A1 {
///     type Message = Message;
///     fn read(self, msg: Message) -> ::hax_lib_protocol::ProtocolResult<A2> {
///         A2::try_from((self, msg))
///     }
/// }
/// ```
#[proc_macro_attribute]
pub fn read(
    attr: proc_macro::TokenStream,
    item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
    let mut output = quote!(#[hax_lib::process_read]);
    output.extend(proc_macro2::TokenStream::from(item.clone()));

    let input: syn::ItemFn = parse_macro_input!(item);
    let Transition {
        current_state,
        next_state,
        message_type,
    } = parse_macro_input!(attr);

    let name = input.sig.ident;

    let expanded = quote!(
        #[hax_lib::exclude]
        impl TryFrom<(#current_state, #message_type)> for #next_state {
            type Error = ::hax_lib_protocol::ProtocolError;

            fn try_from((state, msg): (#current_state, #message_type)) -> Result<Self, Self::Error> {
                #name(state, msg)
            }
        }

        #[hax_lib::exclude]
        impl ReadState<#next_state> for #current_state {
            type Message = #message_type;
            fn read(self, msg: Self::Message) -> ::hax_lib_protocol::ProtocolResult<#next_state> {
                #next_state::try_from((self, msg))
            }
        }
    );
    output.extend(expanded);

    output.into()
}