rust-utils-macros 0.1.0

Procedural macros for the rust-utils crate
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
use proc_macro::TokenStream;
use syn::{
    parse_macro_input, parse_quote, Attribute, DeriveInput, GenericParam, ImplItemFn, ItemEnum, ItemStruct, PathArguments, TraitItemFn, Type, TypePath
};
use quote::quote;
use if_chain::if_chain;

mod chainable;
mod encapsulated;
mod config;

use config::*;
use chainable::*;
use encapsulated::*;

// helper macro to return a compiler error message
// if a ParseResult is an error
macro_rules! ok_or_compile_err {
    ($expr:expr) => {
        match $expr {
            Ok(val) => val,
            Err(why) => return why.into_compile_error().into()
        }
    }
}

// helper macro to return a compiler error message
// if an Option is None
macro_rules! some_or_compile_err {
    ($expr:expr, $reason:literal) => {
        if let Some(val) = $expr {
            val
        }
        else {
            return crate::quote_compile_err!($reason);
        }
    };

    ($expr:expr, $reason:expr) => {
        if let Some(val) = $expr {
            val
        }
        else {
            return crate::quote_compile_err!($reason);
        }
    }
}

// helper macro to create a TokenStream with a compile error message
macro_rules! quote_compile_err {
    ($msg:literal) => {
        quote::quote! {
            compile_error!($msg)
        }
    };

    ($msg:expr) => {
        {
            let msg = $msg;
            quote::quote! {
                compile_error!(#msg)
            }
        }
    }
}

use ok_or_compile_err;
use some_or_compile_err;
use quote_compile_err;

/// Convenience macro that generates builder-like chainable methods from setter or adder methods in an
/// inherent implementation, trait definition, or from fields in a `struct`
///
/// # Examples
///
/// ## On an inherent method
///
/// ```
/// struct Example {
///     field_0: bool,
///     opt_field: Option<usize>
/// }
///
/// impl Example {
///     fn new() -> Self {
///         Example {
///             field_0: false
///         }
///     }
///
///     #[chainable]
///     fn set_field_0(&mut self, val: bool) {
///         self.field_0 = val;
///     }
///
///     // this will make the generated method take usize as an argument
///     // instead of Option<usize>
///     #[chainable(collapse_options)]
///     fn set_opt_field(&mut self, opt_field: Option<usize>) {
///         self.opt_field = opt_field;
///     }
/// }
///
/// let example = Example::new().field_0(true);
/// println!("Value of field_0: {}", example.field_0);
/// ```
///
/// ## In a trait definition
///
/// To use the macro in a trait definition, it must be a subtrait of [`Sized`]. This macro
/// will also make a trait object unsafe
///
/// ```
/// pub trait ExampleTrait: Sized {
///     #[chainable]
///     fn set_something(&mut self, val: u32);
///
///     #[chainable]
///     fn set_something_else(&mut self, val: u32) {
///         self.set_something(val);
///     }
/// }
/// ```
///
///  ## In a struct definition
///
/// In a struct definition, the specified fields will have chainable methods generated for them
/// with the same visibility as that field
///
/// ```
/// #[derive(Default, Debug)]
/// #[chainable]
/// struct Example {
///     // generated chainable method with documentation
///     #[chainable(doc = "Documentation for `field_0`")]
///     field_0: bool,
///     field_1: usize,
///     field_2: f64,
/// 
///     // this will make the generated method take usize as an argument
///     // instead of Option<usize>
///     #[chainable(collapse_option)]
///     opt_field: Option<usize>
/// }
///
/// let example = Example::default()
///     .field_0(false)
///     .field_1(100)
///     .field_2(std::f64::consts::PI)
///     .opt_field(1);
///
/// println!("{example:?}");
/// ```
///
/// # Method Visibility
/// 
/// Methods generated by this macro have the same visibility as the annotated item
/// (if the struct field or method is `pub`, so will the generated methods)
/// 
/// # Options for struct fields:
///
/// ## `collapse_option`
///
/// If the field is `Option<T>`, make the generated chainable method take `T` as its argument
///
/// ## `use_into_impl`
///
/// Make the generated chainable method take `impl Into<T>` and convert it to the field's type
///
/// ## `doc = "Your documentation here"`
///
/// Creates documentation for the generated chainable method
///
/// # Options for setter and adder methods
///
/// ## `collapse_options`
///
/// If any methods are `Option<T>`, collapse them to their inner types
///
/// ## `use_into_impl`
///
/// Make all the methods take `Into<T>` and convert them to their input types
#[proc_macro_attribute]
pub fn chainable(attr_args: TokenStream, item: TokenStream) -> TokenStream {
    if let Ok(method) = syn::parse::<ImplItemFn>(item.clone()) {
        chainable_inh_method(method, attr_args)
    }
    else if let Ok(method) = syn::parse::<TraitItemFn>(item.clone()) {
        chainable_trait_method(method, attr_args)
    }
    else if let Ok(struct_def) = syn::parse::<ItemStruct>(item) {
        if !attr_args.is_empty() {
            quote_compile_err!("This attribute doesn't take any input!")
        }
        else {
            chainable_struct_fields(struct_def)
        }
    }
    else {
        quote! {
            compile_error!("This attribute can only be used on methods and structs!")
        }
    }
        .into()
}

/// Java style encapsulation for struct fields
///
/// # Example
/// ```
/// #[encapsulated]
/// pub struct Example {
///     // make the getter method copy the value instead
///     // returning a reference
///     #[getter(copy_val)]
///     #[setter]
///     a: usize,
///
///     // return a mutable reference
///     #[getter(mutable, doc = "Your documentation here")]
///     // create a setter method with an Into impl
///     #[setter(use_into_impl)]
///     b: f64,
///     c: f32,
///
///     #[setter]
///     // it also possible to create chainable methods with this macro
///     // (including with documentation)
///     #[chainable(doc = "Documentation for `field_0`")]
///     chainable: u32,
///
///     #[setter]
///     #[chainable(collapse_option)]
///     thing1: Option<u32>,
///
///     #[setter]
///     #[chainable(collapse_option, use_into_impl)]
///     thing2: Option<usize>
/// }
/// ```
///
/// # Method Visibility
/// 
/// Methods generated by this macro have the same visibility as the annotated struct
/// (if the struct is `pub`, so will the generated methods)
/// 
/// # Helper attributes:
/// 
/// ## `#[setter]`
/// 
/// Create a setter method for the annotated field
/// 
/// ### Options:
/// `use_into_impl`: Make the generated method take an [`Into`] implementation
/// of the field type and convert it
/// 
/// `doc = "Your documentation here"`: Creates documentation for the generated setter method
/// if `#[chainable]` is also specified for this field without documentation, the documentation from this
/// attribute is used for the chainable method
///
/// ## `#[getter]`
/// 
/// Create a setter method for the annotated field
/// 
/// ### Options:
/// `copy_val`: copy the field value instead of returning a reference. 
/// This only works if the field's type implements [`Copy`]!
/// 
/// `mutable`: Create a getter method that returns a mutable
/// reference to the field
///
/// `doc = "Your documentation here"`: Creates documentation for the generated setter method
/// 
/// ## `#[chainable]`
/// 
/// Works exactly like the [`macro@chainable`] macro on struct fields
#[proc_macro_attribute]
pub fn encapsulated(attr_args: TokenStream, item: TokenStream) -> TokenStream {
    if !attr_args.is_empty() {
        quote_compile_err!("This attribute doesn't take any input!")
    }
    else {
        let struct_def = ok_or_compile_err!(syn::parse::<ItemStruct>(item));
        encapsulated_struct(struct_def)
    }
        .into()
}

/// A macro that implements [`Default`] for a type if its inherent implementation has a `Self::new() -> Self` method
#[proc_macro]
pub fn new_default(input: TokenStream) -> TokenStream {
    let in_type = parse_macro_input!(input as Type);
    
    let generics = if_chain! {
        if let Type::Path(TypePath { path, .. }) = &in_type;
        if let Some(type_segment) = path.segments.last();
        if let PathArguments::AngleBracketed(type_args) = &type_segment.arguments;

        then {
            Some(type_args)
        }
        else { None }
    };

    quote! {
        impl #generics core::default::Default for #in_type {
            fn default() -> Self { Self::new() }
        }
    }
        .into()
}

/// A derive macro that implements an inherent `Self::new()` method if
/// [`Default`] is already implemented (can be derived)
#[proc_macro_derive(New)]
pub fn new_derive(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = input.ident;
    let mut generics = input.generics;

    for param in &mut generics.params {
        if let GenericParam::Type(ref mut type_param) = *param {
            type_param.bounds.push(parse_quote!(core::default::Default));
        }
    }

    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

    quote! {
        impl #impl_generics #name #ty_generics #where_clause {
            pub fn new() -> Self { Self::default() }
        }
    }
        .into()
}

/// [`Config`]: rust_utils::config::Config
/// [`Serialize`]: serde::Serialize
/// [`Deserialize`]: serde::Deserialize
///
/// Convenience macro to quickly create an implementation of the [`Config`] trait.
/// This also automatically implements the [`Serialize`] and [`Deserialize`] traits from
/// the [`serde`] crate (requires the feature `serde_derive`)
///
/// # Example
/// ```
/// #[config(file_name = "example.toml", save_dir = "example")]
/// pub struct ExampleConfig {
///     string: String,
///     number: u32,
///     boolean: bool
/// }
///
/// impl Default for ExampleConfig {
///     fn default() -> Self {
///         Self {
///             string: "string".into(),
///             number: 100,
///             boolean: true
///         }
///     }
/// }
/// ```
///
/// # Options
///
/// ## `file_name = "<file name here>"`
///
/// The file name of the config
///
/// ## `save_dir = "<save directory>"`
///
/// The path of the config file's folder relative to the config root (normally `$HOME/.config/`)
/// 
/// ## `cfg_type(<config type>)` (optional)
///
/// The type of config the file will be saved as.
///
/// Valid options are `toml` and `ron`
#[proc_macro_attribute]
pub fn config(attr_args: TokenStream, item: TokenStream) -> TokenStream {
    if let Ok(struct_def) = syn::parse::<ItemStruct>(item.clone()) {
        gen_config_impl(&struct_def, &struct_def.ident, &struct_def.generics, attr_args)
    }
    else if let Ok(enum_def) = syn::parse::<ItemEnum>(item) {
        gen_config_impl(&enum_def, &enum_def.ident, &enum_def.generics, attr_args)
    }
    else {
        quote_compile_err!("This attribute can only be used on structs and enums!")
    }
        .into()
}

fn gen_doc_attrs<S: AsRef<str>>(doc_string: S) -> Vec<Attribute> {
    let mut doc_attrs = Vec::new();
    for line in doc_string.as_ref().lines() {
        doc_attrs.push(
            parse_quote! { #[doc = #line] }
        );
    }

    doc_attrs
}