parse.rs 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421
  1. // SPDX-License-Identifier: Apache-2.0 OR MIT
  2. //! Parsing interface for parsing a token stream into a syntax tree node.
  3. //!
  4. //! Parsing in Syn is built on parser functions that take in a [`ParseStream`]
  5. //! and produce a [`Result<T>`] where `T` is some syntax tree node. Underlying
  6. //! these parser functions is a lower level mechanism built around the
  7. //! [`Cursor`] type. `Cursor` is a cheaply copyable cursor over a range of
  8. //! tokens in a token stream.
  9. //!
  10. //! [`Result<T>`]: Result
  11. //! [`Cursor`]: crate::buffer::Cursor
  12. //!
  13. //! # Example
  14. //!
  15. //! Here is a snippet of parsing code to get a feel for the style of the
  16. //! library. We define data structures for a subset of Rust syntax including
  17. //! enums (not shown) and structs, then provide implementations of the [`Parse`]
  18. //! trait to parse these syntax tree data structures from a token stream.
  19. //!
  20. //! Once `Parse` impls have been defined, they can be called conveniently from a
  21. //! procedural macro through [`parse_macro_input!`] as shown at the bottom of
  22. //! the snippet. If the caller provides syntactically invalid input to the
  23. //! procedural macro, they will receive a helpful compiler error message
  24. //! pointing out the exact token that triggered the failure to parse.
  25. //!
  26. //! [`parse_macro_input!`]: crate::parse_macro_input!
  27. //!
  28. //! ```
  29. //! # extern crate proc_macro;
  30. //! #
  31. //! use proc_macro::TokenStream;
  32. //! use syn::{braced, parse_macro_input, token, Field, Ident, Result, Token};
  33. //! use syn::parse::{Parse, ParseStream};
  34. //! use syn::punctuated::Punctuated;
  35. //!
  36. //! enum Item {
  37. //! Struct(ItemStruct),
  38. //! Enum(ItemEnum),
  39. //! }
  40. //!
  41. //! struct ItemStruct {
  42. //! struct_token: Token![struct],
  43. //! ident: Ident,
  44. //! brace_token: token::Brace,
  45. //! fields: Punctuated<Field, Token![,]>,
  46. //! }
  47. //! #
  48. //! # enum ItemEnum {}
  49. //!
  50. //! impl Parse for Item {
  51. //! fn parse(input: ParseStream) -> Result<Self> {
  52. //! let lookahead = input.lookahead1();
  53. //! if lookahead.peek(Token![struct]) {
  54. //! input.parse().map(Item::Struct)
  55. //! } else if lookahead.peek(Token![enum]) {
  56. //! input.parse().map(Item::Enum)
  57. //! } else {
  58. //! Err(lookahead.error())
  59. //! }
  60. //! }
  61. //! }
  62. //!
  63. //! impl Parse for ItemStruct {
  64. //! fn parse(input: ParseStream) -> Result<Self> {
  65. //! let content;
  66. //! Ok(ItemStruct {
  67. //! struct_token: input.parse()?,
  68. //! ident: input.parse()?,
  69. //! brace_token: braced!(content in input),
  70. //! fields: content.parse_terminated(Field::parse_named, Token![,])?,
  71. //! })
  72. //! }
  73. //! }
  74. //! #
  75. //! # impl Parse for ItemEnum {
  76. //! # fn parse(input: ParseStream) -> Result<Self> {
  77. //! # unimplemented!()
  78. //! # }
  79. //! # }
  80. //!
  81. //! # const IGNORE: &str = stringify! {
  82. //! #[proc_macro]
  83. //! # };
  84. //! pub fn my_macro(tokens: TokenStream) -> TokenStream {
  85. //! let input = parse_macro_input!(tokens as Item);
  86. //!
  87. //! /* ... */
  88. //! # TokenStream::new()
  89. //! }
  90. //! ```
  91. //!
  92. //! # The `syn::parse*` functions
  93. //!
  94. //! The [`syn::parse`], [`syn::parse2`], and [`syn::parse_str`] functions serve
  95. //! as an entry point for parsing syntax tree nodes that can be parsed in an
  96. //! obvious default way. These functions can return any syntax tree node that
  97. //! implements the [`Parse`] trait, which includes most types in Syn.
  98. //!
  99. //! [`syn::parse`]: crate::parse()
  100. //! [`syn::parse2`]: crate::parse2()
  101. //! [`syn::parse_str`]: crate::parse_str()
  102. //!
  103. //! ```
  104. //! use syn::Type;
  105. //!
  106. //! # fn run_parser() -> syn::Result<()> {
  107. //! let t: Type = syn::parse_str("std::collections::HashMap<String, Value>")?;
  108. //! # Ok(())
  109. //! # }
  110. //! #
  111. //! # run_parser().unwrap();
  112. //! ```
  113. //!
  114. //! The [`parse_quote!`] macro also uses this approach.
  115. //!
  116. //! [`parse_quote!`]: crate::parse_quote!
  117. //!
  118. //! # The `Parser` trait
  119. //!
  120. //! Some types can be parsed in several ways depending on context. For example
  121. //! an [`Attribute`] can be either "outer" like `#[...]` or "inner" like
  122. //! `#![...]` and parsing the wrong one would be a bug. Similarly [`Punctuated`]
  123. //! may or may not allow trailing punctuation, and parsing it the wrong way
  124. //! would either reject valid input or accept invalid input.
  125. //!
  126. //! [`Attribute`]: crate::Attribute
  127. //! [`Punctuated`]: crate::punctuated
  128. //!
  129. //! The `Parse` trait is not implemented in these cases because there is no good
  130. //! behavior to consider the default.
  131. //!
  132. //! ```compile_fail
  133. //! # extern crate proc_macro;
  134. //! #
  135. //! # use syn::punctuated::Punctuated;
  136. //! # use syn::{PathSegment, Result, Token};
  137. //! #
  138. //! # fn f(tokens: proc_macro::TokenStream) -> Result<()> {
  139. //! #
  140. //! // Can't parse `Punctuated` without knowing whether trailing punctuation
  141. //! // should be allowed in this context.
  142. //! let path: Punctuated<PathSegment, Token![::]> = syn::parse(tokens)?;
  143. //! #
  144. //! # Ok(())
  145. //! # }
  146. //! ```
  147. //!
  148. //! In these cases the types provide a choice of parser functions rather than a
  149. //! single `Parse` implementation, and those parser functions can be invoked
  150. //! through the [`Parser`] trait.
  151. //!
  152. //!
  153. //! ```
  154. //! # extern crate proc_macro;
  155. //! #
  156. //! use proc_macro::TokenStream;
  157. //! use syn::parse::Parser;
  158. //! use syn::punctuated::Punctuated;
  159. //! use syn::{Attribute, Expr, PathSegment, Result, Token};
  160. //!
  161. //! fn call_some_parser_methods(input: TokenStream) -> Result<()> {
  162. //! // Parse a nonempty sequence of path segments separated by `::` punctuation
  163. //! // with no trailing punctuation.
  164. //! let tokens = input.clone();
  165. //! let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty;
  166. //! let _path = parser.parse(tokens)?;
  167. //!
  168. //! // Parse a possibly empty sequence of expressions terminated by commas with
  169. //! // an optional trailing punctuation.
  170. //! let tokens = input.clone();
  171. //! let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
  172. //! let _args = parser.parse(tokens)?;
  173. //!
  174. //! // Parse zero or more outer attributes but not inner attributes.
  175. //! let tokens = input.clone();
  176. //! let parser = Attribute::parse_outer;
  177. //! let _attrs = parser.parse(tokens)?;
  178. //!
  179. //! Ok(())
  180. //! }
  181. //! ```
  182. #[path = "discouraged.rs"]
  183. pub mod discouraged;
  184. use crate::buffer::{Cursor, TokenBuffer};
  185. use crate::error;
  186. use crate::lookahead;
  187. use crate::punctuated::Punctuated;
  188. use crate::token::Token;
  189. use proc_macro2::{Delimiter, Group, Literal, Punct, Span, TokenStream, TokenTree};
  190. #[cfg(feature = "printing")]
  191. use quote::ToTokens;
  192. use std::cell::Cell;
  193. use std::fmt::{self, Debug, Display};
  194. #[cfg(feature = "extra-traits")]
  195. use std::hash::{Hash, Hasher};
  196. use std::marker::PhantomData;
  197. use std::mem;
  198. use std::ops::Deref;
  199. use std::panic::{RefUnwindSafe, UnwindSafe};
  200. use std::rc::Rc;
  201. use std::str::FromStr;
  202. pub use crate::error::{Error, Result};
  203. pub use crate::lookahead::{End, Lookahead1, Peek};
  204. /// Parsing interface implemented by all types that can be parsed in a default
  205. /// way from a token stream.
  206. ///
  207. /// Refer to the [module documentation] for details about implementing and using
  208. /// the `Parse` trait.
  209. ///
  210. /// [module documentation]: self
  211. pub trait Parse: Sized {
  212. fn parse(input: ParseStream) -> Result<Self>;
  213. }
  214. /// Input to a Syn parser function.
  215. ///
  216. /// See the methods of this type under the documentation of [`ParseBuffer`]. For
  217. /// an overview of parsing in Syn, refer to the [module documentation].
  218. ///
  219. /// [module documentation]: self
  220. pub type ParseStream<'a> = &'a ParseBuffer<'a>;
  221. /// Cursor position within a buffered token stream.
  222. ///
  223. /// This type is more commonly used through the type alias [`ParseStream`] which
  224. /// is an alias for `&ParseBuffer`.
  225. ///
  226. /// `ParseStream` is the input type for all parser functions in Syn. They have
  227. /// the signature `fn(ParseStream) -> Result<T>`.
  228. ///
  229. /// ## Calling a parser function
  230. ///
  231. /// There is no public way to construct a `ParseBuffer`. Instead, if you are
  232. /// looking to invoke a parser function that requires `ParseStream` as input,
  233. /// you will need to go through one of the public parsing entry points.
  234. ///
  235. /// - The [`parse_macro_input!`] macro if parsing input of a procedural macro;
  236. /// - One of [the `syn::parse*` functions][syn-parse]; or
  237. /// - A method of the [`Parser`] trait.
  238. ///
  239. /// [`parse_macro_input!`]: crate::parse_macro_input!
  240. /// [syn-parse]: self#the-synparse-functions
  241. pub struct ParseBuffer<'a> {
  242. scope: Span,
  243. // Instead of Cell<Cursor<'a>> so that ParseBuffer<'a> is covariant in 'a.
  244. // The rest of the code in this module needs to be careful that only a
  245. // cursor derived from this `cell` is ever assigned to this `cell`.
  246. //
  247. // Cell<Cursor<'a>> cannot be covariant in 'a because then we could take a
  248. // ParseBuffer<'a>, upcast to ParseBuffer<'short> for some lifetime shorter
  249. // than 'a, and then assign a Cursor<'short> into the Cell.
  250. //
  251. // By extension, it would not be safe to expose an API that accepts a
  252. // Cursor<'a> and trusts that it lives as long as the cursor currently in
  253. // the cell.
  254. cell: Cell<Cursor<'static>>,
  255. marker: PhantomData<Cursor<'a>>,
  256. unexpected: Cell<Option<Rc<Cell<Unexpected>>>>,
  257. }
  258. impl<'a> Drop for ParseBuffer<'a> {
  259. fn drop(&mut self) {
  260. if let Some((unexpected_span, delimiter)) = span_of_unexpected_ignoring_nones(self.cursor())
  261. {
  262. let (inner, old_span) = inner_unexpected(self);
  263. if old_span.is_none() {
  264. inner.set(Unexpected::Some(unexpected_span, delimiter));
  265. }
  266. }
  267. }
  268. }
  269. impl<'a> Display for ParseBuffer<'a> {
  270. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  271. Display::fmt(&self.cursor().token_stream(), f)
  272. }
  273. }
  274. impl<'a> Debug for ParseBuffer<'a> {
  275. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  276. Debug::fmt(&self.cursor().token_stream(), f)
  277. }
  278. }
  279. impl<'a> UnwindSafe for ParseBuffer<'a> {}
  280. impl<'a> RefUnwindSafe for ParseBuffer<'a> {}
  281. /// Cursor state associated with speculative parsing.
  282. ///
  283. /// This type is the input of the closure provided to [`ParseStream::step`].
  284. ///
  285. /// [`ParseStream::step`]: ParseBuffer::step
  286. ///
  287. /// # Example
  288. ///
  289. /// ```
  290. /// use proc_macro2::TokenTree;
  291. /// use syn::Result;
  292. /// use syn::parse::ParseStream;
  293. ///
  294. /// // This function advances the stream past the next occurrence of `@`. If
  295. /// // no `@` is present in the stream, the stream position is unchanged and
  296. /// // an error is returned.
  297. /// fn skip_past_next_at(input: ParseStream) -> Result<()> {
  298. /// input.step(|cursor| {
  299. /// let mut rest = *cursor;
  300. /// while let Some((tt, next)) = rest.token_tree() {
  301. /// match &tt {
  302. /// TokenTree::Punct(punct) if punct.as_char() == '@' => {
  303. /// return Ok(((), next));
  304. /// }
  305. /// _ => rest = next,
  306. /// }
  307. /// }
  308. /// Err(cursor.error("no `@` was found after this point"))
  309. /// })
  310. /// }
  311. /// #
  312. /// # fn remainder_after_skipping_past_next_at(
  313. /// # input: ParseStream,
  314. /// # ) -> Result<proc_macro2::TokenStream> {
  315. /// # skip_past_next_at(input)?;
  316. /// # input.parse()
  317. /// # }
  318. /// #
  319. /// # use syn::parse::Parser;
  320. /// # let remainder = remainder_after_skipping_past_next_at
  321. /// # .parse_str("a @ b c")
  322. /// # .unwrap();
  323. /// # assert_eq!(remainder.to_string(), "b c");
  324. /// ```
  325. pub struct StepCursor<'c, 'a> {
  326. scope: Span,
  327. // This field is covariant in 'c.
  328. cursor: Cursor<'c>,
  329. // This field is contravariant in 'c. Together these make StepCursor
  330. // invariant in 'c. Also covariant in 'a. The user cannot cast 'c to a
  331. // different lifetime but can upcast into a StepCursor with a shorter
  332. // lifetime 'a.
  333. //
  334. // As long as we only ever construct a StepCursor for which 'c outlives 'a,
  335. // this means if ever a StepCursor<'c, 'a> exists we are guaranteed that 'c
  336. // outlives 'a.
  337. marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
  338. }
  339. impl<'c, 'a> Deref for StepCursor<'c, 'a> {
  340. type Target = Cursor<'c>;
  341. fn deref(&self) -> &Self::Target {
  342. &self.cursor
  343. }
  344. }
  345. impl<'c, 'a> Copy for StepCursor<'c, 'a> {}
  346. impl<'c, 'a> Clone for StepCursor<'c, 'a> {
  347. fn clone(&self) -> Self {
  348. *self
  349. }
  350. }
  351. impl<'c, 'a> StepCursor<'c, 'a> {
  352. /// Triggers an error at the current position of the parse stream.
  353. ///
  354. /// The `ParseStream::step` invocation will return this same error without
  355. /// advancing the stream state.
  356. pub fn error<T: Display>(self, message: T) -> Error {
  357. error::new_at(self.scope, self.cursor, message)
  358. }
  359. }
  360. pub(crate) fn advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a> {
  361. // Refer to the comments within the StepCursor definition. We use the
  362. // fact that a StepCursor<'c, 'a> exists as proof that 'c outlives 'a.
  363. // Cursor is covariant in its lifetime parameter so we can cast a
  364. // Cursor<'c> to one with the shorter lifetime Cursor<'a>.
  365. let _ = proof;
  366. unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) }
  367. }
  368. pub(crate) fn new_parse_buffer(
  369. scope: Span,
  370. cursor: Cursor,
  371. unexpected: Rc<Cell<Unexpected>>,
  372. ) -> ParseBuffer {
  373. ParseBuffer {
  374. scope,
  375. // See comment on `cell` in the struct definition.
  376. cell: Cell::new(unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) }),
  377. marker: PhantomData,
  378. unexpected: Cell::new(Some(unexpected)),
  379. }
  380. }
  381. pub(crate) enum Unexpected {
  382. None,
  383. Some(Span, Delimiter),
  384. Chain(Rc<Cell<Unexpected>>),
  385. }
  386. impl Default for Unexpected {
  387. fn default() -> Self {
  388. Unexpected::None
  389. }
  390. }
  391. impl Clone for Unexpected {
  392. fn clone(&self) -> Self {
  393. match self {
  394. Unexpected::None => Unexpected::None,
  395. Unexpected::Some(span, delimiter) => Unexpected::Some(*span, *delimiter),
  396. Unexpected::Chain(next) => Unexpected::Chain(next.clone()),
  397. }
  398. }
  399. }
  400. // We call this on Cell<Unexpected> and Cell<Option<T>> where temporarily
  401. // swapping in a None is cheap.
  402. fn cell_clone<T: Default + Clone>(cell: &Cell<T>) -> T {
  403. let prev = cell.take();
  404. let ret = prev.clone();
  405. cell.set(prev);
  406. ret
  407. }
  408. fn inner_unexpected(buffer: &ParseBuffer) -> (Rc<Cell<Unexpected>>, Option<(Span, Delimiter)>) {
  409. let mut unexpected = get_unexpected(buffer);
  410. loop {
  411. match cell_clone(&unexpected) {
  412. Unexpected::None => return (unexpected, None),
  413. Unexpected::Some(span, delimiter) => return (unexpected, Some((span, delimiter))),
  414. Unexpected::Chain(next) => unexpected = next,
  415. }
  416. }
  417. }
  418. pub(crate) fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Unexpected>> {
  419. cell_clone(&buffer.unexpected).unwrap()
  420. }
  421. fn span_of_unexpected_ignoring_nones(mut cursor: Cursor) -> Option<(Span, Delimiter)> {
  422. if cursor.eof() {
  423. return None;
  424. }
  425. while let Some((inner, _span, rest)) = cursor.group(Delimiter::None) {
  426. if let Some(unexpected) = span_of_unexpected_ignoring_nones(inner) {
  427. return Some(unexpected);
  428. }
  429. cursor = rest;
  430. }
  431. if cursor.eof() {
  432. None
  433. } else {
  434. Some((cursor.span(), cursor.scope_delimiter()))
  435. }
  436. }
  437. impl<'a> ParseBuffer<'a> {
  438. /// Parses a syntax tree node of type `T`, advancing the position of our
  439. /// parse stream past it.
  440. pub fn parse<T: Parse>(&self) -> Result<T> {
  441. T::parse(self)
  442. }
  443. /// Calls the given parser function to parse a syntax tree node of type `T`
  444. /// from this stream.
  445. ///
  446. /// # Example
  447. ///
  448. /// The parser below invokes [`Attribute::parse_outer`] to parse a vector of
  449. /// zero or more outer attributes.
  450. ///
  451. /// [`Attribute::parse_outer`]: crate::Attribute::parse_outer
  452. ///
  453. /// ```
  454. /// use syn::{Attribute, Ident, Result, Token};
  455. /// use syn::parse::{Parse, ParseStream};
  456. ///
  457. /// // Parses a unit struct with attributes.
  458. /// //
  459. /// // #[path = "s.tmpl"]
  460. /// // struct S;
  461. /// struct UnitStruct {
  462. /// attrs: Vec<Attribute>,
  463. /// struct_token: Token![struct],
  464. /// name: Ident,
  465. /// semi_token: Token![;],
  466. /// }
  467. ///
  468. /// impl Parse for UnitStruct {
  469. /// fn parse(input: ParseStream) -> Result<Self> {
  470. /// Ok(UnitStruct {
  471. /// attrs: input.call(Attribute::parse_outer)?,
  472. /// struct_token: input.parse()?,
  473. /// name: input.parse()?,
  474. /// semi_token: input.parse()?,
  475. /// })
  476. /// }
  477. /// }
  478. /// ```
  479. pub fn call<T>(&'a self, function: fn(ParseStream<'a>) -> Result<T>) -> Result<T> {
  480. function(self)
  481. }
  482. /// Looks at the next token in the parse stream to determine whether it
  483. /// matches the requested type of token.
  484. ///
  485. /// Does not advance the position of the parse stream.
  486. ///
  487. /// # Syntax
  488. ///
  489. /// Note that this method does not use turbofish syntax. Pass the peek type
  490. /// inside of parentheses.
  491. ///
  492. /// - `input.peek(Token![struct])`
  493. /// - `input.peek(Token![==])`
  494. /// - `input.peek(syn::Ident)`&emsp;*(does not accept keywords)*
  495. /// - `input.peek(syn::Ident::peek_any)`
  496. /// - `input.peek(Lifetime)`
  497. /// - `input.peek(token::Brace)`
  498. ///
  499. /// # Example
  500. ///
  501. /// In this example we finish parsing the list of supertraits when the next
  502. /// token in the input is either `where` or an opening curly brace.
  503. ///
  504. /// ```
  505. /// use syn::{braced, token, Generics, Ident, Result, Token, TypeParamBound};
  506. /// use syn::parse::{Parse, ParseStream};
  507. /// use syn::punctuated::Punctuated;
  508. ///
  509. /// // Parses a trait definition containing no associated items.
  510. /// //
  511. /// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
  512. /// struct MarkerTrait {
  513. /// trait_token: Token![trait],
  514. /// ident: Ident,
  515. /// generics: Generics,
  516. /// colon_token: Option<Token![:]>,
  517. /// supertraits: Punctuated<TypeParamBound, Token![+]>,
  518. /// brace_token: token::Brace,
  519. /// }
  520. ///
  521. /// impl Parse for MarkerTrait {
  522. /// fn parse(input: ParseStream) -> Result<Self> {
  523. /// let trait_token: Token![trait] = input.parse()?;
  524. /// let ident: Ident = input.parse()?;
  525. /// let mut generics: Generics = input.parse()?;
  526. /// let colon_token: Option<Token![:]> = input.parse()?;
  527. ///
  528. /// let mut supertraits = Punctuated::new();
  529. /// if colon_token.is_some() {
  530. /// loop {
  531. /// supertraits.push_value(input.parse()?);
  532. /// if input.peek(Token![where]) || input.peek(token::Brace) {
  533. /// break;
  534. /// }
  535. /// supertraits.push_punct(input.parse()?);
  536. /// }
  537. /// }
  538. ///
  539. /// generics.where_clause = input.parse()?;
  540. /// let content;
  541. /// let empty_brace_token = braced!(content in input);
  542. ///
  543. /// Ok(MarkerTrait {
  544. /// trait_token,
  545. /// ident,
  546. /// generics,
  547. /// colon_token,
  548. /// supertraits,
  549. /// brace_token: empty_brace_token,
  550. /// })
  551. /// }
  552. /// }
  553. /// ```
  554. pub fn peek<T: Peek>(&self, token: T) -> bool {
  555. let _ = token;
  556. T::Token::peek(self.cursor())
  557. }
  558. /// Looks at the second-next token in the parse stream.
  559. ///
  560. /// This is commonly useful as a way to implement contextual keywords.
  561. ///
  562. /// # Example
  563. ///
  564. /// This example needs to use `peek2` because the symbol `union` is not a
  565. /// keyword in Rust. We can't use just `peek` and decide to parse a union if
  566. /// the very next token is `union`, because someone is free to write a `mod
  567. /// union` and a macro invocation that looks like `union::some_macro! { ...
  568. /// }`. In other words `union` is a contextual keyword.
  569. ///
  570. /// ```
  571. /// use syn::{Ident, ItemUnion, Macro, Result, Token};
  572. /// use syn::parse::{Parse, ParseStream};
  573. ///
  574. /// // Parses either a union or a macro invocation.
  575. /// enum UnionOrMacro {
  576. /// // union MaybeUninit<T> { uninit: (), value: T }
  577. /// Union(ItemUnion),
  578. /// // lazy_static! { ... }
  579. /// Macro(Macro),
  580. /// }
  581. ///
  582. /// impl Parse for UnionOrMacro {
  583. /// fn parse(input: ParseStream) -> Result<Self> {
  584. /// if input.peek(Token![union]) && input.peek2(Ident) {
  585. /// input.parse().map(UnionOrMacro::Union)
  586. /// } else {
  587. /// input.parse().map(UnionOrMacro::Macro)
  588. /// }
  589. /// }
  590. /// }
  591. /// ```
  592. pub fn peek2<T: Peek>(&self, token: T) -> bool {
  593. fn peek2(buffer: &ParseBuffer, peek: fn(Cursor) -> bool) -> bool {
  594. buffer.cursor().skip().map_or(false, peek)
  595. }
  596. let _ = token;
  597. peek2(self, T::Token::peek)
  598. }
  599. /// Looks at the third-next token in the parse stream.
  600. pub fn peek3<T: Peek>(&self, token: T) -> bool {
  601. fn peek3(buffer: &ParseBuffer, peek: fn(Cursor) -> bool) -> bool {
  602. buffer
  603. .cursor()
  604. .skip()
  605. .and_then(Cursor::skip)
  606. .map_or(false, peek)
  607. }
  608. let _ = token;
  609. peek3(self, T::Token::peek)
  610. }
  611. /// Parses zero or more occurrences of `T` separated by punctuation of type
  612. /// `P`, with optional trailing punctuation.
  613. ///
  614. /// Parsing continues until the end of this parse stream. The entire content
  615. /// of this parse stream must consist of `T` and `P`.
  616. ///
  617. /// # Example
  618. ///
  619. /// ```
  620. /// # use quote::quote;
  621. /// #
  622. /// use syn::{parenthesized, token, Ident, Result, Token, Type};
  623. /// use syn::parse::{Parse, ParseStream};
  624. /// use syn::punctuated::Punctuated;
  625. ///
  626. /// // Parse a simplified tuple struct syntax like:
  627. /// //
  628. /// // struct S(A, B);
  629. /// struct TupleStruct {
  630. /// struct_token: Token![struct],
  631. /// ident: Ident,
  632. /// paren_token: token::Paren,
  633. /// fields: Punctuated<Type, Token![,]>,
  634. /// semi_token: Token![;],
  635. /// }
  636. ///
  637. /// impl Parse for TupleStruct {
  638. /// fn parse(input: ParseStream) -> Result<Self> {
  639. /// let content;
  640. /// Ok(TupleStruct {
  641. /// struct_token: input.parse()?,
  642. /// ident: input.parse()?,
  643. /// paren_token: parenthesized!(content in input),
  644. /// fields: content.parse_terminated(Type::parse, Token![,])?,
  645. /// semi_token: input.parse()?,
  646. /// })
  647. /// }
  648. /// }
  649. /// #
  650. /// # let input = quote! {
  651. /// # struct S(A, B);
  652. /// # };
  653. /// # syn::parse2::<TupleStruct>(input).unwrap();
  654. /// ```
  655. ///
  656. /// # See also
  657. ///
  658. /// If your separator is anything more complicated than an invocation of the
  659. /// `Token!` macro, this method won't be applicable and you can instead
  660. /// directly use `Punctuated`'s parser functions: [`parse_terminated`],
  661. /// [`parse_separated_nonempty`] etc.
  662. ///
  663. /// [`parse_terminated`]: Punctuated::parse_terminated
  664. /// [`parse_separated_nonempty`]: Punctuated::parse_separated_nonempty
  665. ///
  666. /// ```
  667. /// use syn::{custom_keyword, Expr, Result, Token};
  668. /// use syn::parse::{Parse, ParseStream};
  669. /// use syn::punctuated::Punctuated;
  670. ///
  671. /// mod kw {
  672. /// syn::custom_keyword!(fin);
  673. /// }
  674. ///
  675. /// struct Fin(kw::fin, Token![;]);
  676. ///
  677. /// impl Parse for Fin {
  678. /// fn parse(input: ParseStream) -> Result<Self> {
  679. /// Ok(Self(input.parse()?, input.parse()?))
  680. /// }
  681. /// }
  682. ///
  683. /// struct Thing {
  684. /// steps: Punctuated<Expr, Fin>,
  685. /// }
  686. ///
  687. /// impl Parse for Thing {
  688. /// fn parse(input: ParseStream) -> Result<Self> {
  689. /// # if true {
  690. /// Ok(Thing {
  691. /// steps: Punctuated::parse_terminated(input)?,
  692. /// })
  693. /// # } else {
  694. /// // or equivalently, this means the same thing:
  695. /// # Ok(Thing {
  696. /// steps: input.call(Punctuated::parse_terminated)?,
  697. /// # })
  698. /// # }
  699. /// }
  700. /// }
  701. /// ```
  702. pub fn parse_terminated<T, P>(
  703. &'a self,
  704. parser: fn(ParseStream<'a>) -> Result<T>,
  705. separator: P,
  706. ) -> Result<Punctuated<T, P::Token>>
  707. where
  708. P: Peek,
  709. P::Token: Parse,
  710. {
  711. let _ = separator;
  712. Punctuated::parse_terminated_with(self, parser)
  713. }
  714. /// Returns whether there are no more tokens remaining to be parsed from
  715. /// this stream.
  716. ///
  717. /// This method returns true upon reaching the end of the content within a
  718. /// set of delimiters, as well as at the end of the tokens provided to the
  719. /// outermost parsing entry point.
  720. ///
  721. /// This is equivalent to
  722. /// <code>.<a href="#method.peek">peek</a>(<a href="struct.End.html">syn::parse::End</a>)</code>.
  723. /// Use `.peek2(End)` or `.peek3(End)` to look for the end of a parse stream
  724. /// further ahead than the current position.
  725. ///
  726. /// # Example
  727. ///
  728. /// ```
  729. /// use syn::{braced, token, Ident, Item, Result, Token};
  730. /// use syn::parse::{Parse, ParseStream};
  731. ///
  732. /// // Parses a Rust `mod m { ... }` containing zero or more items.
  733. /// struct Mod {
  734. /// mod_token: Token![mod],
  735. /// name: Ident,
  736. /// brace_token: token::Brace,
  737. /// items: Vec<Item>,
  738. /// }
  739. ///
  740. /// impl Parse for Mod {
  741. /// fn parse(input: ParseStream) -> Result<Self> {
  742. /// let content;
  743. /// Ok(Mod {
  744. /// mod_token: input.parse()?,
  745. /// name: input.parse()?,
  746. /// brace_token: braced!(content in input),
  747. /// items: {
  748. /// let mut items = Vec::new();
  749. /// while !content.is_empty() {
  750. /// items.push(content.parse()?);
  751. /// }
  752. /// items
  753. /// },
  754. /// })
  755. /// }
  756. /// }
  757. /// ```
  758. pub fn is_empty(&self) -> bool {
  759. self.cursor().eof()
  760. }
  761. /// Constructs a helper for peeking at the next token in this stream and
  762. /// building an error message if it is not one of a set of expected tokens.
  763. ///
  764. /// # Example
  765. ///
  766. /// ```
  767. /// use syn::{ConstParam, Ident, Lifetime, LifetimeParam, Result, Token, TypeParam};
  768. /// use syn::parse::{Parse, ParseStream};
  769. ///
  770. /// // A generic parameter, a single one of the comma-separated elements inside
  771. /// // angle brackets in:
  772. /// //
  773. /// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
  774. /// //
  775. /// // On invalid input, lookahead gives us a reasonable error message.
  776. /// //
  777. /// // error: expected one of: identifier, lifetime, `const`
  778. /// // |
  779. /// // 5 | fn f<!Sized>() {}
  780. /// // | ^
  781. /// enum GenericParam {
  782. /// Type(TypeParam),
  783. /// Lifetime(LifetimeParam),
  784. /// Const(ConstParam),
  785. /// }
  786. ///
  787. /// impl Parse for GenericParam {
  788. /// fn parse(input: ParseStream) -> Result<Self> {
  789. /// let lookahead = input.lookahead1();
  790. /// if lookahead.peek(Ident) {
  791. /// input.parse().map(GenericParam::Type)
  792. /// } else if lookahead.peek(Lifetime) {
  793. /// input.parse().map(GenericParam::Lifetime)
  794. /// } else if lookahead.peek(Token![const]) {
  795. /// input.parse().map(GenericParam::Const)
  796. /// } else {
  797. /// Err(lookahead.error())
  798. /// }
  799. /// }
  800. /// }
  801. /// ```
  802. pub fn lookahead1(&self) -> Lookahead1<'a> {
  803. lookahead::new(self.scope, self.cursor())
  804. }
  805. /// Forks a parse stream so that parsing tokens out of either the original
  806. /// or the fork does not advance the position of the other.
  807. ///
  808. /// # Performance
  809. ///
  810. /// Forking a parse stream is a cheap fixed amount of work and does not
  811. /// involve copying token buffers. Where you might hit performance problems
  812. /// is if your macro ends up parsing a large amount of content more than
  813. /// once.
  814. ///
  815. /// ```
  816. /// # use syn::{Expr, Result};
  817. /// # use syn::parse::ParseStream;
  818. /// #
  819. /// # fn bad(input: ParseStream) -> Result<Expr> {
  820. /// // Do not do this.
  821. /// if input.fork().parse::<Expr>().is_ok() {
  822. /// return input.parse::<Expr>();
  823. /// }
  824. /// # unimplemented!()
  825. /// # }
  826. /// ```
  827. ///
  828. /// As a rule, avoid parsing an unbounded amount of tokens out of a forked
  829. /// parse stream. Only use a fork when the amount of work performed against
  830. /// the fork is small and bounded.
  831. ///
  832. /// When complex speculative parsing against the forked stream is
  833. /// unavoidable, use [`parse::discouraged::Speculative`] to advance the
  834. /// original stream once the fork's parse is determined to have been
  835. /// successful.
  836. ///
  837. /// For a lower level way to perform speculative parsing at the token level,
  838. /// consider using [`ParseStream::step`] instead.
  839. ///
  840. /// [`parse::discouraged::Speculative`]: discouraged::Speculative
  841. /// [`ParseStream::step`]: ParseBuffer::step
  842. ///
  843. /// # Example
  844. ///
  845. /// The parse implementation shown here parses possibly restricted `pub`
  846. /// visibilities.
  847. ///
  848. /// - `pub`
  849. /// - `pub(crate)`
  850. /// - `pub(self)`
  851. /// - `pub(super)`
  852. /// - `pub(in some::path)`
  853. ///
  854. /// To handle the case of visibilities inside of tuple structs, the parser
  855. /// needs to distinguish parentheses that specify visibility restrictions
  856. /// from parentheses that form part of a tuple type.
  857. ///
  858. /// ```
  859. /// # struct A;
  860. /// # struct B;
  861. /// # struct C;
  862. /// #
  863. /// struct S(pub(crate) A, pub (B, C));
  864. /// ```
  865. ///
  866. /// In this example input the first tuple struct element of `S` has
  867. /// `pub(crate)` visibility while the second tuple struct element has `pub`
  868. /// visibility; the parentheses around `(B, C)` are part of the type rather
  869. /// than part of a visibility restriction.
  870. ///
  871. /// The parser uses a forked parse stream to check the first token inside of
  872. /// parentheses after the `pub` keyword. This is a small bounded amount of
  873. /// work performed against the forked parse stream.
  874. ///
  875. /// ```
  876. /// use syn::{parenthesized, token, Ident, Path, Result, Token};
  877. /// use syn::ext::IdentExt;
  878. /// use syn::parse::{Parse, ParseStream};
  879. ///
  880. /// struct PubVisibility {
  881. /// pub_token: Token![pub],
  882. /// restricted: Option<Restricted>,
  883. /// }
  884. ///
  885. /// struct Restricted {
  886. /// paren_token: token::Paren,
  887. /// in_token: Option<Token![in]>,
  888. /// path: Path,
  889. /// }
  890. ///
  891. /// impl Parse for PubVisibility {
  892. /// fn parse(input: ParseStream) -> Result<Self> {
  893. /// let pub_token: Token![pub] = input.parse()?;
  894. ///
  895. /// if input.peek(token::Paren) {
  896. /// let ahead = input.fork();
  897. /// let mut content;
  898. /// parenthesized!(content in ahead);
  899. ///
  900. /// if content.peek(Token![crate])
  901. /// || content.peek(Token![self])
  902. /// || content.peek(Token![super])
  903. /// {
  904. /// return Ok(PubVisibility {
  905. /// pub_token,
  906. /// restricted: Some(Restricted {
  907. /// paren_token: parenthesized!(content in input),
  908. /// in_token: None,
  909. /// path: Path::from(content.call(Ident::parse_any)?),
  910. /// }),
  911. /// });
  912. /// } else if content.peek(Token![in]) {
  913. /// return Ok(PubVisibility {
  914. /// pub_token,
  915. /// restricted: Some(Restricted {
  916. /// paren_token: parenthesized!(content in input),
  917. /// in_token: Some(content.parse()?),
  918. /// path: content.call(Path::parse_mod_style)?,
  919. /// }),
  920. /// });
  921. /// }
  922. /// }
  923. ///
  924. /// Ok(PubVisibility {
  925. /// pub_token,
  926. /// restricted: None,
  927. /// })
  928. /// }
  929. /// }
  930. /// ```
  931. pub fn fork(&self) -> Self {
  932. ParseBuffer {
  933. scope: self.scope,
  934. cell: self.cell.clone(),
  935. marker: PhantomData,
  936. // Not the parent's unexpected. Nothing cares whether the clone
  937. // parses all the way unless we `advance_to`.
  938. unexpected: Cell::new(Some(Rc::new(Cell::new(Unexpected::None)))),
  939. }
  940. }
  941. /// Triggers an error at the current position of the parse stream.
  942. ///
  943. /// # Example
  944. ///
  945. /// ```
  946. /// use syn::{Expr, Result, Token};
  947. /// use syn::parse::{Parse, ParseStream};
  948. ///
  949. /// // Some kind of loop: `while` or `for` or `loop`.
  950. /// struct Loop {
  951. /// expr: Expr,
  952. /// }
  953. ///
  954. /// impl Parse for Loop {
  955. /// fn parse(input: ParseStream) -> Result<Self> {
  956. /// if input.peek(Token![while])
  957. /// || input.peek(Token![for])
  958. /// || input.peek(Token![loop])
  959. /// {
  960. /// Ok(Loop {
  961. /// expr: input.parse()?,
  962. /// })
  963. /// } else {
  964. /// Err(input.error("expected some kind of loop"))
  965. /// }
  966. /// }
  967. /// }
  968. /// ```
  969. pub fn error<T: Display>(&self, message: T) -> Error {
  970. error::new_at(self.scope, self.cursor(), message)
  971. }
  972. /// Speculatively parses tokens from this parse stream, advancing the
  973. /// position of this stream only if parsing succeeds.
  974. ///
  975. /// This is a powerful low-level API used for defining the `Parse` impls of
  976. /// the basic built-in token types. It is not something that will be used
  977. /// widely outside of the Syn codebase.
  978. ///
  979. /// # Example
  980. ///
  981. /// ```
  982. /// use proc_macro2::TokenTree;
  983. /// use syn::Result;
  984. /// use syn::parse::ParseStream;
  985. ///
  986. /// // This function advances the stream past the next occurrence of `@`. If
  987. /// // no `@` is present in the stream, the stream position is unchanged and
  988. /// // an error is returned.
  989. /// fn skip_past_next_at(input: ParseStream) -> Result<()> {
  990. /// input.step(|cursor| {
  991. /// let mut rest = *cursor;
  992. /// while let Some((tt, next)) = rest.token_tree() {
  993. /// match &tt {
  994. /// TokenTree::Punct(punct) if punct.as_char() == '@' => {
  995. /// return Ok(((), next));
  996. /// }
  997. /// _ => rest = next,
  998. /// }
  999. /// }
  1000. /// Err(cursor.error("no `@` was found after this point"))
  1001. /// })
  1002. /// }
  1003. /// #
  1004. /// # fn remainder_after_skipping_past_next_at(
  1005. /// # input: ParseStream,
  1006. /// # ) -> Result<proc_macro2::TokenStream> {
  1007. /// # skip_past_next_at(input)?;
  1008. /// # input.parse()
  1009. /// # }
  1010. /// #
  1011. /// # use syn::parse::Parser;
  1012. /// # let remainder = remainder_after_skipping_past_next_at
  1013. /// # .parse_str("a @ b c")
  1014. /// # .unwrap();
  1015. /// # assert_eq!(remainder.to_string(), "b c");
  1016. /// ```
  1017. pub fn step<F, R>(&self, function: F) -> Result<R>
  1018. where
  1019. F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
  1020. {
  1021. // Since the user's function is required to work for any 'c, we know
  1022. // that the Cursor<'c> they return is either derived from the input
  1023. // StepCursor<'c, 'a> or from a Cursor<'static>.
  1024. //
  1025. // It would not be legal to write this function without the invariant
  1026. // lifetime 'c in StepCursor<'c, 'a>. If this function were written only
  1027. // in terms of 'a, the user could take our ParseBuffer<'a>, upcast it to
  1028. // a ParseBuffer<'short> which some shorter lifetime than 'a, invoke
  1029. // `step` on their ParseBuffer<'short> with a closure that returns
  1030. // Cursor<'short>, and we would wrongly write that Cursor<'short> into
  1031. // the Cell intended to hold Cursor<'a>.
  1032. //
  1033. // In some cases it may be necessary for R to contain a Cursor<'a>.
  1034. // Within Syn we solve this using `advance_step_cursor` which uses the
  1035. // existence of a StepCursor<'c, 'a> as proof that it is safe to cast
  1036. // from Cursor<'c> to Cursor<'a>. If needed outside of Syn, it would be
  1037. // safe to expose that API as a method on StepCursor.
  1038. let (node, rest) = function(StepCursor {
  1039. scope: self.scope,
  1040. cursor: self.cell.get(),
  1041. marker: PhantomData,
  1042. })?;
  1043. self.cell.set(rest);
  1044. Ok(node)
  1045. }
  1046. /// Returns the `Span` of the next token in the parse stream, or
  1047. /// `Span::call_site()` if this parse stream has completely exhausted its
  1048. /// input `TokenStream`.
  1049. pub fn span(&self) -> Span {
  1050. let cursor = self.cursor();
  1051. if cursor.eof() {
  1052. self.scope
  1053. } else {
  1054. crate::buffer::open_span_of_group(cursor)
  1055. }
  1056. }
  1057. /// Provides low-level access to the token representation underlying this
  1058. /// parse stream.
  1059. ///
  1060. /// Cursors are immutable so no operations you perform against the cursor
  1061. /// will affect the state of this parse stream.
  1062. ///
  1063. /// # Example
  1064. ///
  1065. /// ```
  1066. /// use proc_macro2::TokenStream;
  1067. /// use syn::buffer::Cursor;
  1068. /// use syn::parse::{ParseStream, Result};
  1069. ///
  1070. /// // Run a parser that returns T, but get its output as TokenStream instead of T.
  1071. /// // This works without T needing to implement ToTokens.
  1072. /// fn recognize_token_stream<T>(
  1073. /// recognizer: fn(ParseStream) -> Result<T>,
  1074. /// ) -> impl Fn(ParseStream) -> Result<TokenStream> {
  1075. /// move |input| {
  1076. /// let begin = input.cursor();
  1077. /// recognizer(input)?;
  1078. /// let end = input.cursor();
  1079. /// Ok(tokens_between(begin, end))
  1080. /// }
  1081. /// }
  1082. ///
  1083. /// // Collect tokens between two cursors as a TokenStream.
  1084. /// fn tokens_between(begin: Cursor, end: Cursor) -> TokenStream {
  1085. /// assert!(begin <= end);
  1086. ///
  1087. /// let mut cursor = begin;
  1088. /// let mut tokens = TokenStream::new();
  1089. /// while cursor < end {
  1090. /// let (token, next) = cursor.token_tree().unwrap();
  1091. /// tokens.extend(std::iter::once(token));
  1092. /// cursor = next;
  1093. /// }
  1094. /// tokens
  1095. /// }
  1096. ///
  1097. /// fn main() {
  1098. /// use quote::quote;
  1099. /// use syn::parse::{Parse, Parser};
  1100. /// use syn::Token;
  1101. ///
  1102. /// // Parse syn::Type as a TokenStream, surrounded by angle brackets.
  1103. /// fn example(input: ParseStream) -> Result<TokenStream> {
  1104. /// let _langle: Token![<] = input.parse()?;
  1105. /// let ty = recognize_token_stream(syn::Type::parse)(input)?;
  1106. /// let _rangle: Token![>] = input.parse()?;
  1107. /// Ok(ty)
  1108. /// }
  1109. ///
  1110. /// let tokens = quote! { <fn() -> u8> };
  1111. /// println!("{}", example.parse2(tokens).unwrap());
  1112. /// }
  1113. /// ```
  1114. pub fn cursor(&self) -> Cursor<'a> {
  1115. self.cell.get()
  1116. }
  1117. fn check_unexpected(&self) -> Result<()> {
  1118. match inner_unexpected(self).1 {
  1119. Some((span, delimiter)) => Err(err_unexpected_token(span, delimiter)),
  1120. None => Ok(()),
  1121. }
  1122. }
  1123. }
  1124. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  1125. impl<T: Parse> Parse for Box<T> {
  1126. fn parse(input: ParseStream) -> Result<Self> {
  1127. input.parse().map(Box::new)
  1128. }
  1129. }
  1130. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  1131. impl<T: Parse + Token> Parse for Option<T> {
  1132. fn parse(input: ParseStream) -> Result<Self> {
  1133. if T::peek(input.cursor()) {
  1134. Ok(Some(input.parse()?))
  1135. } else {
  1136. Ok(None)
  1137. }
  1138. }
  1139. }
  1140. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  1141. impl Parse for TokenStream {
  1142. fn parse(input: ParseStream) -> Result<Self> {
  1143. input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty())))
  1144. }
  1145. }
  1146. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  1147. impl Parse for TokenTree {
  1148. fn parse(input: ParseStream) -> Result<Self> {
  1149. input.step(|cursor| match cursor.token_tree() {
  1150. Some((tt, rest)) => Ok((tt, rest)),
  1151. None => Err(cursor.error("expected token tree")),
  1152. })
  1153. }
  1154. }
  1155. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  1156. impl Parse for Group {
  1157. fn parse(input: ParseStream) -> Result<Self> {
  1158. input.step(|cursor| {
  1159. if let Some((group, rest)) = cursor.any_group_token() {
  1160. if group.delimiter() != Delimiter::None {
  1161. return Ok((group, rest));
  1162. }
  1163. }
  1164. Err(cursor.error("expected group token"))
  1165. })
  1166. }
  1167. }
  1168. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  1169. impl Parse for Punct {
  1170. fn parse(input: ParseStream) -> Result<Self> {
  1171. input.step(|cursor| match cursor.punct() {
  1172. Some((punct, rest)) => Ok((punct, rest)),
  1173. None => Err(cursor.error("expected punctuation token")),
  1174. })
  1175. }
  1176. }
  1177. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  1178. impl Parse for Literal {
  1179. fn parse(input: ParseStream) -> Result<Self> {
  1180. input.step(|cursor| match cursor.literal() {
  1181. Some((literal, rest)) => Ok((literal, rest)),
  1182. None => Err(cursor.error("expected literal token")),
  1183. })
  1184. }
  1185. }
  1186. /// Parser that can parse Rust tokens into a particular syntax tree node.
  1187. ///
  1188. /// Refer to the [module documentation] for details about parsing in Syn.
  1189. ///
  1190. /// [module documentation]: self
  1191. pub trait Parser: Sized {
  1192. type Output;
  1193. /// Parse a proc-macro2 token stream into the chosen syntax tree node.
  1194. ///
  1195. /// This function enforces that the input is fully parsed. If there are any
  1196. /// unparsed tokens at the end of the stream, an error is returned.
  1197. fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
  1198. /// Parse tokens of source code into the chosen syntax tree node.
  1199. ///
  1200. /// This function enforces that the input is fully parsed. If there are any
  1201. /// unparsed tokens at the end of the stream, an error is returned.
  1202. #[cfg(feature = "proc-macro")]
  1203. #[cfg_attr(docsrs, doc(cfg(feature = "proc-macro")))]
  1204. fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
  1205. self.parse2(proc_macro2::TokenStream::from(tokens))
  1206. }
  1207. /// Parse a string of Rust code into the chosen syntax tree node.
  1208. ///
  1209. /// This function enforces that the input is fully parsed. If there are any
  1210. /// unparsed tokens at the end of the string, an error is returned.
  1211. ///
  1212. /// # Hygiene
  1213. ///
  1214. /// Every span in the resulting syntax tree will be set to resolve at the
  1215. /// macro call site.
  1216. fn parse_str(self, s: &str) -> Result<Self::Output> {
  1217. self.parse2(proc_macro2::TokenStream::from_str(s)?)
  1218. }
  1219. // Not public API.
  1220. #[doc(hidden)]
  1221. fn __parse_scoped(self, scope: Span, tokens: TokenStream) -> Result<Self::Output> {
  1222. let _ = scope;
  1223. self.parse2(tokens)
  1224. }
  1225. }
  1226. fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer {
  1227. let scope = Span::call_site();
  1228. let cursor = tokens.begin();
  1229. let unexpected = Rc::new(Cell::new(Unexpected::None));
  1230. new_parse_buffer(scope, cursor, unexpected)
  1231. }
  1232. impl<F, T> Parser for F
  1233. where
  1234. F: FnOnce(ParseStream) -> Result<T>,
  1235. {
  1236. type Output = T;
  1237. fn parse2(self, tokens: TokenStream) -> Result<T> {
  1238. let buf = TokenBuffer::new2(tokens);
  1239. let state = tokens_to_parse_buffer(&buf);
  1240. let node = self(&state)?;
  1241. state.check_unexpected()?;
  1242. if let Some((unexpected_span, delimiter)) =
  1243. span_of_unexpected_ignoring_nones(state.cursor())
  1244. {
  1245. Err(err_unexpected_token(unexpected_span, delimiter))
  1246. } else {
  1247. Ok(node)
  1248. }
  1249. }
  1250. fn __parse_scoped(self, scope: Span, tokens: TokenStream) -> Result<Self::Output> {
  1251. let buf = TokenBuffer::new2(tokens);
  1252. let cursor = buf.begin();
  1253. let unexpected = Rc::new(Cell::new(Unexpected::None));
  1254. let state = new_parse_buffer(scope, cursor, unexpected);
  1255. let node = self(&state)?;
  1256. state.check_unexpected()?;
  1257. if let Some((unexpected_span, delimiter)) =
  1258. span_of_unexpected_ignoring_nones(state.cursor())
  1259. {
  1260. Err(err_unexpected_token(unexpected_span, delimiter))
  1261. } else {
  1262. Ok(node)
  1263. }
  1264. }
  1265. }
  1266. pub(crate) fn parse_scoped<F: Parser>(f: F, scope: Span, tokens: TokenStream) -> Result<F::Output> {
  1267. f.__parse_scoped(scope, tokens)
  1268. }
  1269. fn err_unexpected_token(span: Span, delimiter: Delimiter) -> Error {
  1270. let msg = match delimiter {
  1271. Delimiter::Parenthesis => "unexpected token, expected `)`",
  1272. Delimiter::Brace => "unexpected token, expected `}`",
  1273. Delimiter::Bracket => "unexpected token, expected `]`",
  1274. Delimiter::None => "unexpected token",
  1275. };
  1276. Error::new(span, msg)
  1277. }
  1278. /// An empty syntax tree node that consumes no tokens when parsed.
  1279. ///
  1280. /// This is useful for attribute macros that want to ensure they are not
  1281. /// provided any attribute args.
  1282. ///
  1283. /// ```
  1284. /// # extern crate proc_macro;
  1285. /// #
  1286. /// use proc_macro::TokenStream;
  1287. /// use syn::parse_macro_input;
  1288. /// use syn::parse::Nothing;
  1289. ///
  1290. /// # const IGNORE: &str = stringify! {
  1291. /// #[proc_macro_attribute]
  1292. /// # };
  1293. /// pub fn my_attr(args: TokenStream, input: TokenStream) -> TokenStream {
  1294. /// parse_macro_input!(args as Nothing);
  1295. ///
  1296. /// /* ... */
  1297. /// # TokenStream::new()
  1298. /// }
  1299. /// ```
  1300. ///
  1301. /// ```text
  1302. /// error: unexpected token
  1303. /// --> src/main.rs:3:19
  1304. /// |
  1305. /// 3 | #[my_attr(asdf)]
  1306. /// | ^^^^
  1307. /// ```
  1308. pub struct Nothing;
  1309. impl Parse for Nothing {
  1310. fn parse(_input: ParseStream) -> Result<Self> {
  1311. Ok(Nothing)
  1312. }
  1313. }
  1314. #[cfg(feature = "printing")]
  1315. #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
  1316. impl ToTokens for Nothing {
  1317. fn to_tokens(&self, tokens: &mut TokenStream) {
  1318. let _ = tokens;
  1319. }
  1320. }
  1321. #[cfg(feature = "clone-impls")]
  1322. #[cfg_attr(docsrs, doc(cfg(feature = "clone-impls")))]
  1323. impl Clone for Nothing {
  1324. fn clone(&self) -> Self {
  1325. *self
  1326. }
  1327. }
  1328. #[cfg(feature = "clone-impls")]
  1329. #[cfg_attr(docsrs, doc(cfg(feature = "clone-impls")))]
  1330. impl Copy for Nothing {}
  1331. #[cfg(feature = "extra-traits")]
  1332. #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))]
  1333. impl Debug for Nothing {
  1334. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  1335. f.write_str("Nothing")
  1336. }
  1337. }
  1338. #[cfg(feature = "extra-traits")]
  1339. #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))]
  1340. impl Eq for Nothing {}
  1341. #[cfg(feature = "extra-traits")]
  1342. #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))]
  1343. impl PartialEq for Nothing {
  1344. fn eq(&self, _other: &Self) -> bool {
  1345. true
  1346. }
  1347. }
  1348. #[cfg(feature = "extra-traits")]
  1349. #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))]
  1350. impl Hash for Nothing {
  1351. fn hash<H: Hasher>(&self, _state: &mut H) {}
  1352. }