ruma_macros/
identifiers.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
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
//! Methods and types for generating identifiers.

use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote};
use syn::{
    parse::{Parse, ParseStream},
    punctuated::Punctuated,
    Fields, ImplGenerics, Index, ItemStruct, LitStr, Path, Token,
};

pub struct IdentifierInput {
    pub dollar_crate: Path,
    pub id: LitStr,
}

impl Parse for IdentifierInput {
    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
        let dollar_crate = input.parse()?;
        let _: Token![,] = input.parse()?;
        let id = input.parse()?;

        Ok(Self { dollar_crate, id })
    }
}

pub fn expand_id_zst(input: ItemStruct) -> syn::Result<TokenStream> {
    let id = &input.ident;
    let owned = format_ident!("Owned{id}");

    let owned_decl = expand_owned_id(&input);

    let meta = input.attrs.iter().filter(|attr| attr.path().is_ident("ruma_id")).try_fold(
        IdZstMeta::default(),
        |meta, attr| {
            let list: Punctuated<IdZstMeta, Token![,]> =
                attr.parse_args_with(Punctuated::parse_terminated)?;

            list.into_iter().try_fold(meta, IdZstMeta::merge)
        },
    )?;

    let extra_impls = if let Some(validate) = meta.validate {
        expand_checked_impls(&input, validate)
    } else {
        assert!(
            input.generics.params.is_empty(),
            "generic unchecked IDs are not currently supported"
        );
        expand_unchecked_impls(&input)
    };

    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
    // So we don't have to insert #where_clause everywhere when it is always None in practice
    assert_eq!(where_clause, None, "where clauses on identifier types are not currently supported");

    let as_str_docs = format!("Creates a string slice from this `{id}`.");
    let as_bytes_docs = format!("Creates a byte slice from this `{id}`.");

    let as_str_impl = match &input.fields {
        Fields::Named(_) | Fields::Unit => {
            syn::Error::new(Span::call_site(), "Only tuple structs are supported currently.")
                .into_compile_error()
        }
        Fields::Unnamed(u) => {
            let last_idx = Index::from(u.unnamed.len() - 1);
            quote! { &self.#last_idx }
        }
    };

    let id_ty = quote! { #id #ty_generics };
    let owned_ty = quote! { #owned #ty_generics };

    let as_str_impls = expand_as_str_impls(id_ty.clone(), &impl_generics);
    // FIXME: Remove?
    let box_partial_eq_string = expand_partial_eq_string(quote! { Box<#id_ty> }, &impl_generics);

    Ok(quote! {
        #owned_decl

        #[automatically_derived]
        impl #impl_generics #id_ty {
            pub(super) const fn from_borrowed(s: &str) -> &Self {
                unsafe { std::mem::transmute(s) }
            }

            pub(super) fn from_box(s: Box<str>) -> Box<Self> {
                unsafe { Box::from_raw(Box::into_raw(s) as _) }
            }

            pub(super) fn from_rc(s: std::rc::Rc<str>) -> std::rc::Rc<Self> {
                unsafe { std::rc::Rc::from_raw(std::rc::Rc::into_raw(s) as _) }
            }

            pub(super) fn from_arc(s: std::sync::Arc<str>) -> std::sync::Arc<Self> {
                unsafe { std::sync::Arc::from_raw(std::sync::Arc::into_raw(s) as _) }
            }

            pub(super) fn into_owned(self: Box<Self>) -> Box<str> {
                unsafe { Box::from_raw(Box::into_raw(self) as _) }
            }

            #[doc = #as_str_docs]
            #[inline]
            pub fn as_str(&self) -> &str {
                #as_str_impl
            }

            #[doc = #as_bytes_docs]
            #[inline]
            pub fn as_bytes(&self) -> &[u8] {
                self.as_str().as_bytes()
            }
        }

        #[automatically_derived]
        impl #impl_generics Clone for Box<#id_ty> {
            fn clone(&self) -> Self {
                (**self).into()
            }
        }

        #[automatically_derived]
        impl #impl_generics ToOwned for #id_ty {
            type Owned = #owned_ty;

            fn to_owned(&self) -> Self::Owned {
                #owned::from_ref(self)
            }
        }

        #[automatically_derived]
        impl #impl_generics AsRef<#id_ty> for #id_ty {
            fn as_ref(&self) -> &#id_ty {
                self
            }
        }

        #[automatically_derived]
        impl #impl_generics AsRef<str> for #id_ty {
            fn as_ref(&self) -> &str {
                self.as_str()
            }
        }

        #[automatically_derived]
        impl #impl_generics AsRef<str> for Box<#id_ty> {
            fn as_ref(&self) -> &str {
                self.as_str()
            }
        }

        #[automatically_derived]
        impl #impl_generics AsRef<[u8]> for #id_ty {
            fn as_ref(&self) -> &[u8] {
                self.as_bytes()
            }
        }

        #[automatically_derived]
        impl #impl_generics AsRef<[u8]> for Box<#id_ty> {
            fn as_ref(&self) -> &[u8] {
                self.as_bytes()
            }
        }

        #[automatically_derived]
        impl #impl_generics From<&#id_ty> for String {
            fn from(id: &#id_ty) -> Self {
                id.as_str().to_owned()
            }
        }

        #[automatically_derived]
        impl #impl_generics From<Box<#id_ty>> for String {
            fn from(id: Box<#id_ty>) -> Self {
                id.into_owned().into()
            }
        }

        #[automatically_derived]
        impl #impl_generics From<&#id_ty> for Box<#id_ty> {
            fn from(id: &#id_ty) -> Self {
                <#id_ty>::from_box(id.as_str().into())
            }
        }

        #[automatically_derived]
        impl #impl_generics From<&#id_ty> for std::rc::Rc<#id_ty> {
            fn from(s: &#id_ty) -> std::rc::Rc<#id_ty> {
                let rc = std::rc::Rc::<str>::from(s.as_str());
                <#id_ty>::from_rc(rc)
            }
        }

        #[automatically_derived]
        impl #impl_generics From<&#id_ty> for std::sync::Arc<#id_ty> {
            fn from(s: &#id_ty) -> std::sync::Arc<#id_ty> {
                let arc = std::sync::Arc::<str>::from(s.as_str());
                <#id_ty>::from_arc(arc)
            }
        }

        #[automatically_derived]
        impl #impl_generics PartialEq<#id_ty> for Box<#id_ty> {
            fn eq(&self, other: &#id_ty) -> bool {
                self.as_str() == other.as_str()
            }
        }

        #[automatically_derived]
        impl #impl_generics PartialEq<&'_ #id_ty> for Box<#id_ty> {
            fn eq(&self, other: &&#id_ty) -> bool {
                self.as_str() == other.as_str()
            }
        }

        #[automatically_derived]
        impl #impl_generics PartialEq<Box<#id_ty>> for #id_ty {
            fn eq(&self, other: &Box<#id_ty>) -> bool {
                self.as_str() == other.as_str()
            }
        }

        #[automatically_derived]
        impl #impl_generics PartialEq<Box<#id_ty>> for &'_ #id_ty {
            fn eq(&self, other: &Box<#id_ty>) -> bool {
                self.as_str() == other.as_str()
            }
        }

        #as_str_impls
        #box_partial_eq_string
        #extra_impls
    })
}

fn expand_owned_id(input: &ItemStruct) -> TokenStream {
    let id = &input.ident;
    let owned = format_ident!("Owned{id}");

    let doc_header = format!("Owned variant of {id}");
    let (impl_generics, ty_generics, _where_clause) = input.generics.split_for_impl();

    let id_ty = quote! { #id #ty_generics };
    let owned_ty = quote! { #owned #ty_generics };

    let as_str_impls = expand_as_str_impls(owned_ty.clone(), &impl_generics);

    quote! {
        #[doc = #doc_header]
        ///
        /// The wrapper type for this type is variable, by default it'll use [`Box`],
        /// but you can change that by setting "`--cfg=ruma_identifiers_storage=...`" using
        /// `RUSTFLAGS` or `.cargo/config.toml` (under `[build]` -> `rustflags = ["..."]`)
        /// to the following;
        /// - `ruma_identifiers_storage="Arc"` to use [`Arc`](std::sync::Arc) as a wrapper type.
        pub struct #owned #impl_generics {
            #[cfg(not(any(ruma_identifiers_storage = "Arc")))]
            inner: Box<#id_ty>,
            #[cfg(ruma_identifiers_storage = "Arc")]
            inner: std::sync::Arc<#id_ty>,
        }

        #[automatically_derived]
        impl #impl_generics #owned_ty {
            fn from_ref(v: &#id_ty) -> Self {
                Self {
                    #[cfg(not(any(ruma_identifiers_storage = "Arc")))]
                    inner: #id::from_box(v.as_str().into()),
                    #[cfg(ruma_identifiers_storage = "Arc")]
                    inner: #id::from_arc(v.as_str().into()),
                }
            }
        }

        #[automatically_derived]
        impl #impl_generics AsRef<#id_ty> for #owned_ty {
            fn as_ref(&self) -> &#id_ty {
                &*self.inner
            }
        }

        #[automatically_derived]
        impl #impl_generics AsRef<str> for #owned_ty {
            fn as_ref(&self) -> &str {
                self.inner.as_str()
            }
        }

        #[automatically_derived]
        impl #impl_generics AsRef<[u8]> for #owned_ty {
            fn as_ref(&self) -> &[u8] {
                self.inner.as_bytes()
            }
        }

        #[automatically_derived]
        impl #impl_generics From<#owned_ty> for String {
            fn from(id: #owned_ty) -> String {
                #[cfg(not(any(ruma_identifiers_storage = "Arc")))]
                { id.inner.into() }
                #[cfg(ruma_identifiers_storage = "Arc")]
                { id.inner.as_ref().into() }
            }
        }

        #[automatically_derived]
        impl #impl_generics std::clone::Clone for #owned_ty {
            fn clone(&self) -> Self {
                (&*self.inner).into()
            }
        }

        #[automatically_derived]
        impl #impl_generics std::ops::Deref for #owned_ty {
            type Target = #id_ty;

            fn deref(&self) -> &Self::Target {
                &self.inner
            }
        }

        #[automatically_derived]
        impl #impl_generics std::borrow::Borrow<#id_ty> for #owned_ty {
            fn borrow(&self) -> &#id_ty {
                self.as_ref()
            }
        }

        #[automatically_derived]
        impl #impl_generics From<&'_ #id_ty> for #owned_ty {
            fn from(id: &#id_ty) -> #owned_ty {
                #owned { inner: id.into() }
            }
        }

        #[automatically_derived]
        impl #impl_generics From<Box<#id_ty>> for #owned_ty {
            fn from(b: Box<#id_ty>) -> #owned_ty {
                Self { inner: b.into() }
            }
        }

        #[automatically_derived]
        impl #impl_generics From<std::sync::Arc<#id_ty>> for #owned_ty {
            fn from(a: std::sync::Arc<#id_ty>) -> #owned_ty {
                Self {
                    #[cfg(not(any(ruma_identifiers_storage = "Arc")))]
                    inner: a.as_ref().into(),
                    #[cfg(ruma_identifiers_storage = "Arc")]
                    inner: a,
                }
            }
        }

        #[automatically_derived]
        impl #impl_generics From<#owned_ty> for Box<#id_ty> {
            fn from(a: #owned_ty) -> Box<#id_ty> {
                #[cfg(not(any(ruma_identifiers_storage = "Arc")))]
                { a.inner }
                #[cfg(ruma_identifiers_storage = "Arc")]
                { a.inner.as_ref().into() }
            }
        }

        #[automatically_derived]
        impl #impl_generics From<#owned_ty> for std::sync::Arc<#id_ty> {
            fn from(a: #owned_ty) -> std::sync::Arc<#id_ty> {
                #[cfg(not(any(ruma_identifiers_storage = "Arc")))]
                { a.inner.into() }
                #[cfg(ruma_identifiers_storage = "Arc")]
                { a.inner }
            }
        }

        #[automatically_derived]
        impl #impl_generics std::cmp::PartialEq for #owned_ty {
            fn eq(&self, other: &Self) -> bool {
                self.as_str() == other.as_str()
            }
        }

        #[automatically_derived]
        impl #impl_generics std::cmp::Eq for #owned_ty {}

        #[automatically_derived]
        impl #impl_generics std::cmp::PartialOrd for #owned_ty {
            fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
                Some(self.cmp(other))
            }
        }

        #[automatically_derived]
        impl #impl_generics std::cmp::Ord for #owned_ty {
            fn cmp(&self, other: &Self) -> std::cmp::Ordering {
                self.as_str().cmp(other.as_str())
            }
        }

        #[automatically_derived]
        impl #impl_generics std::hash::Hash for #owned_ty {
            fn hash<H>(&self, state: &mut H)
            where
                H: std::hash::Hasher,
            {
                self.as_str().hash(state)
            }
        }

        #as_str_impls

        #[automatically_derived]
        impl #impl_generics PartialEq<#id_ty> for #owned_ty {
            fn eq(&self, other: &#id_ty) -> bool {
                AsRef::<#id_ty>::as_ref(self) == other
            }
        }

        #[automatically_derived]
        impl #impl_generics PartialEq<#owned_ty> for #id_ty {
            fn eq(&self, other: &#owned_ty) -> bool {
                self == AsRef::<#id_ty>::as_ref(other)
            }
        }

        #[automatically_derived]
        impl #impl_generics PartialEq<&#id_ty> for #owned_ty {
            fn eq(&self, other: &&#id_ty) -> bool {
                AsRef::<#id_ty>::as_ref(self) == *other
            }
        }

        #[automatically_derived]
        impl #impl_generics PartialEq<#owned_ty> for &#id_ty {
            fn eq(&self, other: &#owned_ty) -> bool {
                *self == AsRef::<#id_ty>::as_ref(other)
            }
        }

        #[automatically_derived]
        impl #impl_generics PartialEq<Box<#id_ty>> for #owned_ty {
            fn eq(&self, other: &Box<#id_ty>) -> bool {
                AsRef::<#id_ty>::as_ref(self) == AsRef::<#id_ty>::as_ref(other)
            }
        }

        #[automatically_derived]
        impl #impl_generics PartialEq<#owned_ty> for Box<#id_ty> {
            fn eq(&self, other: &#owned_ty) -> bool {
                AsRef::<#id_ty>::as_ref(self) == AsRef::<#id_ty>::as_ref(other)
            }
        }

        #[automatically_derived]
        impl #impl_generics PartialEq<std::sync::Arc<#id_ty>> for #owned_ty {
            fn eq(&self, other: &std::sync::Arc<#id_ty>) -> bool {
                AsRef::<#id_ty>::as_ref(self) == AsRef::<#id_ty>::as_ref(other)
            }
        }

        #[automatically_derived]
        impl #impl_generics PartialEq<#owned_ty> for std::sync::Arc<#id_ty> {
            fn eq(&self, other: &#owned_ty) -> bool {
                AsRef::<#id_ty>::as_ref(self) == AsRef::<#id_ty>::as_ref(other)
            }
        }
    }
}

fn expand_checked_impls(input: &ItemStruct, validate: Path) -> TokenStream {
    let id = &input.ident;
    let owned = format_ident!("Owned{id}");

    let (impl_generics, ty_generics, _where_clause) = input.generics.split_for_impl();
    let generic_params = &input.generics.params;

    let parse_doc_header = format!("Try parsing a `&str` into an `Owned{id}`.");
    let parse_box_doc_header = format!("Try parsing a `&str` into a `Box<{id}>`.");
    let parse_rc_docs = format!("Try parsing a `&str` into an `Rc<{id}>`.");
    let parse_arc_docs = format!("Try parsing a `&str` into an `Arc<{id}>`.");

    let id_ty = quote! { #id #ty_generics };
    let owned_ty = quote! { #owned #ty_generics };

    quote! {
        #[automatically_derived]
        impl #impl_generics #id_ty {
            #[doc = #parse_doc_header]
            ///
            /// The same can also be done using `FromStr`, `TryFrom` or `TryInto`.
            /// This function is simply more constrained and thus useful in generic contexts.
            pub fn parse(
                s: impl AsRef<str>,
            ) -> Result<#owned_ty, crate::IdParseError> {
                let s = s.as_ref();
                #validate(s)?;
                Ok(#id::from_borrowed(s).to_owned())
            }

            #[doc = #parse_box_doc_header]
            ///
            /// The same can also be done using `FromStr`, `TryFrom` or `TryInto`.
            /// This function is simply more constrained and thus useful in generic contexts.
            pub fn parse_box(
                s: impl AsRef<str> + Into<Box<str>>,
            ) -> Result<Box<Self>, crate::IdParseError> {
                #validate(s.as_ref())?;
                Ok(#id::from_box(s.into()))
            }

            #[doc = #parse_rc_docs]
            pub fn parse_rc(
                s: impl AsRef<str> + Into<std::rc::Rc<str>>,
            ) -> Result<std::rc::Rc<Self>, crate::IdParseError> {
                #validate(s.as_ref())?;
                Ok(#id::from_rc(s.into()))
            }

            #[doc = #parse_arc_docs]
            pub fn parse_arc(
                s: impl AsRef<str> + Into<std::sync::Arc<str>>,
            ) -> Result<std::sync::Arc<Self>, crate::IdParseError> {
                #validate(s.as_ref())?;
                Ok(#id::from_arc(s.into()))
            }
        }

        #[automatically_derived]
        impl<'de, #generic_params> serde::Deserialize<'de> for Box<#id_ty> {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                use serde::de::Error;

                let s = String::deserialize(deserializer)?;

                match #id::parse_box(s) {
                    Ok(o) => Ok(o),
                    Err(e) => Err(D::Error::custom(e)),
                }
            }
        }

        #[automatically_derived]
        impl<'de, #generic_params> serde::Deserialize<'de> for #owned_ty {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                use serde::de::Error;

                let s = String::deserialize(deserializer)?;

                match #id::parse(s) {
                    Ok(o) => Ok(o),
                    Err(e) => Err(D::Error::custom(e)),
                }
            }
        }

        #[automatically_derived]
        impl<'a, #generic_params> std::convert::TryFrom<&'a str> for &'a #id_ty {
            type Error = crate::IdParseError;

            fn try_from(s: &'a str) -> Result<Self, Self::Error> {
                #validate(s)?;
                Ok(<#id_ty>::from_borrowed(s))
            }
        }

        #[automatically_derived]
        impl #impl_generics std::str::FromStr for Box<#id_ty> {
            type Err = crate::IdParseError;

            fn from_str(s: &str) -> Result<Self, Self::Err> {
                <#id_ty>::parse_box(s)
            }
        }

        #[automatically_derived]
        impl #impl_generics std::convert::TryFrom<&str> for Box<#id_ty> {
            type Error = crate::IdParseError;

            fn try_from(s: &str) -> Result<Self, Self::Error> {
                <#id_ty>::parse_box(s)
            }
        }

        #[automatically_derived]
        impl #impl_generics std::convert::TryFrom<String> for Box<#id_ty> {
            type Error = crate::IdParseError;

            fn try_from(s: String) -> Result<Self, Self::Error> {
                <#id_ty>::parse_box(s)
            }
        }

        #[automatically_derived]
        impl #impl_generics std::str::FromStr for #owned_ty {
            type Err = crate::IdParseError;

            fn from_str(s: &str) -> Result<Self, Self::Err> {
                <#id_ty>::parse(s)
            }
        }

        #[automatically_derived]
        impl #impl_generics std::convert::TryFrom<&str> for #owned_ty {
            type Error = crate::IdParseError;

            fn try_from(s: &str) -> Result<Self, Self::Error> {
                <#id_ty>::parse(s)
            }
        }

        #[automatically_derived]
        impl #impl_generics std::convert::TryFrom<String> for #owned_ty {
            type Error = crate::IdParseError;

            fn try_from(s: String) -> Result<Self, Self::Error> {
                <#id_ty>::parse(s)
            }
        }
    }
}

fn expand_unchecked_impls(input: &ItemStruct) -> TokenStream {
    let id = &input.ident;
    let owned = format_ident!("Owned{id}");

    quote! {
        #[automatically_derived]
        impl<'a> From<&'a str> for &'a #id {
            fn from(s: &'a str) -> Self {
                #id::from_borrowed(s)
            }
        }

        #[automatically_derived]
        impl From<&str> for #owned {
            fn from(s: &str) -> Self {
                <&#id>::from(s).into()
            }
        }

        #[automatically_derived]
        impl From<Box<str>> for #owned {
            fn from(s: Box<str>) -> Self {
                <&#id>::from(&*s).into()
            }
        }

        #[automatically_derived]
        impl From<String> for #owned {
            fn from(s: String) -> Self {
                <&#id>::from(s.as_str()).into()
            }
        }

        #[automatically_derived]
        impl From<&str> for Box<#id> {
            fn from(s: &str) -> Self {
                #id::from_box(s.into())
            }
        }

        #[automatically_derived]
        impl From<Box<str>> for Box<#id> {
            fn from(s: Box<str>) -> Self {
                #id::from_box(s)
            }
        }

        #[automatically_derived]
        impl From<String> for Box<#id> {
            fn from(s: String) -> Self {
                #id::from_box(s.into())
            }
        }

        #[automatically_derived]
        impl From<Box<#id>> for Box<str> {
            fn from(id: Box<#id>) -> Self {
                id.into_owned()
            }
        }

        #[automatically_derived]
        impl<'de> serde::Deserialize<'de> for Box<#id> {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                Box::<str>::deserialize(deserializer).map(#id::from_box)
            }
        }

        #[automatically_derived]
        impl<'de> serde::Deserialize<'de> for #owned {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                // FIXME: Deserialize inner, convert that
                Box::<str>::deserialize(deserializer).map(#id::from_box).map(Into::into)
            }
        }
    }
}

fn expand_as_str_impls(ty: TokenStream, impl_generics: &ImplGenerics<'_>) -> TokenStream {
    let partial_eq_string = expand_partial_eq_string(ty.clone(), impl_generics);

    quote! {
        #[automatically_derived]
        impl #impl_generics std::fmt::Display for #ty {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{}", self.as_str())
            }
        }

        #[automatically_derived]
        impl #impl_generics std::fmt::Debug for #ty {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                <str as std::fmt::Debug>::fmt(self.as_str(), f)
            }
        }

        #[automatically_derived]
        impl #impl_generics serde::Serialize for #ty {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: serde::Serializer,
            {
                serializer.serialize_str(self.as_str())
            }
        }

        #partial_eq_string
    }
}

fn expand_partial_eq_string(ty: TokenStream, impl_generics: &ImplGenerics<'_>) -> TokenStream {
    IntoIterator::into_iter([
        (ty.clone(), quote! { str }),
        (ty.clone(), quote! { &str }),
        (ty.clone(), quote! { String }),
        (quote! { str }, ty.clone()),
        (quote! { &str }, ty.clone()),
        (quote! { String }, ty),
    ])
    .map(|(lhs, rhs)| {
        quote! {
            #[automatically_derived]
            impl #impl_generics PartialEq<#rhs> for #lhs {
                fn eq(&self, other: &#rhs) -> bool {
                    AsRef::<str>::as_ref(self)
                        == AsRef::<str>::as_ref(other)
                }
            }
        }
    })
    .collect()
}

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

#[derive(Default)]
struct IdZstMeta {
    validate: Option<Path>,
}

impl IdZstMeta {
    fn merge(self, other: IdZstMeta) -> syn::Result<Self> {
        let validate = match (self.validate, other.validate) {
            (None, None) => None,
            (Some(val), None) | (None, Some(val)) => Some(val),
            (Some(a), Some(b)) => {
                let mut error = syn::Error::new_spanned(b, "duplicate attribute argument");
                error.combine(syn::Error::new_spanned(a, "note: first one here"));
                return Err(error);
            }
        };

        Ok(Self { validate })
    }
}

impl Parse for IdZstMeta {
    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
        let _: kw::validate = input.parse()?;
        let _: Token![=] = input.parse()?;
        let validate = Some(input.parse()?);
        Ok(Self { validate })
    }
}