sails-macros-core 1.0.0

Implementations of procedural macros for the Sails framework
Documentation
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use proc_macro_error::abort;
use syn::{
    Ident, LitBool, LitStr, Path, Token,
    parse::{Parse, ParseStream},
    punctuated::Punctuated,
};

#[derive(PartialEq, Debug)]
pub(crate) struct ExportArgs {
    route: Option<String>,
    unwrap_result: bool,
    #[cfg(feature = "ethexe")]
    payable: bool,
    overrides: Option<Path>,
    entry_id: Option<u16>,
    scale: bool,
    #[cfg(feature = "ethexe")]
    ethabi: bool,
}

impl Default for ExportArgs {
    fn default() -> Self {
        Self {
            route: None,
            unwrap_result: false,
            #[cfg(feature = "ethexe")]
            payable: false,
            overrides: None,
            entry_id: None,
            scale: true,
            #[cfg(feature = "ethexe")]
            ethabi: true,
        }
    }
}

impl ExportArgs {
    pub fn route(&self) -> Option<&str> {
        self.route.as_deref()
    }

    pub fn unwrap_result(&self) -> bool {
        self.unwrap_result
    }

    #[cfg(feature = "ethexe")]
    pub fn payable(&self) -> bool {
        self.payable
    }

    pub fn overrides(&self) -> Option<&Path> {
        self.overrides.as_ref()
    }

    pub fn entry_id(&self) -> Option<u16> {
        self.entry_id
    }

    pub fn scale(&self) -> bool {
        self.scale
    }

    #[cfg(feature = "ethexe")]
    pub fn ethabi(&self) -> bool {
        self.ethabi
    }
}

impl Parse for ExportArgs {
    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
        let punctuated: Punctuated<ImportArg, Token![,]> = Punctuated::parse_terminated(input)?;
        let mut args = Self {
            route: None,
            unwrap_result: false,
            #[cfg(feature = "ethexe")]
            payable: false,
            overrides: None,
            entry_id: None,
            scale: false,
            #[cfg(feature = "ethexe")]
            ethabi: false,
        };
        let mut any_transport_flag_seen = false;
        let mut scale_seen = false;
        #[cfg(feature = "ethexe")]
        let mut ethabi_seen = false;
        #[cfg(feature = "ethexe")]
        let mut payable_span: Option<proc_macro2::Span> = None;

        for arg in punctuated {
            match arg {
                ImportArg::Route(route) => {
                    args.route = Some(route);
                }
                ImportArg::UnwrapResult(unwrap_result) => {
                    args.unwrap_result = unwrap_result;
                }
                #[cfg(feature = "ethexe")]
                ImportArg::Payable(span) => {
                    args.payable = true;
                    payable_span = Some(span);
                }
                ImportArg::Overrides(path) => {
                    args.overrides = Some(path);
                }
                ImportArg::EntryId(entry_id) => {
                    args.entry_id = Some(entry_id);
                }
                ImportArg::Scale(span) => {
                    if scale_seen {
                        return Err(syn::Error::new(
                            span,
                            "duplicate `scale` flag in `#[export]`",
                        ));
                    }
                    scale_seen = true;
                    any_transport_flag_seen = true;
                    args.scale = true;
                }
                #[cfg(feature = "ethexe")]
                ImportArg::Ethabi(span) => {
                    if ethabi_seen {
                        return Err(syn::Error::new(
                            span,
                            "duplicate `ethabi` flag in `#[export]`",
                        ));
                    }
                    ethabi_seen = true;
                    any_transport_flag_seen = true;
                    args.ethabi = true;
                }
            }
        }

        if !any_transport_flag_seen {
            args.scale = true;
            #[cfg(feature = "ethexe")]
            {
                args.ethabi = true;
            }
        }

        #[cfg(feature = "ethexe")]
        if let Some(span) = payable_span
            && !args.ethabi
        {
            return Err(syn::Error::new(
                span,
                "`payable` requires `ethabi` transport; write `#[export(ethabi, payable)]` or `#[export(scale, ethabi, payable)]`",
            ));
        }

        Ok(args)
    }
}

#[derive(Debug)]
enum ImportArg {
    Route(String),
    UnwrapResult(bool),
    #[cfg(feature = "ethexe")]
    Payable(proc_macro2::Span),
    Overrides(Path),
    EntryId(u16),
    Scale(proc_macro2::Span),
    #[cfg(feature = "ethexe")]
    Ethabi(proc_macro2::Span),
}

impl Parse for ImportArg {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let path = input.parse::<Path>()?;
        let ident = path.get_ident().unwrap();
        let ident_span = ident.span();
        match ident.to_string().as_str() {
            "route" => {
                input.parse::<Token![=]>()?;
                if let Ok(lit) = input.parse::<LitStr>() {
                    let route = lit.value();
                    _ = syn::parse_str::<Ident>(&route).map_err(|err| {
                        abort!(
                            lit.span(),
                            "`route` argument requires a literal with a valid Rust identifier: {}",
                            err
                        )
                    });
                    return Ok(Self::Route(route));
                }
                abort!(ident, "unexpected value for `route` argument: {}", input)
            }
            "unwrap_result" => {
                if input.parse::<Token![=]>().is_ok()
                    && let Ok(val) = input.parse::<LitBool>()
                {
                    return Ok(Self::UnwrapResult(val.value()));
                }
                Ok(Self::UnwrapResult(true))
            }
            #[cfg(feature = "ethexe")]
            "payable" => Ok(Self::Payable(ident_span)),
            "overrides" => {
                input.parse::<Token![=]>()?;
                let path = input.parse::<Path>()?;
                Ok(Self::Overrides(path))
            }
            "entry_id" => {
                input.parse::<Token![=]>()?;
                let lit = input.parse::<syn::LitInt>()?;
                let entry_id = lit.base10_parse::<u16>()?;
                Ok(Self::EntryId(entry_id))
            }
            "scale" => Ok(Self::Scale(ident_span)),
            #[cfg(feature = "ethexe")]
            "ethabi" => Ok(Self::Ethabi(ident_span)),
            _ => abort!(ident, "unknown argument: {}", ident),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use quote::quote;

    #[test]
    fn export_parse_args() {
        // arrange
        let input = quote!(route = "CallMe", unwrap_result);
        let expected = ExportArgs {
            route: Some("CallMe".to_owned()),
            unwrap_result: true,
            #[cfg(feature = "ethexe")]
            payable: false,
            overrides: None,
            entry_id: None,
            scale: true,
            #[cfg(feature = "ethexe")]
            ethabi: true,
        };

        // act
        let args = syn::parse2::<ExportArgs>(input).unwrap();

        // arrange
        assert_eq!(expected, args);
    }

    #[test]
    fn export_parse_args_unwrap_result() {
        // arrange
        let input = quote!(unwrap_result);
        let expected = ExportArgs {
            route: None,
            unwrap_result: true,
            #[cfg(feature = "ethexe")]
            payable: false,
            overrides: None,
            entry_id: None,
            scale: true,
            #[cfg(feature = "ethexe")]
            ethabi: true,
        };

        // act
        let args = syn::parse2::<ExportArgs>(input).unwrap();

        // arrange
        assert_eq!(expected, args);
    }

    #[test]
    fn export_parse_args_unwrap_result_eq_false() {
        // arrange
        let input = quote!(unwrap_result = false);
        let expected = ExportArgs {
            route: None,
            unwrap_result: false,
            #[cfg(feature = "ethexe")]
            payable: false,
            overrides: None,
            entry_id: None,
            scale: true,
            #[cfg(feature = "ethexe")]
            ethabi: true,
        };

        // act
        let args = syn::parse2::<ExportArgs>(input).unwrap();

        // arrange
        assert_eq!(expected, args);
    }

    #[cfg(feature = "ethexe")]
    #[test]
    fn export_parse_args_payable() {
        // arrange
        let input = quote!(payable);
        let expected = ExportArgs {
            route: None,
            unwrap_result: false,
            payable: true,
            overrides: None,
            entry_id: None,
            scale: true,
            ethabi: true,
        };

        // act
        let args = syn::parse2::<ExportArgs>(input).unwrap();

        // arrange
        assert_eq!(expected, args);
    }

    #[test]
    fn export_parse_args_overrides() {
        // arrange
        let input = quote!(overrides = BaseService, entry_id = 42);
        let expected_path: Path = syn::parse2(quote!(BaseService)).unwrap();
        let expected = ExportArgs {
            route: None,
            unwrap_result: false,
            #[cfg(feature = "ethexe")]
            payable: false,
            overrides: Some(expected_path),
            entry_id: Some(42),
            scale: true,
            #[cfg(feature = "ethexe")]
            ethabi: true,
        };

        // act
        let args = syn::parse2::<ExportArgs>(input).unwrap();

        // arrange
        assert_eq!(expected, args);
    }

    #[test]
    fn export_parse_args_scale_only() {
        let input = quote!(scale);
        let args = syn::parse2::<ExportArgs>(input).unwrap();

        assert!(args.scale());
        #[cfg(feature = "ethexe")]
        assert!(!args.ethabi());
    }

    #[cfg(feature = "ethexe")]
    #[test]
    fn export_parse_args_ethabi_only() {
        let input = quote!(ethabi);
        let args = syn::parse2::<ExportArgs>(input).unwrap();

        assert!(!args.scale());
        assert!(args.ethabi());
    }

    #[cfg(feature = "ethexe")]
    #[test]
    fn export_parse_args_scale_and_ethabi() {
        let input = quote!(scale, ethabi);
        let args = syn::parse2::<ExportArgs>(input).unwrap();

        assert!(args.scale());
        assert!(args.ethabi());
    }

    #[test]
    fn export_parse_args_default_is_both() {
        let input = quote!();
        let args = syn::parse2::<ExportArgs>(input).unwrap();

        assert!(args.scale());
        #[cfg(feature = "ethexe")]
        assert!(args.ethabi());
    }

    #[test]
    fn export_parse_args_duplicate_scale_errors() {
        let input = quote!(scale, scale);
        let err = syn::parse2::<ExportArgs>(input).unwrap_err();

        assert!(err.to_string().contains("duplicate `scale` flag"));
    }

    #[cfg(feature = "ethexe")]
    #[test]
    fn export_parse_args_duplicate_ethabi_errors() {
        let input = quote!(ethabi, ethabi);
        let err = syn::parse2::<ExportArgs>(input).unwrap_err();

        assert!(err.to_string().contains("duplicate `ethabi` flag"));
    }

    #[cfg(feature = "ethexe")]
    #[test]
    fn export_parse_args_payable_requires_ethabi() {
        let input = quote!(scale, payable);
        let err = syn::parse2::<ExportArgs>(input).unwrap_err();

        assert!(
            err.to_string()
                .contains("`payable` requires `ethabi` transport")
        );
    }

    #[cfg(feature = "ethexe")]
    #[test]
    fn export_parse_args_payable_with_ethabi_ok() {
        let input = quote!(ethabi, payable);
        let args = syn::parse2::<ExportArgs>(input).unwrap();

        assert!(!args.scale());
        assert!(args.ethabi());
        assert!(args.payable());
    }

    #[cfg(feature = "ethexe")]
    #[test]
    fn export_parse_args_plain_payable_ok_under_ethexe() {
        let input = quote!(payable);
        let args = syn::parse2::<ExportArgs>(input).unwrap();

        assert!(args.scale());
        assert!(args.ethabi());
        assert!(args.payable());
    }
}