Skip to main content

syn/
ty.rs

1use crate::attr::Attribute;
2use crate::expr::Expr;
3use crate::generics::{BoundLifetimes, TypeParamBound};
4use crate::ident::Ident;
5use crate::lifetime::Lifetime;
6use crate::lit::LitStr;
7use crate::mac::Macro;
8use crate::path::{Path, QSelf};
9use crate::punctuated::Punctuated;
10use crate::token;
11use alloc::boxed::Box;
12use alloc::vec::Vec;
13use proc_macro2::TokenStream;
14
15ast_enum_of_structs! {
16    /// The possible types that a Rust value could have.
17    ///
18    /// # Syntax tree enum
19    ///
20    /// This type is a [syntax tree enum].
21    ///
22    /// [syntax tree enum]: crate::expr::Expr#syntax-tree-enums
23    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
24    #[non_exhaustive]
25    pub enum Type {
26        /// A fixed size array type: `[T; n]`.
27        Array(TypeArray),
28
29        /// A function pointer type: `fn(usize) -> bool`.
30        FnPtr(TypeFnPtr),
31
32        /// A type contained within invisible delimiters.
33        Group(TypeGroup),
34
35        /// An `impl Bound1 + Bound2 + Bound3` type where `Bound` is a trait or
36        /// a lifetime.
37        ImplTrait(TypeImplTrait),
38
39        /// Indication that a type should be inferred by the compiler: `_`.
40        Infer(TypeInfer),
41
42        /// A macro in the type position.
43        Macro(TypeMacro),
44
45        /// The never type: `!`.
46        Never(TypeNever),
47
48        /// A parenthesized type equivalent to the inner type.
49        Paren(TypeParen),
50
51        /// A path like `core::slice::Iter`, optionally qualified with a
52        /// self-type as in `<Vec<T> as SomeTrait>::Associated`.
53        Path(TypePath),
54
55        /// A raw pointer type: `*const T` or `*mut T`.
56        Ptr(TypePtr),
57
58        /// A reference type: `&'a T` or `&'a mut T`.
59        Reference(TypeReference),
60
61        /// A dynamically sized slice type: `[T]`.
62        Slice(TypeSlice),
63
64        /// A trait object type `dyn Bound1 + Bound2 + Bound3` where `Bound` is a
65        /// trait or a lifetime.
66        TraitObject(TypeTraitObject),
67
68        /// A tuple type: `(A, B, C, String)`.
69        Tuple(TypeTuple),
70
71        /// Tokens in type position not interpreted by Syn.
72        Verbatim(TokenStream),
73
74        // For testing exhaustiveness in downstream code, use the following idiom:
75        //
76        //     match ty {
77        //         #![cfg_attr(test, deny(non_exhaustive_omitted_patterns))]
78        //
79        //         Type::Array(ty) => {...}
80        //         Type::FnPtr(ty) => {...}
81        //         ...
82        //         Type::Verbatim(ty) => {...}
83        //
84        //         _ => { /* some sane fallback */ }
85        //     }
86        //
87        // This way we fail your tests but don't break your library when adding
88        // a variant. You will be notified by a test failure when a variant is
89        // added, so that you can add code to handle it, but your library will
90        // continue to compile and work for downstream users in the interim.
91    }
92}
93
94ast_struct! {
95    /// A fixed size array type: `[T; n]`.
96    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
97    pub struct TypeArray {
98        pub attrs: Vec<Attribute>,
99        pub bracket_token: token::Bracket,
100        pub elem: Box<Type>,
101        pub semi_token: Token![;],
102        pub len: Expr,
103    }
104}
105
106ast_struct! {
107    /// A function pointer type: `fn(usize) -> bool`.
108    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
109    pub struct TypeFnPtr {
110        pub attrs: Vec<Attribute>,
111        pub lifetimes: Option<BoundLifetimes>,
112        pub unsafety: Option<Token![unsafe]>,
113        pub abi: Option<Abi>,
114        pub fn_token: Token![fn],
115        pub paren_token: token::Paren,
116        pub inputs: Punctuated<NamedArg, Token![,]>,
117        pub variadic: Option<FnPtrVariadic>,
118        pub output: ReturnType,
119    }
120}
121
122ast_struct! {
123    /// A type contained within invisible delimiters.
124    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
125    pub struct TypeGroup {
126        pub attrs: Vec<Attribute>,
127        pub group_token: token::Group,
128        pub elem: Box<Type>,
129    }
130}
131
132ast_struct! {
133    /// An `impl Bound1 + Bound2 + Bound3` type where `Bound` is a trait or
134    /// a lifetime.
135    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
136    pub struct TypeImplTrait {
137        pub attrs: Vec<Attribute>,
138        pub impl_token: Token![impl],
139        pub bounds: Punctuated<TypeParamBound, Token![+]>,
140    }
141}
142
143ast_struct! {
144    /// Indication that a type should be inferred by the compiler: `_`.
145    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
146    pub struct TypeInfer {
147        pub attrs: Vec<Attribute>,
148        pub underscore_token: Token![_],
149    }
150}
151
152ast_struct! {
153    /// A macro in the type position.
154    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
155    pub struct TypeMacro {
156        pub attrs: Vec<Attribute>,
157        pub mac: Macro,
158    }
159}
160
161ast_struct! {
162    /// The never type: `!`.
163    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
164    pub struct TypeNever {
165        pub attrs: Vec<Attribute>,
166        pub bang_token: Token![!],
167    }
168}
169
170ast_struct! {
171    /// A parenthesized type equivalent to the inner type.
172    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
173    pub struct TypeParen {
174        pub attrs: Vec<Attribute>,
175        pub paren_token: token::Paren,
176        pub elem: Box<Type>,
177    }
178}
179
180ast_struct! {
181    /// A path like `core::slice::Iter`, optionally qualified with a
182    /// self-type as in `<Vec<T> as SomeTrait>::Associated`.
183    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
184    pub struct TypePath {
185        pub attrs: Vec<Attribute>,
186        pub qself: Option<QSelf>,
187        pub path: Path,
188    }
189}
190
191ast_struct! {
192    /// A raw pointer type: `*const T` or `*mut T`.
193    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
194    pub struct TypePtr {
195        pub attrs: Vec<Attribute>,
196        pub star_token: Token![*],
197        pub mutability: PointerMutability,
198        pub elem: Box<Type>,
199    }
200}
201
202ast_struct! {
203    /// A reference type: `&'a T` or `&'a mut T`.
204    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
205    pub struct TypeReference {
206        pub attrs: Vec<Attribute>,
207        pub and_token: Token![&],
208        pub lifetime: Option<Lifetime>,
209        pub mutability: Option<Token![mut]>,
210        pub elem: Box<Type>,
211    }
212}
213
214ast_struct! {
215    /// A dynamically sized slice type: `[T]`.
216    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
217    pub struct TypeSlice {
218        pub attrs: Vec<Attribute>,
219        pub bracket_token: token::Bracket,
220        pub elem: Box<Type>,
221    }
222}
223
224ast_struct! {
225    /// A trait object type `dyn Bound1 + Bound2 + Bound3` where `Bound` is a
226    /// trait or a lifetime.
227    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
228    pub struct TypeTraitObject {
229        pub attrs: Vec<Attribute>,
230        /// The `dyn` keyword is required since Rust 2021 edition. In editions
231        /// 2015&ndash;2018, trait objects without a `dyn` keyword are allowed
232        /// but deprecated.
233        pub dyn_token: Option<Token![dyn]>,
234        pub bounds: Punctuated<TypeParamBound, Token![+]>,
235    }
236}
237
238ast_struct! {
239    /// A tuple type: `(A, B, C, String)`.
240    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
241    pub struct TypeTuple {
242        pub attrs: Vec<Attribute>,
243        pub paren_token: token::Paren,
244        pub elems: Punctuated<Type, Token![,]>,
245    }
246}
247
248ast_struct! {
249    /// The binary interface of a function: `extern "C"`.
250    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
251    pub struct Abi {
252        pub extern_token: Token![extern],
253
254        /// ABI name is optional, but note that extern blocks and functions with
255        /// an omitted ABI name are [deprecated since Rust 1.86.0][deprecated].
256        /// Omitting the ABI after the extern keyword has always implicitly
257        /// resulted in the "C" ABI. It is now recommended to explicitly specify
258        /// the "C" ABI (`extern "C" {}` and `extern "C" fn`).
259        ///
260        /// [deprecated]: https://blog.rust-lang.org/2025/04/03/Rust-1.86.0/#make-missing-abi-lint-warn-by-default
261        pub name: Option<LitStr>,
262    }
263}
264
265ast_enum! {
266    /// Mutability of a raw pointer (`*const T`, `*mut T`), in which non-mutable
267    /// isn't the implicit default.
268    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
269    pub enum PointerMutability {
270        Const(Token![const]),
271        Mut(Token![mut]),
272    }
273}
274
275ast_struct! {
276    /// An argument in a function type: the `usize` in `fn(usize) -> bool`.
277    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
278    pub struct NamedArg {
279        pub attrs: Vec<Attribute>,
280        pub name: Option<(Ident, Token![:])>,
281        pub ty: Type,
282    }
283}
284
285ast_struct! {
286    /// The variadic argument of a function pointer like `fn(usize, ...)`.
287    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
288    pub struct FnPtrVariadic {
289        pub attrs: Vec<Attribute>,
290        pub name: Option<(Ident, Token![:])>,
291        pub dots: Token![...],
292        pub comma: Option<Token![,]>,
293    }
294}
295
296ast_enum! {
297    /// Return type of a function signature.
298    #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
299    pub enum ReturnType {
300        /// Return type is not specified.
301        ///
302        /// Functions default to `()` and closures default to type inference.
303        Default,
304        /// A particular type is returned.
305        Type(Token![->], Box<Type>),
306    }
307}
308
309#[cfg(feature = "parsing")]
310pub(crate) mod parsing {
311    use crate::attr::Attribute;
312    use crate::error::{self, Result};
313    use crate::ext::IdentExt as _;
314    use crate::generics::{BoundLifetimes, TraitBound, TraitBoundModifiers, TypeParamBound};
315    use crate::ident::Ident;
316    use crate::lifetime::Lifetime;
317    use crate::mac::{self, Macro};
318    use crate::parse::{Parse, ParseStream};
319    use crate::path;
320    use crate::path::{Path, PathArguments, QSelf};
321    use crate::punctuated::Punctuated;
322    use crate::token;
323    use crate::ty::{
324        Abi, FnPtrVariadic, NamedArg, PointerMutability, ReturnType, Type, TypeArray, TypeFnPtr,
325        TypeGroup, TypeImplTrait, TypeInfer, TypeMacro, TypeNever, TypeParen, TypePath, TypePtr,
326        TypeReference, TypeSlice, TypeTraitObject, TypeTuple,
327    };
328    use crate::verbatim;
329    use alloc::boxed::Box;
330    use alloc::vec::Vec;
331    use proc_macro2::{Span, TokenStream};
332
333    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
334    impl Parse for Type {
335        fn parse(input: ParseStream) -> Result<Self> {
336            let allow_plus = true;
337            let allow_group_generic = true;
338            ambig_ty(input, allow_plus, allow_group_generic)
339        }
340    }
341
342    impl Type {
343        /// In some positions, types may not contain the `+` character, to
344        /// disambiguate them. For example in the expression `1 as T`, T may not
345        /// contain a `+` character.
346        ///
347        /// This parser does not allow a `+`, while the default parser does.
348        #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
349        pub fn without_plus(input: ParseStream) -> Result<Self> {
350            let allow_plus = false;
351            let allow_group_generic = true;
352            ambig_ty(input, allow_plus, allow_group_generic)
353        }
354    }
355
356    pub(crate) fn ambig_ty(
357        input: ParseStream,
358        allow_plus: bool,
359        allow_group_generic: bool,
360    ) -> Result<Type> {
361        let begin = input.cursor();
362
363        if input.peek(token::Group) {
364            let mut group: TypeGroup = input.parse()?;
365            if input.peek(Token![::]) && input.peek3(Ident::peek_any) {
366                if let Type::Path(mut ty) = *group.elem {
367                    Path::parse_rest(input, &mut ty.path, false)?;
368                    return Ok(Type::Path(ty));
369                } else {
370                    return Ok(Type::Path(TypePath {
371                        attrs: Vec::new(),
372                        qself: Some(QSelf {
373                            lt_token: Token![<](group.group_token.span),
374                            position: 0,
375                            as_token: None,
376                            gt_token: Token![>](group.group_token.span),
377                            ty: group.elem,
378                        }),
379                        path: Path::parse_helper(input, false)?,
380                    }));
381                }
382            } else if input.peek(Token![<]) && allow_group_generic
383                || input.peek(Token![::]) && input.peek3(Token![<])
384            {
385                if let Type::Path(mut ty) = *group.elem {
386                    let arguments = &mut ty.path.segments.last_mut().unwrap().arguments;
387                    if arguments.is_none() {
388                        *arguments = PathArguments::AngleBracketed(input.parse()?);
389                        Path::parse_rest(input, &mut ty.path, false)?;
390                        return Ok(Type::Path(ty));
391                    } else {
392                        *group.elem = Type::Path(ty);
393                    }
394                }
395            }
396            return Ok(Type::Group(group));
397        }
398
399        let mut lifetimes = None::<BoundLifetimes>;
400        let mut lookahead = input.lookahead1();
401        if lookahead.peek(Token![for]) {
402            lifetimes = input.parse()?;
403            lookahead = input.lookahead1();
404            if !lookahead.peek(Ident)
405                && !lookahead.peek(Token![fn])
406                && !lookahead.peek(Token![unsafe])
407                && !lookahead.peek(Token![extern])
408                && !lookahead.peek(Token![super])
409                && !lookahead.peek(Token![self])
410                && !lookahead.peek(Token![Self])
411                && !lookahead.peek(Token![crate])
412                || input.peek(Token![dyn])
413            {
414                return Err(lookahead.error());
415            }
416        }
417
418        if lookahead.peek(token::Paren) {
419            let content;
420            let paren_token = parenthesized!(content in input);
421            if content.is_empty() {
422                return Ok(Type::Tuple(TypeTuple {
423                    attrs: Vec::new(),
424                    paren_token,
425                    elems: Punctuated::new(),
426                }));
427            }
428            if content.peek(Lifetime) {
429                return Ok(Type::Paren(TypeParen {
430                    attrs: Vec::new(),
431                    paren_token,
432                    elem: Box::new(Type::TraitObject(content.parse()?)),
433                }));
434            }
435            if content.peek(Token![?]) {
436                return Ok(Type::TraitObject(TypeTraitObject {
437                    attrs: Vec::new(),
438                    dyn_token: None,
439                    bounds: {
440                        let mut bounds = Punctuated::new();
441                        bounds.push_value(TypeParamBound::Trait(TraitBound {
442                            paren_token: Some(paren_token),
443                            ..content.parse()?
444                        }));
445                        while let Some(plus) = input.parse()? {
446                            bounds.push_punct(plus);
447                            bounds.push_value({
448                                let allow_precise_capture = false;
449                                let allow_const = false;
450                                TypeParamBound::parse_single(
451                                    input,
452                                    allow_precise_capture,
453                                    allow_const,
454                                )?
455                            });
456                        }
457                        bounds
458                    },
459                }));
460            }
461            let mut first: Type = content.parse()?;
462            if content.peek(Token![,]) {
463                return Ok(Type::Tuple(TypeTuple {
464                    attrs: Vec::new(),
465                    paren_token,
466                    elems: {
467                        let mut elems = Punctuated::new();
468                        elems.push_value(first);
469                        elems.push_punct(content.parse()?);
470                        while !content.is_empty() {
471                            elems.push_value(content.parse()?);
472                            if content.is_empty() {
473                                break;
474                            }
475                            elems.push_punct(content.parse()?);
476                        }
477                        elems
478                    },
479                }));
480            }
481            if allow_plus && input.peek(Token![+]) {
482                loop {
483                    let first = match first {
484                        Type::Path(TypePath {
485                            attrs: _,
486                            qself: None,
487                            path,
488                        }) => TypeParamBound::Trait(TraitBound {
489                            paren_token: Some(paren_token),
490                            lifetimes: None,
491                            modifiers: TraitBoundModifiers {},
492                            maybe: None,
493                            path,
494                        }),
495                        Type::TraitObject(TypeTraitObject {
496                            attrs: _,
497                            dyn_token: None,
498                            bounds,
499                        }) => {
500                            if bounds.len() > 1 || bounds.trailing_punct() {
501                                first = Type::TraitObject(TypeTraitObject {
502                                    attrs: Vec::new(),
503                                    dyn_token: None,
504                                    bounds,
505                                });
506                                break;
507                            }
508                            match bounds.into_iter().next().unwrap() {
509                                TypeParamBound::Trait(trait_bound) => {
510                                    TypeParamBound::Trait(TraitBound {
511                                        paren_token: Some(paren_token),
512                                        ..trait_bound
513                                    })
514                                }
515                                other @ (TypeParamBound::Lifetime(_)
516                                | TypeParamBound::PreciseCapture(_)
517                                | TypeParamBound::Verbatim(_)) => other,
518                            }
519                        }
520                        _ => break,
521                    };
522                    return Ok(Type::TraitObject(TypeTraitObject {
523                        attrs: Vec::new(),
524                        dyn_token: None,
525                        bounds: {
526                            let mut bounds = Punctuated::new();
527                            bounds.push_value(first);
528                            while let Some(plus) = input.parse()? {
529                                bounds.push_punct(plus);
530                                bounds.push_value({
531                                    let allow_precise_capture = false;
532                                    let allow_const = false;
533                                    TypeParamBound::parse_single(
534                                        input,
535                                        allow_precise_capture,
536                                        allow_const,
537                                    )?
538                                });
539                            }
540                            bounds
541                        },
542                    }));
543                }
544            }
545            Ok(Type::Paren(TypeParen {
546                attrs: Vec::new(),
547                paren_token,
548                elem: Box::new(first),
549            }))
550        } else if lookahead.peek(Token![fn])
551            || lookahead.peek(Token![unsafe])
552            || lookahead.peek(Token![extern])
553        {
554            let mut fn_ptr: TypeFnPtr = input.parse()?;
555            fn_ptr.lifetimes = lifetimes;
556            Ok(Type::FnPtr(fn_ptr))
557        } else if cfg!(feature = "full")
558            && token::parsing::peek_keyword(input.cursor(), "builtin")
559            && input.peek2(Token![#])
560        {
561            token::parsing::keyword(input, "builtin")?;
562            input.parse::<Token![#]>()?;
563            input.parse::<Ident>()?;
564            let args;
565            parenthesized!(args in input);
566            args.parse::<TokenStream>()?;
567            Ok(Type::Verbatim(verbatim::between(begin, input.cursor())))
568        } else if lookahead.peek(Ident)
569            || input.peek(Token![super])
570            || input.peek(Token![self])
571            || input.peek(Token![Self])
572            || input.peek(Token![crate])
573            || lookahead.peek(Token![::])
574            || lookahead.peek(Token![<])
575        {
576            let ty: TypePath = input.parse()?;
577            if ty.qself.is_some() {
578                return Ok(Type::Path(ty));
579            }
580
581            if input.peek(Token![!]) && !input.peek(Token![!=]) && ty.path.is_mod_style() {
582                let bang_token: Token![!] = input.parse()?;
583                let (delimiter, tokens) = mac::parse_delimiter(input)?;
584                return Ok(Type::Macro(TypeMacro {
585                    attrs: Vec::new(),
586                    mac: Macro {
587                        path: ty.path,
588                        bang_token,
589                        delimiter,
590                        tokens,
591                    },
592                }));
593            }
594
595            if lifetimes.is_some() || allow_plus && input.peek(Token![+]) {
596                let mut bounds = Punctuated::new();
597                bounds.push_value(TypeParamBound::Trait(TraitBound {
598                    paren_token: None,
599                    lifetimes,
600                    modifiers: TraitBoundModifiers {},
601                    maybe: None,
602                    path: ty.path,
603                }));
604                if allow_plus {
605                    while input.peek(Token![+]) {
606                        bounds.push_punct(input.parse()?);
607                        if !(input.peek(Ident::peek_any)
608                            || input.peek(Token![::])
609                            || input.peek(Token![?])
610                            || input.peek(Lifetime)
611                            || input.peek(token::Paren))
612                        {
613                            break;
614                        }
615                        bounds.push_value({
616                            let allow_precise_capture = false;
617                            let allow_const = false;
618                            TypeParamBound::parse_single(input, allow_precise_capture, allow_const)?
619                        });
620                    }
621                }
622                return Ok(Type::TraitObject(TypeTraitObject {
623                    attrs: Vec::new(),
624                    dyn_token: None,
625                    bounds,
626                }));
627            }
628
629            Ok(Type::Path(ty))
630        } else if lookahead.peek(Token![dyn]) {
631            let dyn_token: Token![dyn] = input.parse()?;
632            let dyn_span = dyn_token.span;
633            let star_token: Option<Token![*]> = input.parse()?;
634            let bounds = TypeTraitObject::parse_bounds(dyn_span, input, allow_plus)?;
635            Ok(if star_token.is_some() {
636                Type::Verbatim(verbatim::between(begin, input.cursor()))
637            } else {
638                Type::TraitObject(TypeTraitObject {
639                    attrs: Vec::new(),
640                    dyn_token: Some(dyn_token),
641                    bounds,
642                })
643            })
644        } else if lookahead.peek(token::Bracket) {
645            let content;
646            let bracket_token = bracketed!(content in input);
647            let elem: Type = content.parse()?;
648            if content.peek(Token![;]) {
649                Ok(Type::Array(TypeArray {
650                    attrs: Vec::new(),
651                    bracket_token,
652                    elem: Box::new(elem),
653                    semi_token: content.parse()?,
654                    len: content.parse()?,
655                }))
656            } else {
657                Ok(Type::Slice(TypeSlice {
658                    attrs: Vec::new(),
659                    bracket_token,
660                    elem: Box::new(elem),
661                }))
662            }
663        } else if lookahead.peek(Token![*]) {
664            input.parse().map(Type::Ptr)
665        } else if lookahead.peek(Token![&]) {
666            input.parse().map(Type::Reference)
667        } else if lookahead.peek(Token![!]) && !input.peek(Token![=]) {
668            input.parse().map(Type::Never)
669        } else if lookahead.peek(Token![impl]) {
670            TypeImplTrait::parse(input, allow_plus).map(Type::ImplTrait)
671        } else if lookahead.peek(Token![_]) {
672            input.parse().map(Type::Infer)
673        } else if lookahead.peek(Lifetime) {
674            input.parse().map(Type::TraitObject)
675        } else {
676            Err(lookahead.error())
677        }
678    }
679
680    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
681    impl Parse for TypeSlice {
682        fn parse(input: ParseStream) -> Result<Self> {
683            let content;
684            Ok(TypeSlice {
685                attrs: Vec::new(),
686                bracket_token: bracketed!(content in input),
687                elem: content.parse()?,
688            })
689        }
690    }
691
692    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
693    impl Parse for TypeArray {
694        fn parse(input: ParseStream) -> Result<Self> {
695            let content;
696            Ok(TypeArray {
697                attrs: Vec::new(),
698                bracket_token: bracketed!(content in input),
699                elem: content.parse()?,
700                semi_token: content.parse()?,
701                len: content.parse()?,
702            })
703        }
704    }
705
706    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
707    impl Parse for TypePtr {
708        fn parse(input: ParseStream) -> Result<Self> {
709            Ok(TypePtr {
710                attrs: Vec::new(),
711                star_token: input.parse()?,
712                mutability: input.parse()?,
713                elem: Box::new(input.call(Type::without_plus)?),
714            })
715        }
716    }
717
718    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
719    impl Parse for TypeReference {
720        fn parse(input: ParseStream) -> Result<Self> {
721            Ok(TypeReference {
722                attrs: Vec::new(),
723                and_token: input.parse()?,
724                lifetime: Lifetime::parse_optional_any(input),
725                mutability: input.parse()?,
726                // & binds tighter than +, so we don't allow + here.
727                elem: Box::new(input.call(Type::without_plus)?),
728            })
729        }
730    }
731
732    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
733    impl Parse for TypeFnPtr {
734        fn parse(input: ParseStream) -> Result<Self> {
735            let args;
736            let mut variadic = None;
737
738            Ok(TypeFnPtr {
739                attrs: Vec::new(),
740                lifetimes: input.parse()?,
741                unsafety: input.parse()?,
742                abi: input.parse()?,
743                fn_token: input.parse()?,
744                paren_token: parenthesized!(args in input),
745                inputs: {
746                    let mut inputs = Punctuated::new();
747
748                    while !args.is_empty() {
749                        let attrs = args.call(Attribute::parse_outer)?;
750
751                        if inputs.empty_or_trailing()
752                            && (args.peek(Token![...])
753                                || (args.peek(Ident) || args.peek(Token![_]))
754                                    && args.peek2(Token![:])
755                                    && args.peek3(Token![...]))
756                        {
757                            variadic = Some(parse_fn_ptr_variadic(&args, attrs)?);
758                            break;
759                        }
760
761                        let allow_self = inputs.is_empty();
762                        let arg = parse_fn_ptr_arg(&args, allow_self)?;
763                        inputs.push_value(NamedArg { attrs, ..arg });
764                        if args.is_empty() {
765                            break;
766                        }
767
768                        let comma = args.parse()?;
769                        inputs.push_punct(comma);
770                    }
771
772                    inputs
773                },
774                variadic,
775                output: input.call(ReturnType::without_plus)?,
776            })
777        }
778    }
779
780    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
781    impl Parse for TypeNever {
782        fn parse(input: ParseStream) -> Result<Self> {
783            Ok(TypeNever {
784                attrs: Vec::new(),
785                bang_token: input.parse()?,
786            })
787        }
788    }
789
790    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
791    impl Parse for TypeInfer {
792        fn parse(input: ParseStream) -> Result<Self> {
793            Ok(TypeInfer {
794                attrs: Vec::new(),
795                underscore_token: input.parse()?,
796            })
797        }
798    }
799
800    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
801    impl Parse for TypeTuple {
802        fn parse(input: ParseStream) -> Result<Self> {
803            let content;
804            let paren_token = parenthesized!(content in input);
805
806            if content.is_empty() {
807                return Ok(TypeTuple {
808                    attrs: Vec::new(),
809                    paren_token,
810                    elems: Punctuated::new(),
811                });
812            }
813
814            let first: Type = content.parse()?;
815            Ok(TypeTuple {
816                attrs: Vec::new(),
817                paren_token,
818                elems: {
819                    let mut elems = Punctuated::new();
820                    elems.push_value(first);
821                    elems.push_punct(content.parse()?);
822                    while !content.is_empty() {
823                        elems.push_value(content.parse()?);
824                        if content.is_empty() {
825                            break;
826                        }
827                        elems.push_punct(content.parse()?);
828                    }
829                    elems
830                },
831            })
832        }
833    }
834
835    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
836    impl Parse for TypeMacro {
837        fn parse(input: ParseStream) -> Result<Self> {
838            Ok(TypeMacro {
839                attrs: Vec::new(),
840                mac: input.parse()?,
841            })
842        }
843    }
844
845    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
846    impl Parse for TypePath {
847        fn parse(input: ParseStream) -> Result<Self> {
848            let expr_style = false;
849            let (qself, path) = path::parsing::qpath(input, expr_style)?;
850            Ok(TypePath {
851                attrs: Vec::new(),
852                qself,
853                path,
854            })
855        }
856    }
857
858    impl ReturnType {
859        #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
860        pub fn without_plus(input: ParseStream) -> Result<Self> {
861            let allow_plus = false;
862            Self::parse(input, allow_plus)
863        }
864
865        pub(crate) fn parse(input: ParseStream, allow_plus: bool) -> Result<Self> {
866            if input.peek(Token![->]) {
867                let arrow = input.parse()?;
868                let allow_group_generic = true;
869                let ty = ambig_ty(input, allow_plus, allow_group_generic)?;
870                Ok(ReturnType::Type(arrow, Box::new(ty)))
871            } else {
872                Ok(ReturnType::Default)
873            }
874        }
875    }
876
877    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
878    impl Parse for ReturnType {
879        fn parse(input: ParseStream) -> Result<Self> {
880            let allow_plus = true;
881            Self::parse(input, allow_plus)
882        }
883    }
884
885    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
886    impl Parse for TypeTraitObject {
887        fn parse(input: ParseStream) -> Result<Self> {
888            let allow_plus = true;
889            Self::parse(input, allow_plus)
890        }
891    }
892
893    impl TypeTraitObject {
894        #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
895        pub fn without_plus(input: ParseStream) -> Result<Self> {
896            let allow_plus = false;
897            Self::parse(input, allow_plus)
898        }
899
900        // Only allow multiple trait references if allow_plus is true.
901        pub(crate) fn parse(input: ParseStream, allow_plus: bool) -> Result<Self> {
902            let dyn_token: Option<Token![dyn]> = input.parse()?;
903            let dyn_span = match &dyn_token {
904                Some(token) => token.span,
905                None => input.span(),
906            };
907            let bounds = Self::parse_bounds(dyn_span, input, allow_plus)?;
908            Ok(TypeTraitObject {
909                attrs: Vec::new(),
910                dyn_token,
911                bounds,
912            })
913        }
914
915        fn parse_bounds(
916            dyn_span: Span,
917            input: ParseStream,
918            allow_plus: bool,
919        ) -> Result<Punctuated<TypeParamBound, Token![+]>> {
920            let allow_precise_capture = false;
921            let allow_const = false;
922            let bounds = TypeParamBound::parse_multiple(
923                input,
924                allow_plus,
925                allow_precise_capture,
926                allow_const,
927            )?;
928            let mut last_lifetime_span = None;
929            let mut at_least_one_trait = false;
930            for bound in &bounds {
931                match bound {
932                    TypeParamBound::Trait(_) => {
933                        at_least_one_trait = true;
934                        break;
935                    }
936                    TypeParamBound::Lifetime(lifetime) => {
937                        last_lifetime_span = Some(lifetime.ident.span());
938                    }
939                    TypeParamBound::PreciseCapture(_) | TypeParamBound::Verbatim(_) => {
940                        unreachable!()
941                    }
942                }
943            }
944            // Just lifetimes like `'a + 'b` is not a TraitObject.
945            if !at_least_one_trait {
946                let msg = "at least one trait is required for an object type";
947                return Err(error::new2(dyn_span, last_lifetime_span.unwrap(), msg));
948            }
949            Ok(bounds)
950        }
951    }
952
953    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
954    impl Parse for TypeImplTrait {
955        fn parse(input: ParseStream) -> Result<Self> {
956            let allow_plus = true;
957            Self::parse(input, allow_plus)
958        }
959    }
960
961    impl TypeImplTrait {
962        #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
963        pub fn without_plus(input: ParseStream) -> Result<Self> {
964            let allow_plus = false;
965            Self::parse(input, allow_plus)
966        }
967
968        pub(crate) fn parse(input: ParseStream, allow_plus: bool) -> Result<Self> {
969            let impl_token: Token![impl] = input.parse()?;
970            let allow_precise_capture = true;
971            let allow_const = true;
972            let bounds = TypeParamBound::parse_multiple(
973                input,
974                allow_plus,
975                allow_precise_capture,
976                allow_const,
977            )?;
978            let mut last_nontrait_span = None;
979            let mut at_least_one_trait = false;
980            for bound in &bounds {
981                match bound {
982                    TypeParamBound::Trait(_) => {
983                        at_least_one_trait = true;
984                        break;
985                    }
986                    TypeParamBound::Lifetime(lifetime) => {
987                        last_nontrait_span = Some(lifetime.ident.span());
988                    }
989                    TypeParamBound::PreciseCapture(precise_capture) => {
990                        #[cfg(feature = "full")]
991                        {
992                            last_nontrait_span = Some(precise_capture.gt_token.span);
993                        }
994                        #[cfg(not(feature = "full"))]
995                        {
996                            _ = precise_capture;
997                            unreachable!();
998                        }
999                    }
1000                    TypeParamBound::Verbatim(_) => {
1001                        // `[const] Trait`
1002                        at_least_one_trait = true;
1003                        break;
1004                    }
1005                }
1006            }
1007            if !at_least_one_trait {
1008                let msg = "at least one trait must be specified";
1009                return Err(error::new2(
1010                    impl_token.span,
1011                    last_nontrait_span.unwrap(),
1012                    msg,
1013                ));
1014            }
1015            Ok(TypeImplTrait {
1016                attrs: Vec::new(),
1017                impl_token,
1018                bounds,
1019            })
1020        }
1021    }
1022
1023    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1024    impl Parse for TypeGroup {
1025        fn parse(input: ParseStream) -> Result<Self> {
1026            let group = crate::group::parse_group(input)?;
1027            Ok(TypeGroup {
1028                attrs: Vec::new(),
1029                group_token: group.token,
1030                elem: group.content.parse()?,
1031            })
1032        }
1033    }
1034
1035    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1036    impl Parse for TypeParen {
1037        fn parse(input: ParseStream) -> Result<Self> {
1038            let allow_plus = false;
1039            Self::parse(input, allow_plus)
1040        }
1041    }
1042
1043    impl TypeParen {
1044        fn parse(input: ParseStream, allow_plus: bool) -> Result<Self> {
1045            let content;
1046            Ok(TypeParen {
1047                attrs: Vec::new(),
1048                paren_token: parenthesized!(content in input),
1049                elem: Box::new({
1050                    let allow_group_generic = true;
1051                    ambig_ty(&content, allow_plus, allow_group_generic)?
1052                }),
1053            })
1054        }
1055    }
1056
1057    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1058    impl Parse for NamedArg {
1059        fn parse(input: ParseStream) -> Result<Self> {
1060            let allow_self = false;
1061            parse_fn_ptr_arg(input, allow_self)
1062        }
1063    }
1064
1065    fn parse_fn_ptr_arg(input: ParseStream, allow_self: bool) -> Result<NamedArg> {
1066        let attrs = input.call(Attribute::parse_outer)?;
1067
1068        let begin = input.cursor();
1069
1070        let has_mut_self = allow_self && input.peek(Token![mut]) && input.peek2(Token![self]);
1071        if has_mut_self {
1072            input.parse::<Token![mut]>()?;
1073        }
1074
1075        let mut has_self = false;
1076        let mut name = if (input.peek(Ident) || input.peek(Token![_]) || {
1077            has_self = allow_self && input.peek(Token![self]);
1078            has_self
1079        }) && input.peek2(Token![:])
1080            && !input.peek2(Token![::])
1081        {
1082            let name = input.call(Ident::parse_any)?;
1083            let colon: Token![:] = input.parse()?;
1084            Some((name, colon))
1085        } else {
1086            has_self = false;
1087            None
1088        };
1089
1090        let ty = if allow_self && !has_self && input.peek(Token![mut]) && input.peek2(Token![self])
1091        {
1092            input.parse::<Token![mut]>()?;
1093            input.parse::<Token![self]>()?;
1094            None
1095        } else if has_mut_self && name.is_none() {
1096            input.parse::<Token![self]>()?;
1097            None
1098        } else {
1099            Some(input.parse()?)
1100        };
1101
1102        let ty = match ty {
1103            Some(ty) if !has_mut_self => ty,
1104            _ => {
1105                name = None;
1106                Type::Verbatim(verbatim::between(begin, input.cursor()))
1107            }
1108        };
1109
1110        Ok(NamedArg { attrs, name, ty })
1111    }
1112
1113    fn parse_fn_ptr_variadic(input: ParseStream, attrs: Vec<Attribute>) -> Result<FnPtrVariadic> {
1114        Ok(FnPtrVariadic {
1115            attrs,
1116            name: if input.peek(Ident) || input.peek(Token![_]) {
1117                let name = input.call(Ident::parse_any)?;
1118                let colon: Token![:] = input.parse()?;
1119                Some((name, colon))
1120            } else {
1121                None
1122            },
1123            dots: input.parse()?,
1124            comma: input.parse()?,
1125        })
1126    }
1127
1128    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1129    impl Parse for Abi {
1130        fn parse(input: ParseStream) -> Result<Self> {
1131            Ok(Abi {
1132                extern_token: input.parse()?,
1133                name: input.parse()?,
1134            })
1135        }
1136    }
1137
1138    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1139    impl Parse for Option<Abi> {
1140        fn parse(input: ParseStream) -> Result<Self> {
1141            if input.peek(Token![extern]) {
1142                input.parse().map(Some)
1143            } else {
1144                Ok(None)
1145            }
1146        }
1147    }
1148
1149    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1150    impl Parse for PointerMutability {
1151        fn parse(input: ParseStream) -> Result<Self> {
1152            let lookahead = input.lookahead1();
1153            if lookahead.peek(Token![const]) {
1154                Ok(PointerMutability::Const(input.parse()?))
1155            } else if lookahead.peek(Token![mut]) {
1156                Ok(PointerMutability::Mut(input.parse()?))
1157            } else {
1158                Err(lookahead.error())
1159            }
1160        }
1161    }
1162}
1163
1164#[cfg(feature = "printing")]
1165mod printing {
1166    use crate::attr::FilterAttrs;
1167    use crate::path;
1168    use crate::path::printing::PathStyle;
1169    use crate::ty::{
1170        Abi, FnPtrVariadic, NamedArg, PointerMutability, ReturnType, TypeArray, TypeFnPtr,
1171        TypeGroup, TypeImplTrait, TypeInfer, TypeMacro, TypeNever, TypeParen, TypePath, TypePtr,
1172        TypeReference, TypeSlice, TypeTraitObject, TypeTuple,
1173    };
1174    use proc_macro2::TokenStream;
1175    use quote::{ToTokens, TokenStreamExt as _};
1176
1177    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
1178    impl ToTokens for TypeSlice {
1179        fn to_tokens(&self, tokens: &mut TokenStream) {
1180            self.bracket_token.surround(tokens, |tokens| {
1181                self.elem.to_tokens(tokens);
1182            });
1183        }
1184    }
1185
1186    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
1187    impl ToTokens for TypeArray {
1188        fn to_tokens(&self, tokens: &mut TokenStream) {
1189            self.bracket_token.surround(tokens, |tokens| {
1190                self.elem.to_tokens(tokens);
1191                self.semi_token.to_tokens(tokens);
1192                self.len.to_tokens(tokens);
1193            });
1194        }
1195    }
1196
1197    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
1198    impl ToTokens for TypePtr {
1199        fn to_tokens(&self, tokens: &mut TokenStream) {
1200            self.star_token.to_tokens(tokens);
1201            self.mutability.to_tokens(tokens);
1202            self.elem.to_tokens(tokens);
1203        }
1204    }
1205
1206    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
1207    impl ToTokens for TypeReference {
1208        fn to_tokens(&self, tokens: &mut TokenStream) {
1209            self.and_token.to_tokens(tokens);
1210            self.lifetime.to_tokens(tokens);
1211            self.mutability.to_tokens(tokens);
1212            self.elem.to_tokens(tokens);
1213        }
1214    }
1215
1216    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
1217    impl ToTokens for TypeFnPtr {
1218        fn to_tokens(&self, tokens: &mut TokenStream) {
1219            self.lifetimes.to_tokens(tokens);
1220            self.unsafety.to_tokens(tokens);
1221            self.abi.to_tokens(tokens);
1222            self.fn_token.to_tokens(tokens);
1223            self.paren_token.surround(tokens, |tokens| {
1224                self.inputs.to_tokens(tokens);
1225                if let Some(variadic) = &self.variadic {
1226                    if !self.inputs.empty_or_trailing() {
1227                        let span = variadic.dots.spans[0];
1228                        Token![,](span).to_tokens(tokens);
1229                    }
1230                    variadic.to_tokens(tokens);
1231                }
1232            });
1233            self.output.to_tokens(tokens);
1234        }
1235    }
1236
1237    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
1238    impl ToTokens for TypeNever {
1239        fn to_tokens(&self, tokens: &mut TokenStream) {
1240            self.bang_token.to_tokens(tokens);
1241        }
1242    }
1243
1244    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
1245    impl ToTokens for TypeTuple {
1246        fn to_tokens(&self, tokens: &mut TokenStream) {
1247            self.paren_token.surround(tokens, |tokens| {
1248                self.elems.to_tokens(tokens);
1249                // If we only have one argument, we need a trailing comma to
1250                // distinguish TypeTuple from TypeParen.
1251                if self.elems.len() == 1 && !self.elems.trailing_punct() {
1252                    <Token![,]>::default().to_tokens(tokens);
1253                }
1254            });
1255        }
1256    }
1257
1258    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
1259    impl ToTokens for TypePath {
1260        fn to_tokens(&self, tokens: &mut TokenStream) {
1261            path::printing::print_qpath(tokens, &self.qself, &self.path, PathStyle::AsWritten);
1262        }
1263    }
1264
1265    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
1266    impl ToTokens for TypeTraitObject {
1267        fn to_tokens(&self, tokens: &mut TokenStream) {
1268            self.dyn_token.to_tokens(tokens);
1269            self.bounds.to_tokens(tokens);
1270        }
1271    }
1272
1273    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
1274    impl ToTokens for TypeImplTrait {
1275        fn to_tokens(&self, tokens: &mut TokenStream) {
1276            self.impl_token.to_tokens(tokens);
1277            self.bounds.to_tokens(tokens);
1278        }
1279    }
1280
1281    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
1282    impl ToTokens for TypeGroup {
1283        fn to_tokens(&self, tokens: &mut TokenStream) {
1284            self.group_token.surround(tokens, |tokens| {
1285                self.elem.to_tokens(tokens);
1286            });
1287        }
1288    }
1289
1290    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
1291    impl ToTokens for TypeParen {
1292        fn to_tokens(&self, tokens: &mut TokenStream) {
1293            self.paren_token.surround(tokens, |tokens| {
1294                self.elem.to_tokens(tokens);
1295            });
1296        }
1297    }
1298
1299    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
1300    impl ToTokens for TypeInfer {
1301        fn to_tokens(&self, tokens: &mut TokenStream) {
1302            self.underscore_token.to_tokens(tokens);
1303        }
1304    }
1305
1306    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
1307    impl ToTokens for TypeMacro {
1308        fn to_tokens(&self, tokens: &mut TokenStream) {
1309            self.mac.to_tokens(tokens);
1310        }
1311    }
1312
1313    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
1314    impl ToTokens for ReturnType {
1315        fn to_tokens(&self, tokens: &mut TokenStream) {
1316            match self {
1317                ReturnType::Default => {}
1318                ReturnType::Type(arrow, ty) => {
1319                    arrow.to_tokens(tokens);
1320                    ty.to_tokens(tokens);
1321                }
1322            }
1323        }
1324    }
1325
1326    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
1327    impl ToTokens for NamedArg {
1328        fn to_tokens(&self, tokens: &mut TokenStream) {
1329            tokens.append_all(self.attrs.outer());
1330            if let Some((name, colon)) = &self.name {
1331                name.to_tokens(tokens);
1332                colon.to_tokens(tokens);
1333            }
1334            self.ty.to_tokens(tokens);
1335        }
1336    }
1337
1338    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
1339    impl ToTokens for FnPtrVariadic {
1340        fn to_tokens(&self, tokens: &mut TokenStream) {
1341            tokens.append_all(self.attrs.outer());
1342            if let Some((name, colon)) = &self.name {
1343                name.to_tokens(tokens);
1344                colon.to_tokens(tokens);
1345            }
1346            self.dots.to_tokens(tokens);
1347            self.comma.to_tokens(tokens);
1348        }
1349    }
1350
1351    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
1352    impl ToTokens for Abi {
1353        fn to_tokens(&self, tokens: &mut TokenStream) {
1354            self.extern_token.to_tokens(tokens);
1355            self.name.to_tokens(tokens);
1356        }
1357    }
1358
1359    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
1360    impl ToTokens for PointerMutability {
1361        fn to_tokens(&self, tokens: &mut TokenStream) {
1362            match self {
1363                PointerMutability::Const(const_token) => const_token.to_tokens(tokens),
1364                PointerMutability::Mut(mut_token) => mut_token.to_tokens(tokens),
1365            }
1366        }
1367    }
1368}