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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
use crate::parse_utils::{consume_path, tokens_from_slice};
use crate::types::{
Attribute, AttributeValue, Constant, Enum, EnumVariant, EnumVariantValue, ExternBlock,
ExternCrate, Fields, FnQualifiers, Function, GenericArg, GenericArgList, GenericBound,
GenericParam, GenericParamList, GroupSpan, Impl, InlineGenericArgs, Item, Lifetime, Macro,
Module, NamedField, Path, Punctuated, Struct, Trait, TupleField, TypeAlias, TypeExpr, Union,
UseDeclaration, VisMarker, WhereClause, WhereClausePredicate,
};
use proc_macro2::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree};
use quote::spanned::Spanned;
impl Item {
/// Returns the [`Vec<Attribute>`] of the declaration.
///
/// This method is provided for convenience, but it's more idiomatic to match on Declaration and use the same method in the matching variant.
pub fn attributes(&self) -> &Vec<Attribute> {
match self {
Item::Struct(struct_decl) => &struct_decl.attributes,
Item::Enum(enum_decl) => &enum_decl.attributes,
Item::Union(union_decl) => &union_decl.attributes,
Item::Module(mod_decl) => &mod_decl.attributes,
Item::Trait(trait_decl) => &trait_decl.attributes,
Item::Impl(impl_decl) => &impl_decl.attributes,
Item::TypeAlias(ty_decl) => &ty_decl.attributes,
Item::Function(function_decl) => &function_decl.attributes,
Item::Constant(const_decl) => &const_decl.attributes,
Item::UseDeclaration(use_decl) => &use_decl.attributes,
Item::Macro(macro_decl) => ¯o_decl.attributes,
Item::ExternBlock(block_decl) => &block_decl.attributes,
Item::ExternCrate(crate_decl) => &crate_decl.attributes,
}
}
/// Returns the [`Vec<Attribute>`] of the declaration.
///
/// This method is provided for convenience, but it's more idiomatic to match on Declaration and use the same method in the matching variant.
pub fn attributes_mut(&mut self) -> &mut Vec<Attribute> {
match self {
Item::Struct(struct_decl) => &mut struct_decl.attributes,
Item::Enum(enum_decl) => &mut enum_decl.attributes,
Item::Union(union_decl) => &mut union_decl.attributes,
Item::Module(mod_decl) => &mut mod_decl.attributes,
Item::Trait(trait_decl) => &mut trait_decl.attributes,
Item::Impl(impl_decl) => &mut impl_decl.attributes,
Item::TypeAlias(ty_decl) => &mut ty_decl.attributes,
Item::Function(function_decl) => &mut function_decl.attributes,
Item::Constant(const_decl) => &mut const_decl.attributes,
Item::UseDeclaration(use_decl) => &mut use_decl.attributes,
Item::Macro(macro_decl) => &mut macro_decl.attributes,
Item::ExternBlock(block_decl) => &mut block_decl.attributes,
Item::ExternCrate(crate_decl) => &mut crate_decl.attributes,
}
}
/// Returns the [`GenericParamList`], if any, of the declaration.
///
/// For instance, this will return Some for `struct MyStruct<A, B, C> { ... }`,
/// Some for `impl<A> MyTrait for MyType<A>` and None for `enum MyEnum { ... }`.
///
/// `TyDefinition` and `Constant` variants never have a generic parameter list.
///
/// This method is provided for convenience, but it's more idiomatic to match on Declaration and use the same method in the matching variant.
pub fn generic_params(&self) -> Option<&GenericParamList> {
match self {
Item::Struct(struct_decl) => struct_decl.generic_params.as_ref(),
Item::Enum(enum_decl) => enum_decl.generic_params.as_ref(),
Item::Union(union_decl) => union_decl.generic_params.as_ref(),
Item::Module(_) => None,
Item::Trait(trait_decl) => trait_decl.generic_params.as_ref(),
Item::Impl(impl_decl) => impl_decl.impl_generic_params.as_ref(),
Item::TypeAlias(_) => None,
Item::Function(function_decl) => function_decl.generic_params.as_ref(),
Item::Constant(_) => None,
Item::UseDeclaration(_) => None,
Item::Macro(_) => None,
Item::ExternBlock(_) => None,
Item::ExternCrate(_) => None,
}
}
/// Returns the [`GenericParamList`], if any, of the declaration.
///
/// For instance, this will return Some for `struct MyStruct<A, B, C> { ... }`,
/// Some for `impl<A> MyTrait for MyType<A>` and None for `enum MyEnum { ... }`.
///
/// `TyDefinition` and `Constant` variants never have a generic parameter list.
///
/// This method is provided for convenience, but it's more idiomatic to match on Declaration and use the same method in the matching variant.
pub fn generic_params_mut(&mut self) -> Option<&mut GenericParamList> {
match self {
Item::Struct(struct_decl) => struct_decl.generic_params.as_mut(),
Item::Enum(enum_decl) => enum_decl.generic_params.as_mut(),
Item::Union(union_decl) => union_decl.generic_params.as_mut(),
Item::Module(_) => None,
Item::Trait(trait_decl) => trait_decl.generic_params.as_mut(),
Item::Impl(impl_decl) => impl_decl.impl_generic_params.as_mut(),
Item::TypeAlias(_) => None,
Item::Function(function_decl) => function_decl.generic_params.as_mut(),
Item::Constant(_) => None,
Item::UseDeclaration(_) => None,
Item::Macro(_) => None,
Item::ExternBlock(_) => None,
Item::ExternCrate(_) => None,
}
}
/// Returns the [`Ident`] of the declaration, if available.
///
/// Certain declarations (currently `impl` blocks) do not have a name, as they refer to other (possibly qualified) types.
/// In that case, `None` is returned.
///
/// ```
/// # use venial::parse_item;
/// # use quote::quote;
/// let struct_type = parse_item(quote!(
/// struct Hello(A, B);
/// )).unwrap();
/// assert_eq!(struct_type.name().unwrap().to_string(), "Hello");
/// ```
pub fn name(&self) -> Option<Ident> {
match self {
Item::Struct(struct_decl) => Some(struct_decl.name.clone()),
Item::Enum(enum_decl) => Some(enum_decl.name.clone()),
Item::Union(union_decl) => Some(union_decl.name.clone()),
Item::Module(mod_decl) => Some(mod_decl.name.clone()),
Item::Trait(trait_decl) => Some(trait_decl.name.clone()),
Item::Impl(_) => None,
Item::TypeAlias(ty_decl) => Some(ty_decl.name.clone()),
Item::Function(function_decl) => Some(function_decl.name.clone()),
Item::Constant(const_decl) => Some(const_decl.name.clone()),
Item::UseDeclaration(_) => None,
Item::Macro(macro_) => Some(macro_.name.clone()),
Item::ExternBlock(_) => None,
Item::ExternCrate(crate_) => Some(crate_.name.clone()),
}
}
/// Returns the [`Struct`] variant of the enum if possible.
pub fn as_struct(&self) -> Option<&Struct> {
match self {
Item::Struct(struct_decl) => Some(struct_decl),
_ => None,
}
}
/// Returns the [`Enum`] variant of the enum if possible.
pub fn as_enum(&self) -> Option<&Enum> {
match self {
Item::Enum(enum_decl) => Some(enum_decl),
_ => None,
}
}
/// Returns the [`Union`] variant of the enum if possible.
pub fn as_union(&self) -> Option<&Union> {
match self {
Item::Union(union_decl) => Some(union_decl),
_ => None,
}
}
/// Returns the [`Module`] variant of the enum if possible.
pub fn as_module(&self) -> Option<&Module> {
match self {
Item::Module(mod_decl) => Some(mod_decl),
_ => None,
}
}
/// Returns the [`Trait`] variant of the enum if possible.
pub fn as_trait(&self) -> Option<&Trait> {
match self {
Item::Trait(trait_decl) => Some(trait_decl),
_ => None,
}
}
/// Returns the [`Impl`] variant of the enum if possible.
pub fn as_impl(&self) -> Option<&Impl> {
match self {
Item::Impl(impl_decl) => Some(impl_decl),
_ => None,
}
}
/// Returns the [`TypeAlias`] variant of the enum if possible.
pub fn as_type_alias(&self) -> Option<&TypeAlias> {
match self {
Item::TypeAlias(ty_decl) => Some(ty_decl),
_ => None,
}
}
/// Returns the [`Function`] variant of the enum if possible.
pub fn as_function(&self) -> Option<&Function> {
match self {
Item::Function(function_decl) => Some(function_decl),
_ => None,
}
}
/// Returns the [`Constant`] variant of the enum if possible.
pub fn as_constant(&self) -> Option<&Constant> {
match self {
Item::Constant(const_decl) => Some(const_decl),
_ => None,
}
}
/// Returns the [`UseDeclaration`] variant of the enum if possible.
pub fn as_use_declaration(&self) -> Option<&UseDeclaration> {
match self {
Item::UseDeclaration(use_decl) => Some(use_decl),
_ => None,
}
}
/// Returns the [`Macro`] variant of the enum if possible.
pub fn as_macro(&self) -> Option<&Macro> {
match self {
Item::Macro(macro_decl) => Some(macro_decl),
_ => None,
}
}
/// Returns the [`ExternBlock`] variant of the enum if possible.
pub fn as_extern_block(&self) -> Option<&ExternBlock> {
match self {
Item::ExternBlock(block_decl) => Some(block_decl),
_ => None,
}
}
/// Returns the [`ExternCrate`] variant of the enum if possible.
pub fn as_extern_crate(&self) -> Option<&ExternCrate> {
match self {
Item::ExternCrate(crate_decl) => Some(crate_decl),
_ => None,
}
}
/// Venial doesn't have an equivalent for the syn split_for_impl() method.
///
/// Given the syn use-case:
///
/// ```ignore
/// let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
/// quote! {
/// impl #impl_generics MyTrait for #name #ty_generics #where_clause {
/// // ...
/// }
/// }
/// ```
///
/// Venial doesn't have an "all-in-one" method. You would instead write:
///
/// ```no_run
/// # let input: venial::Item = None.unwrap();
/// let impl_generics = input.generic_params().unwrap();
/// let ty_generics = input.generic_params().unwrap().as_inline_args();
/// ```
#[deprecated = "Documentation item"]
pub fn __no_split_for_impl__() -> ! {
unimplemented!();
}
}
impl Struct {
/// Returns a collection of strings that can be used to exhaustively
/// access the struct's fields.
///
/// If the struct is a tuple struct, integer strings will be returned.
///
/// ```
/// # use venial::parse_item;
/// # use quote::quote;
/// let struct_type = parse_item(quote!(
/// struct Hello {
/// a: Foo,
/// b: Bar,
/// }
/// )).unwrap();
/// let struct_type = struct_type.as_struct().unwrap();
/// let field_names: Vec<_> = struct_type.field_names().into_iter().collect();
/// assert_eq!(field_names, ["a", "b"]);
/// ```
///
/// ```
/// # use venial::parse_item;
/// # use quote::quote;
/// let tuple_type = parse_item(quote!(
/// struct Hello(Foo, Bar);
/// )).unwrap();
/// let tuple_type = tuple_type.as_struct().unwrap();
/// let field_names: Vec<_> = tuple_type.field_names().into_iter().collect();
/// assert_eq!(field_names, ["0", "1"]);
/// ```
pub fn field_names(&self) -> impl IntoIterator<Item = String> {
match &self.fields {
Fields::Unit => Vec::new(),
Fields::Tuple(tuple_fields) => {
let range = 0..tuple_fields.fields.len();
range.map(|i| i.to_string()).collect()
}
Fields::Named(named_fields) => named_fields
.fields
.items()
.map(|field| field.name.to_string())
.collect(),
}
}
/// Returns a collection of tokens that can be used to exhaustively
/// access the struct's fields.
///
/// If the struct is a tuple struct, span-less integer literals will be returned.
pub fn field_tokens(&self) -> impl IntoIterator<Item = TokenTree> {
match &self.fields {
Fields::Unit => Vec::new(),
Fields::Tuple(tuple_fields) => {
let range = 0..tuple_fields.fields.len();
range.map(|i| Literal::usize_unsuffixed(i).into()).collect()
}
Fields::Named(named_fields) => named_fields
.fields
.items()
.map(|field| field.name.clone().into())
.collect(),
}
}
/// Returns a collection of references to the struct's field types.
pub fn field_types(&self) -> impl IntoIterator<Item = &TypeExpr> {
match &self.fields {
Fields::Unit => Vec::new(),
Fields::Tuple(tuple_fields) => {
tuple_fields.fields.items().map(|field| &field.ty).collect()
}
Fields::Named(named_fields) => {
named_fields.fields.items().map(|field| &field.ty).collect()
}
}
}
}
impl Enum {
/// Returns true if every single variant is empty.
///
/// ```
/// # use venial::parse_item;
/// # use quote::quote;
/// let enum_type = parse_item(quote!(
/// enum MyEnum { A, B, C, D }
/// )).unwrap();
/// let enum_type = enum_type.as_enum().unwrap();
/// assert!(enum_type.is_c_enum());
/// ```
pub fn is_c_enum(&self) -> bool {
for variant in self.variants.items() {
if !variant.is_empty_variant() {
return false;
}
}
true
}
}
macro_rules! implement_common_methods {
($Kind:ident) => {
impl $Kind {
/// Builder method, add a [`GenericParam`] to `self.generic_params`.
///
/// Creates a default [`GenericParamList`] if `self.generic_params` is None.
pub fn with_param(mut self, param: GenericParam) -> Self {
let params = self.generic_params.take().unwrap_or_default();
let params = params.with_param(param);
self.generic_params = Some(params);
self
}
/// Builder method, add a [`WhereClausePredicate`] to `self.where_clause`.
///
/// Creates a default [`WhereClause`] if `self.where_clause` is None.
pub fn with_where_predicate(mut self, pred: WhereClausePredicate) -> Self {
if let Some(where_clause) = self.where_clause {
self.where_clause = Some(where_clause.with_predicate(pred));
} else {
self.where_clause = Some(WhereClause::from_predicate(pred));
}
self
}
/// Returns a collection of references to declared lifetime params, if any.
pub fn get_lifetime_params(&self) -> impl Iterator<Item = &GenericParam> {
let params: &[_] = if let Some(params) = self.generic_params.as_ref() {
¶ms.params
} else {
&[]
};
params
.iter()
.map(|(param, _punct)| param)
.filter(|param| GenericParam::is_lifetime(param))
}
/// Returns a collection of references to declared type params, if any.
pub fn get_type_params(&self) -> impl Iterator<Item = &GenericParam> {
let params: &[_] = if let Some(params) = self.generic_params.as_ref() {
¶ms.params
} else {
&[]
};
params
.iter()
.map(|(param, _punct)| param)
.filter(|param| GenericParam::is_ty(param))
}
/// Returns a collection of references to declared const generic params, if any.
pub fn get_const_params(&self) -> impl Iterator<Item = &GenericParam> {
let params: &[_] = if let Some(params) = self.generic_params.as_ref() {
¶ms.params
} else {
&[]
};
params
.iter()
.map(|(param, _punct)| param)
.filter(|param| GenericParam::is_const(param))
}
/// See [`InlineGenericArgs`] for details.
pub fn get_inline_generic_args(&self) -> Option<InlineGenericArgs<'_>> {
Some(self.generic_params.as_ref()?.as_inline_args())
}
/// Returns a where clause that can be quoted to form
/// a `impl TRAIT for TYPE where ... { ... }` trait implementation.
///
/// This takes the bounds of the current declaration and adds one bound
/// to `derived_trait` for every generic argument. For instance:
///
/// ```no_run
/// struct MyStruct<T, U> where T: Clone {
/// t: T,
/// u: U
/// }
///
/// // my_struct_decl.create_derive_where_clause(quote!(SomeTrait))
///
/// # trait SomeTrait {}
/// impl<T, U> SomeTrait for MyStruct<T, U>
/// // GENERATED WHERE CLAUSE
/// where T: SomeTrait, U: SomeTrait, T: Clone
/// {
/// // ...
/// }
/// ```
pub fn create_derive_where_clause(&self, derived_trait: TokenStream) -> WhereClause {
let mut where_clause = self.where_clause.clone().unwrap_or_default();
for param in self.get_type_params() {
let pred = WhereClausePredicate {
left_side: vec![param.name.clone().into()],
bound: GenericBound {
tk_colon: Punct::new(':', Spacing::Alone),
tokens: derived_trait.clone().into_iter().collect(),
},
};
where_clause = where_clause.with_predicate(pred);
}
where_clause
}
}
};
}
implement_common_methods! { Struct }
implement_common_methods! { Enum }
implement_common_methods! { Union }
impl Attribute {
/// Returns Some if the attribute has a single path segment, eg `#[hello(...)]`.
/// Returns None if the attribute has multiple segments, eg `#[hello::world(...)]`.
pub fn get_single_path_segment(&self) -> Option<&Ident> {
let mut segments: Vec<_> = self
.path
.iter()
.filter_map(|segment| match segment {
TokenTree::Ident(ident) => Some(ident),
_ => None,
})
.collect();
if segments.len() == 1 {
segments.pop()
} else {
None
}
}
/// Returns `foo + bar` for `#[hello = foo + bar]` and `#[hello(foo + bar)]`.
/// Returns an empty slice for `#[hello]`.
pub fn get_value_tokens(&self) -> &[TokenTree] {
self.value.get_value_tokens()
}
}
impl AttributeValue {
/// Returns `foo + bar` for `#[hello = foo + bar]` and `#[hello(foo + bar)]`.
/// Returns an empty slice for `#[hello]`.
pub fn get_value_tokens(&self) -> &[TokenTree] {
match self {
AttributeValue::Group(_, tokens) => tokens,
AttributeValue::Equals(_, tokens) => tokens,
AttributeValue::Empty => &[],
}
}
}
impl EnumVariant {
/// Returns true if the variant doesn't store a type.
pub fn is_empty_variant(&self) -> bool {
matches!(self.fields, Fields::Unit)
}
/// Returns Some if the variant is a wrapper around a single type.
/// Returns None otherwise.
pub fn get_single_type(&self) -> Option<&TupleField> {
match &self.fields {
Fields::Tuple(fields) if fields.fields.len() == 1 => Some(&fields.fields[0].0),
Fields::Tuple(_fields) => None,
Fields::Unit => None,
Fields::Named(_) => None,
}
}
}
impl FnQualifiers {
/// Whether exactly either `const` or `unsafe` attribute is set, and no other one
/// (so the tokens could be the start of a constant or impl declaration)
pub(crate) fn has_only_const_xor_unsafe(&self) -> bool {
(self.tk_const.is_some() ^ self.tk_unsafe.is_some())
&& self.tk_default.is_none()
&& self.tk_async.is_none()
&& self.tk_extern.is_none()
&& self.extern_abi.is_none()
}
}
impl GenericParamList {
/// Builder method, add a [`GenericParam`].
///
/// Add lifetime params to the beginning of the list.
pub fn with_param(mut self, param: GenericParam) -> Self {
if param.is_lifetime() {
self.params.insert(0, param, None);
} else {
self.params.push(param, None);
}
self
}
/// See [`InlineGenericArgs`] for details.
pub fn as_inline_args(&self) -> InlineGenericArgs<'_> {
InlineGenericArgs(self)
}
}
impl GenericParam {
/// Create new lifetime param from name.
///
/// ```
/// # use venial::GenericParam;
/// GenericParam::lifetime("a")
/// # ;
/// ```
pub fn lifetime(name: &str) -> Self {
let lifetime_ident = Ident::new(name, Span::call_site());
GenericParam {
tk_prefix: Some(Punct::new('\'', Spacing::Joint).into()),
name: lifetime_ident,
bound: None,
}
}
/// Create new lifetime param from name and bound.
///
/// ```
/// # use venial::GenericParam;
/// # use quote::quote;
/// GenericParam::bounded_lifetime("a", quote!(b + c).into_iter().collect())
/// # ;
/// ```
pub fn bounded_lifetime(name: &str, bound: Vec<TokenTree>) -> Self {
let lifetime_ident = Ident::new(name, Span::call_site());
GenericParam {
tk_prefix: Some(Punct::new('\'', Spacing::Alone).into()),
name: lifetime_ident,
bound: Some(GenericBound {
tk_colon: Punct::new(':', Spacing::Alone),
tokens: bound,
}),
}
}
/// Create new type param from name.
///
/// ```
/// # use venial::GenericParam;
/// GenericParam::ty("T")
/// # ;
/// ```
pub fn ty(name: &str) -> Self {
let ty_ident = Ident::new(name, Span::call_site());
GenericParam {
tk_prefix: None,
name: ty_ident,
bound: None,
}
}
/// Create new type param from name and bound.
///
/// ```
/// # use venial::GenericParam;
/// # use quote::quote;
/// GenericParam::bounded_ty("T", quote!(Debug + Eq).into_iter().collect())
/// # ;
/// ```
pub fn bounded_ty(name: &str, bound: Vec<TokenTree>) -> Self {
let ty_ident = Ident::new(name, Span::call_site());
GenericParam {
tk_prefix: None,
name: ty_ident,
bound: Some(GenericBound {
tk_colon: Punct::new(':', Spacing::Alone),
tokens: bound,
}),
}
}
/// Create new const param from name and type.
///
/// ```
/// # use venial::GenericParam;
/// # use quote::quote;
/// GenericParam::const_param("N", quote!(i32).into_iter().collect())
/// # ;
/// ```
pub fn const_param(name: &str, ty: Vec<TokenTree>) -> Self {
let lifetime_ident = Ident::new(name, Span::call_site());
GenericParam {
tk_prefix: Some(Ident::new("const", Span::call_site()).into()),
name: lifetime_ident,
bound: Some(GenericBound {
tk_colon: Punct::new(':', Spacing::Alone),
tokens: ty,
}),
}
}
/// Returns true if the generic param is a lifetime param.
pub fn is_lifetime(&self) -> bool {
matches!(
&self.tk_prefix,
Some(TokenTree::Punct(punct)) if punct.as_char() == '\''
)
}
/// Returns true if the generic param is a type param.
pub fn is_ty(&self) -> bool {
self.tk_prefix.is_none()
}
/// Returns true if the generic param is a const param.
pub fn is_const(&self) -> bool {
matches!(
&self.tk_prefix,
Some(TokenTree::Ident(ident)) if ident == "const"
)
}
}
impl InlineGenericArgs<'_> {
/// Returns an owned argument list from this.
///
/// # Panics
/// If `self` is a mal-formed generic argument list.
pub fn to_owned_args(&self) -> GenericArgList {
let GenericParamList {
tk_l_bracket,
params,
tk_r_bracket,
} = self.0;
GenericArgList {
tk_turbofish_colons: None, // TODO add if GenericParamList supports this, too
tk_l_bracket: tk_l_bracket.clone(),
args: Punctuated {
inner: params
.inner
.iter()
.map(|(param, punctuated_punct)| {
let name = param.name.clone();
let arg = match ¶m.tk_prefix {
Some(TokenTree::Punct(punct)) if punct.as_char() == '\'' => {
GenericArg::Lifetime {
lifetime: Lifetime {
tk_apostrophe: punct.clone(),
name,
},
}
}
Some(TokenTree::Ident(ident)) if ident == "const" => {
GenericArg::TypeOrConst {
expr: TypeExpr {
tokens: vec![TokenTree::Ident(name)],
},
}
}
Some(_) => panic!("unexpected tk_prefix, must be ' or const"),
None => GenericArg::TypeOrConst {
expr: TypeExpr {
tokens: vec![TokenTree::Ident(name)],
},
},
};
(arg, punctuated_punct.clone())
})
.collect(),
skip_last: params.skip_last,
},
tk_r_bracket: tk_r_bracket.clone(),
}
}
}
impl WhereClause {
/// Create where-clause with a single predicate.
pub fn from_predicate(item: WhereClausePredicate) -> Self {
Self::default().with_predicate(item)
}
/// Builder method, add a predicate to the where-clause.
pub fn with_predicate(mut self, item: WhereClausePredicate) -> Self {
self.items.push(item, None);
self
}
}
impl WhereClausePredicate {
/// Helper method to create a WhereClauseItem from a quote.
///
/// # Panics
///
/// Panics if given a token stream that isn't a valid where-clause item.
pub fn parse(tokens: TokenStream) -> Self {
let mut tokens = tokens.into_iter().peekable();
let left_side = crate::parse_utils::consume_stuff_until(
&mut tokens,
|token| match token {
TokenTree::Punct(punct) if punct.as_char() == ':' => true,
_ => false,
},
false,
);
let colon = match tokens.next() {
Some(TokenTree::Punct(punct)) if punct.as_char() == ':' => punct,
Some(token) => panic!(
"cannot parse where-clause item: expected ':', found token {:?}",
token
),
None => {
panic!("cannot parse where-clause item: expected colon, found end of stream")
}
};
let bound_tokens = tokens.collect();
WhereClausePredicate {
left_side,
bound: GenericBound {
tk_colon: colon,
tokens: bound_tokens,
},
}
}
}
impl TypeExpr {
/// Tries to parse this type as a [`Path`] such as `path::to::Type<'a, other::Type>`.
///
/// If it does not match a path, `None` is returned.
pub fn as_path(&self) -> Option<Path> {
let tokens = if let Some(path) = self.unwrap_invisible_group() {
tokens_from_slice(&path)
} else {
tokens_from_slice(&self.tokens)
};
consume_path(tokens)
}
/// If the type has a top-level `Group` token without separator, extract the contents. Otherwise return `None`.
fn unwrap_invisible_group(&self) -> Option<Vec<TokenTree>> {
match self.tokens.as_slice() {
[TokenTree::Group(group)] if group.delimiter() == Delimiter::None => {
Some(group.stream().into_iter().collect())
}
_ => None,
}
}
}
macro_rules! implement_span {
($Kind:ident) => {
impl $Kind {
/// Returns span of this item.
pub fn span(&self) -> Span {
self.__span()
}
}
};
}
implement_span!(Attribute);
implement_span!(AttributeValue);
implement_span!(Item);
implement_span!(Enum);
implement_span!(EnumVariant);
implement_span!(EnumVariantValue);
implement_span!(Function);
implement_span!(GenericBound);
implement_span!(GenericParam);
implement_span!(GenericParamList);
implement_span!(NamedField);
implement_span!(Struct);
implement_span!(Fields);
implement_span!(TupleField);
implement_span!(TypeExpr);
implement_span!(Union);
implement_span!(VisMarker);
implement_span!(WhereClause);
implement_span!(WhereClausePredicate);
impl InlineGenericArgs<'_> {
/// Returns span of this item.
pub fn span(&self) -> Span {
self.__span()
}
}
impl GroupSpan {
/// Create from proc_macro2 Group.
pub fn new(group: &Group) -> Self {
Self {
span: group.span(),
delimiter: group.delimiter(),
}
}
}