aliri_braid_impl 0.4.0

Implementation macros for the `aliri_braid` 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
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
use quote::{quote, ToTokens};

use super::{impls::ToImpl, AttrList, CheckMode, Field, Impls, StdLib};

pub struct OwnedCodeGen<'a> {
    pub common_attrs: &'a [syn::Attribute],
    pub attrs: &'a AttrList,
    pub body: &'a syn::ItemStruct,
    pub ty: &'a syn::Ident,
    pub field: &'a Field,
    pub check_mode: &'a CheckMode,
    pub ref_ty: &'a syn::Type,
    pub std_lib: &'a StdLib,
    pub expose_inner: bool,
    pub impls: &'a Impls,
}

impl<'a> OwnedCodeGen<'a> {
    fn constructor(&self) -> proc_macro2::TokenStream {
        match &self.check_mode {
            CheckMode::None => self.infallible_constructor(),
            CheckMode::Validate(validator) => self.fallible_constructor(validator),
            CheckMode::Normalize(normalizer) => self.normalized_constructor(normalizer),
        }
    }

    fn infallible_constructor(&self) -> proc_macro2::TokenStream {
        let doc_comment = format!("Constructs a new {}", self.ty);
        let static_doc_comment = format!("{doc_comment} from a static reference");

        let param = self.field.name.input_name();
        let create = self.field.self_constructor();
        let ref_ty = self.ref_ty;
        let field_ty = &self.field.ty;
        let alloc = self.std_lib.alloc();

        let vis = self
            .expose_inner
            .then(|| proc_macro2::Ident::new("pub", proc_macro2::Span::call_site()));

        quote! {
            #[doc = #doc_comment]
            #[inline]
            #vis const fn new(#param: #field_ty) -> Self {
                #create
            }

            #[inline]
            #[doc = #static_doc_comment]
            #[track_caller]
            pub fn from_static(raw: &'static str) -> Self {
                ::#alloc::borrow::ToOwned::to_owned(#ref_ty::from_static(raw))
            }
        }
    }

    fn fallible_constructor(&self, validator: &syn::Type) -> proc_macro2::TokenStream {
        let validator_tokens = validator.to_token_stream();
        let doc_comment = format!(
            "Constructs a new {} if it conforms to [`{}`]",
            self.ty, validator_tokens
        );

        let static_doc_comment = format!(
            "Constructs a new {} from a static reference if it conforms to [`{}`]",
            self.ty, validator_tokens
        );

        let doc_comment_unsafe = format!(
            "Constructs a new {} without validation\n\n# Safety\n\nConsumers of this function \
             must ensure that values conform to [`{}`]. Failure to maintain this invariant may \
             lead to undefined behavior.",
            self.ty, validator_tokens
        );

        let validator = crate::as_validator(validator);
        let param = self.field.name.input_name();
        let create = self.field.self_constructor();
        let ref_ty = self.ref_ty;
        let field_ty = &self.field.ty;
        let core = self.std_lib.core();
        let alloc = self.std_lib.alloc();

        let vis = self
            .expose_inner
            .then(|| proc_macro2::Ident::new("pub", proc_macro2::Span::call_site()));

        quote! {
            #[doc = #doc_comment]
            #[inline]
            #vis fn new(#param: #field_ty) -> ::#core::result::Result<Self, #validator::Error> {
                #validator::validate(#param.as_ref())?;
                ::#core::result::Result::Ok(#create)
            }

            #[doc = #doc_comment_unsafe]
            #[allow(unsafe_code)]
            #[inline]
            #vis const unsafe fn new_unchecked(#param: #field_ty) -> Self {
                #create
            }

            #[inline]
            #[doc = #static_doc_comment]
            #[doc = ""]
            #[doc = "# Panics"]
            #[doc = ""]
            #[doc = "This function will panic if the provided raw string is not valid."]
            #[track_caller]
            pub fn from_static(raw: &'static str) -> Self {
                ::#alloc::borrow::ToOwned::to_owned(#ref_ty::from_static(raw))
            }
        }
    }

    fn normalized_constructor(&self, normalizer: &syn::Type) -> proc_macro2::TokenStream {
        let normalizer_tokens = normalizer.to_token_stream();
        let doc_comment = format!(
            "Constructs a new {} if it conforms to [`{}`] and normalizes the input",
            self.ty, normalizer_tokens
        );

        let static_doc_comment = format!(
            "Constructs a new {} from a static reference if it conforms to [`{}`], normalizing \
             the input",
            self.ty, normalizer_tokens
        );

        let doc_comment_unsafe = format!(
            "Constructs a new {} without validation or normalization\n\n# Safety\n\nConsumers of \
             this function must ensure that values conform to [`{}`] and are in normalized form. \
             Failure to maintain this invariant may lead to undefined behavior.",
            self.ty, normalizer_tokens
        );

        let ty = self.ty;
        let validator = crate::as_validator(normalizer);
        let normalizer = crate::as_normalizer(normalizer);
        let param = self.field.name.input_name();
        let create = self.field.self_constructor();
        let ref_ty = self.ref_ty;
        let field_ty = &self.field.ty;
        let core = self.std_lib.core();

        let vis = self
            .expose_inner
            .then(|| proc_macro2::Ident::new("pub", proc_macro2::Span::call_site()));

        quote! {
            #[doc = #doc_comment]
            #[inline]
            #vis fn new(#param: #field_ty) -> ::#core::result::Result<Self, #validator::Error> {
                let #param = ::#core::convert::From::from(#normalizer::normalize(#param.as_ref())?);
                ::#core::result::Result::Ok(#create)
            }

            #[doc = #doc_comment_unsafe]
            #[allow(unsafe_code)]
            #[inline]
            #vis const unsafe fn new_unchecked(#param: #field_ty) -> Self {
                #create
            }

            #[inline]
            #[doc = #static_doc_comment]
            #[doc = ""]
            #[doc = "# Panics"]
            #[doc = ""]
            #[doc = "This function will panic if the provided raw string is not valid."]
            #[track_caller]
            pub fn from_static(raw: &'static str) -> Self {
                #ref_ty::from_str(raw).expect(concat!("invalid ", stringify!(#ty))).into_owned()
            }
        }
    }

    fn make_into_boxed_ref(&self) -> proc_macro2::TokenStream {
        let doc = format!(
            "Converts this `{}` into a [`Box<{}>`]\n\nThis will drop any excess capacity.",
            self.ty,
            self.ref_ty.to_token_stream(),
        );

        let ref_type = self.ref_ty;
        let field = &self.field.name;
        let alloc = self.std_lib.alloc();
        let box_pointer_reinterpret_safety_comment = {
            let doc = format!(
                "SAFETY: `{ty}` is `#[repr(transparent)]` around a single `str` field, so a `*mut \
                 str` can be safely reinterpreted as a `*mut {ty}`",
                ty = self.ref_ty.to_token_stream(),
            );

            quote! {
                #[doc = #doc]
                fn ptr_safety_comment() {}
            }
        };

        quote! {
            #[doc = #doc]
            #[allow(unsafe_code)]
            #[inline]
            pub fn into_boxed_ref(self) -> ::#alloc::boxed::Box<#ref_type> {
                #box_pointer_reinterpret_safety_comment
                let box_str = ::#alloc::string::String::from(self.#field).into_boxed_str();
                unsafe { ::#alloc::boxed::Box::from_raw(::#alloc::boxed::Box::into_raw(box_str) as *mut #ref_type) }
            }
        }
    }

    fn make_take(&self) -> proc_macro2::TokenStream {
        let field = &self.field.name;
        let field_ty = &self.field.ty;
        let doc = format!(
            "Unwraps the underlying [`{}`] value",
            field_ty.to_token_stream()
        );

        let vis = self
            .expose_inner
            .then(|| proc_macro2::Ident::new("pub", proc_macro2::Span::call_site()));

        quote! {
            #[doc = #doc]
            #[inline]
            #vis fn take(self) -> #field_ty {
                self.#field
            }
        }
    }

    fn inherent(&self) -> proc_macro2::TokenStream {
        let name = self.ty;
        let constructor = self.constructor();
        let into_boxed_ref = self.make_into_boxed_ref();
        let into_string = self.make_take();

        quote! {
            #[automatically_derived]
            impl #name {
                #constructor
                #into_boxed_ref
                #into_string
            }
        }
    }

    fn common_conversion(&self) -> proc_macro2::TokenStream {
        let ty = self.ty;
        let field_name = &self.field.name;
        let ref_ty = self.ref_ty;
        let core = self.std_lib.core();
        let alloc = self.std_lib.alloc();

        quote! {
            #[automatically_derived]
            impl ::#core::convert::From<&'_ #ref_ty> for #ty {
                #[inline]
                fn from(s: &#ref_ty) -> Self {
                    ::#alloc::borrow::ToOwned::to_owned(s)
                }
            }

            #[automatically_derived]
            impl ::#core::convert::From<#ty> for ::#alloc::string::String {
                #[inline]
                fn from(s: #ty) -> Self {
                    ::#core::convert::From::from(s.#field_name)
                }
            }

            #[automatically_derived]
            impl ::#core::borrow::Borrow<#ref_ty> for #ty {
                #[inline]
                fn borrow(&self) -> &#ref_ty {
                    ::#core::ops::Deref::deref(self)
                }
            }

            #[automatically_derived]
            impl ::#core::convert::AsRef<#ref_ty> for #ty {
                #[inline]
                fn as_ref(&self) -> &#ref_ty {
                    ::#core::ops::Deref::deref(self)
                }
            }

            #[automatically_derived]
            impl ::#core::convert::AsRef<str> for #ty {
                #[inline]
                fn as_ref(&self) -> &str {
                    self.as_str()
                }
            }


            #[automatically_derived]
            impl ::#core::convert::From<#ty> for ::#alloc::boxed::Box<#ref_ty> {
                #[inline]
                fn from(r: #ty) -> Self {
                    r.into_boxed_ref()
                }
            }

            #[automatically_derived]
            impl ::#core::convert::From<::#alloc::boxed::Box<#ref_ty>> for #ty {
                #[inline]
                fn from(r: ::#alloc::boxed::Box<#ref_ty>) -> Self {
                    r.into_owned()
                }
            }

            #[automatically_derived]
            impl<'a> ::#core::convert::From<::#alloc::borrow::Cow<'a, #ref_ty>> for #ty {
                #[inline]
                fn from(r: ::#alloc::borrow::Cow<'a, #ref_ty>) -> Self {
                    match r {
                        ::#alloc::borrow::Cow::Borrowed(b) => ::#alloc::borrow::ToOwned::to_owned(b),
                        ::#alloc::borrow::Cow::Owned(o) => o,
                    }
                }
            }

            #[automatically_derived]
            impl<'a> ::#core::convert::From<#ty> for ::#alloc::borrow::Cow<'a, #ref_ty> {
                #[inline]
                fn from(owned: #ty) -> Self {
                    ::#alloc::borrow::Cow::Owned(owned)
                }
            }
        }
    }

    fn infallible_conversion(&self) -> proc_macro2::TokenStream {
        let ty = self.ty;
        let ref_ty = self.ref_ty;
        let field_name = &self.field.name;
        let core = self.std_lib.core();
        let alloc = self.std_lib.alloc();

        quote! {
            #[automatically_derived]
            impl ::#core::convert::From<::#alloc::string::String> for #ty {
                #[inline]
                fn from(s: ::#alloc::string::String) -> Self {
                    Self::new(From::from(s))
                }
            }

            #[automatically_derived]
            impl ::#core::convert::From<&'_ str> for #ty {
                #[inline]
                fn from(s: &str) -> Self {
                    Self::new(::#core::convert::From::from(s))
                }
            }

            #[automatically_derived]
            impl ::#core::convert::From<::#alloc::boxed::Box<str>> for #ty {
                #[inline]
                fn from(s: ::#alloc::boxed::Box<str>) -> Self {
                    Self::new(::#core::convert::From::from(s))
                }
            }

            #[automatically_derived]
            impl ::#core::str::FromStr for #ty {
                type Err = ::#core::convert::Infallible;

                #[inline]
                fn from_str(s: &str) -> ::#core::result::Result<Self, Self::Err> {
                    ::#core::result::Result::Ok(::#core::convert::From::from(s))
                }
            }

            #[automatically_derived]
            impl ::#core::borrow::Borrow<str> for #ty {
                #[inline]
                fn borrow(&self) -> &str {
                    self.as_str()
                }
            }

            #[automatically_derived]
            impl ::#core::ops::Deref for #ty {
                type Target = #ref_ty;

                #[inline]
                fn deref(&self) -> &Self::Target {
                    #ref_ty::from_str(::#core::convert::AsRef::as_ref(&self.#field_name))
                }
            }
        }
    }

    fn unchecked_safety_comment(is_normalized: bool) -> proc_macro2::TokenStream {
        let doc = format!(
            "SAFETY: The value was satisfies the type's invariant and conforms to the required \
             implicit contracts of the {}.",
            if is_normalized {
                "normalizer"
            } else {
                "validator"
            },
        );

        quote! {
            #[doc = #doc]
            fn unchecked_safety_comment() {}
        }
    }

    fn fallible_conversion(&self, validator: &syn::Type) -> proc_macro2::TokenStream {
        let ty = self.ty;
        let ref_ty = self.ref_ty;
        let field_name = &self.field.name;
        let field_ty = &self.field.ty;
        let validator = crate::as_validator(validator);
        let core = self.std_lib.core();
        let alloc = self.std_lib.alloc();
        let unchecked_safety_comment = Self::unchecked_safety_comment(false);

        quote! {
            #[automatically_derived]
            impl ::#core::convert::TryFrom<::#alloc::string::String> for #ty {
                type Error = #validator::Error;

                #[inline]
                fn try_from(s: ::#alloc::string::String) -> ::#core::result::Result<Self, Self::Error> {
                    const fn ensure_try_from_string_error_converts_to_validator_error<T: ?Sized + From<<#field_ty as ::#core::convert::TryFrom<::#alloc::string::String>>::Error>>() {}
                    ensure_try_from_string_error_converts_to_validator_error::<Self::Error>();

                    Self::new(::#core::convert::TryFrom::try_from(s)?)
                }
            }

            #[automatically_derived]
            impl ::#core::convert::TryFrom<&'_ str> for #ty {
                type Error = #validator::Error;

                #[inline]
                fn try_from(s: &str) -> ::#core::result::Result<Self, Self::Error> {
                    let ref_ty = #ref_ty::from_str(s)?;
                    ::#core::result::Result::Ok(::#alloc::borrow::ToOwned::to_owned(ref_ty))
                }
            }

            #[automatically_derived]
            impl ::#core::str::FromStr for #ty {
                type Err = #validator::Error;

                #[inline]
                fn from_str(s: &str) -> ::#core::result::Result<Self, Self::Err> {
                    let ref_ty = #ref_ty::from_str(s)?;
                    ::#core::result::Result::Ok(::#alloc::borrow::ToOwned::to_owned(ref_ty))
                }
            }

            #[automatically_derived]
            impl ::#core::borrow::Borrow<str> for #ty {
                #[inline]
                fn borrow(&self) -> &str {
                    self.as_str()
                }
            }

            #[automatically_derived]
            impl ::#core::ops::Deref for #ty {
                type Target = #ref_ty;

                #[allow(unsafe_code)]
                #[inline]
                fn deref(&self) -> &Self::Target {
                    #unchecked_safety_comment
                    unsafe { #ref_ty::from_str_unchecked(::#core::convert::AsRef::as_ref(&self.#field_name)) }
                }
            }
        }
    }

    fn normalized_conversion(&self, normalizer: &syn::Type) -> proc_macro2::TokenStream {
        let ty = self.ty;
        let ref_ty = self.ref_ty;
        let field_name = &self.field.name;
        let field_ty = &self.field.ty;
        let validator = crate::as_validator(normalizer);
        let core = self.std_lib.core();
        let alloc = self.std_lib.alloc();
        let unchecked_safety_comment = Self::unchecked_safety_comment(true);

        quote! {
            #[automatically_derived]
            impl ::#core::convert::TryFrom<::#alloc::string::String> for #ty {
                type Error = #validator::Error;

                #[inline]
                fn try_from(s: ::#alloc::string::String) -> ::#core::result::Result<Self, Self::Error> {
                    const fn ensure_try_from_string_error_converts_to_validator_error<T: ?Sized + From<<#field_ty as ::#core::convert::TryFrom<::#alloc::string::String>>::Error>>() {}
                    ensure_try_from_string_error_converts_to_validator_error::<Self::Error>();

                    Self::new(::#core::convert::TryFrom::try_from(s)?)
                }
            }

            #[automatically_derived]
            impl ::#core::convert::TryFrom<&'_ str> for #ty {
                type Error = #validator::Error;

                #[inline]
                fn try_from(s: &str) -> ::#core::result::Result<Self, Self::Error> {
                    let ref_ty = #ref_ty::from_str(s)?;
                    ::#core::result::Result::Ok(ref_ty.into_owned())
                }
            }

            #[automatically_derived]
            impl ::#core::str::FromStr for #ty {
                type Err = #validator::Error;

                #[inline]
                fn from_str(s: &str) -> ::#core::result::Result<Self, Self::Err> {
                    let ref_ty = #ref_ty::from_str(s)?;
                    ::#core::result::Result::Ok(ref_ty.into_owned())
                }
            }

            #[automatically_derived]
            impl ::#core::ops::Deref for #ty {
                type Target = #ref_ty;

                #[allow(unsafe_code)]
                #[inline]
                fn deref(&self) -> &Self::Target {
                    #unchecked_safety_comment
                    unsafe { #ref_ty::from_str_unchecked(&self.#field_name) }
                }
            }
        }
    }

    fn conversion(&self) -> proc_macro2::TokenStream {
        let common = self.common_conversion();
        let convert = match &self.check_mode {
            CheckMode::None => self.infallible_conversion(),
            CheckMode::Validate(validator) => self.fallible_conversion(validator),
            CheckMode::Normalize(normalizer) => self.normalized_conversion(normalizer),
        };

        quote! {
            #common
            #convert
        }
    }

    pub fn tokens(&self) -> proc_macro2::TokenStream {
        let clone = self.impls.clone.to_owned_impl(self);
        let display = self.impls.display.to_owned_impl(self);
        let debug = self.impls.debug.to_owned_impl(self);
        let ord = self.impls.ord.to_owned_impl(self);
        let serde = self.impls.serde.to_owned_impl(self);

        let owned_attrs: proc_macro2::TokenStream =
            self.attrs.iter().map(|a| quote! {#[#a]}).collect();
        let body = &self.body;
        let inherent = self.inherent();
        let conversion = self.conversion();

        quote! {
            #clone
            #[derive(Hash, PartialEq, Eq)]
            #[repr(transparent)]
            #owned_attrs
            #body

            #inherent
            #conversion
            #debug
            #display
            #ord
            #serde
        }
    }
}