ty.rs 44 KB

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