// SPDX-License-Identifier: Apache-2.0 OR MIT12#[cfg(feature = "parsing")]3use crate::buffer::Cursor;4use crate::thread::ThreadBound;5use proc_macro2::{6Delimiter, Group, Ident, LexError, Literal, Punct, Spacing, Span, TokenStream, TokenTree,7};8#[cfg(feature = "printing")]9use quote::ToTokens;10use std::fmt::{self, Debug, Display};11use std::slice;12use std::vec;1314/// The result of a Syn parser.15pub type Result<T> = std::result::Result<T, Error>;1617/// Error returned when a Syn parser cannot parse the input tokens.18///19/// # Error reporting in proc macros20///21/// The correct way to report errors back to the compiler from a procedural22/// macro is by emitting an appropriately spanned invocation of23/// [`compile_error!`] in the generated code. This produces a better diagnostic24/// message than simply panicking the macro.25///26/// [`compile_error!`]: std::compile_error!27///28/// When parsing macro input, the [`parse_macro_input!`] macro handles the29/// conversion to `compile_error!` automatically.30///31/// [`parse_macro_input!`]: crate::parse_macro_input!32///33/// ```34/// # extern crate proc_macro;35/// #36/// use proc_macro::TokenStream;37/// use syn::parse::{Parse, ParseStream, Result};38/// use syn::{parse_macro_input, ItemFn};39///40/// # const IGNORE: &str = stringify! {41/// #[proc_macro_attribute]42/// # };43/// pub fn my_attr(args: TokenStream, input: TokenStream) -> TokenStream {44/// let args = parse_macro_input!(args as MyAttrArgs);45/// let input = parse_macro_input!(input as ItemFn);46///47/// /* ... */48/// # TokenStream::new()49/// }50///51/// struct MyAttrArgs {52/// # _k: [(); { stringify! {53/// ...54/// # }; 0 }]55/// }56///57/// impl Parse for MyAttrArgs {58/// fn parse(input: ParseStream) -> Result<Self> {59/// # stringify! {60/// ...61/// # };62/// # unimplemented!()63/// }64/// }65/// ```66///67/// For errors that arise later than the initial parsing stage, the68/// [`.to_compile_error()`] or [`.into_compile_error()`] methods can be used to69/// perform an explicit conversion to `compile_error!`.70///71/// [`.to_compile_error()`]: Error::to_compile_error72/// [`.into_compile_error()`]: Error::into_compile_error73///74/// ```75/// # extern crate proc_macro;76/// #77/// # use proc_macro::TokenStream;78/// # use syn::{parse_macro_input, DeriveInput};79/// #80/// # const IGNORE: &str = stringify! {81/// #[proc_macro_derive(MyDerive)]82/// # };83/// pub fn my_derive(input: TokenStream) -> TokenStream {84/// let input = parse_macro_input!(input as DeriveInput);85///86/// // fn(DeriveInput) -> syn::Result<proc_macro2::TokenStream>87/// expand::my_derive(input)88/// .unwrap_or_else(syn::Error::into_compile_error)89/// .into()90/// }91/// #92/// # mod expand {93/// # use proc_macro2::TokenStream;94/// # use syn::{DeriveInput, Result};95/// #96/// # pub fn my_derive(input: DeriveInput) -> Result<TokenStream> {97/// # unimplemented!()98/// # }99/// # }100/// ```101pub struct Error {102messages: Vec<ErrorMessage>,103}104105struct ErrorMessage {106// Span is implemented as an index into a thread-local interner to keep the107// size small. It is not safe to access from a different thread. We want108// errors to be Send and Sync to play nicely with ecosystem crates for error109// handling, so pin the span we're given to its original thread and assume110// it is Span::call_site if accessed from any other thread.111span: ThreadBound<SpanRange>,112message: String,113}114115// Cannot use std::ops::Range<Span> because that does not implement Copy,116// whereas ThreadBound<T> requires a Copy impl as a way to ensure no Drop impls117// are involved.118struct SpanRange {119start: Span,120end: Span,121}122123#[cfg(test)]124struct _Test125where126Error: Send + Sync;127128impl Error {129/// Usually the [`ParseStream::error`] method will be used instead, which130/// automatically uses the correct span from the current position of the131/// parse stream.132///133/// Use `Error::new` when the error needs to be triggered on some span other134/// than where the parse stream is currently positioned.135///136/// [`ParseStream::error`]: crate::parse::ParseBuffer::error137///138/// # Example139///140/// ```141/// use syn::{Error, Ident, LitStr, Result, Token};142/// use syn::parse::ParseStream;143///144/// // Parses input that looks like `name = "string"` where the key must be145/// // the identifier `name` and the value may be any string literal.146/// // Returns the string literal.147/// fn parse_name(input: ParseStream) -> Result<LitStr> {148/// let name_token: Ident = input.parse()?;149/// if name_token != "name" {150/// // Trigger an error not on the current position of the stream,151/// // but on the position of the unexpected identifier.152/// return Err(Error::new(name_token.span(), "expected `name`"));153/// }154/// input.parse::<Token![=]>()?;155/// let s: LitStr = input.parse()?;156/// Ok(s)157/// }158/// ```159pub fn new<T: Display>(span: Span, message: T) -> Self {160return new(span, message.to_string());161162fn new(span: Span, message: String) -> Error {163Error {164messages: vec![ErrorMessage {165span: ThreadBound::new(SpanRange {166start: span,167end: span,168}),169message,170}],171}172}173}174175/// Creates an error with the specified message spanning the given syntax176/// tree node.177///178/// Unlike the `Error::new` constructor, this constructor takes an argument179/// `tokens` which is a syntax tree node. This allows the resulting `Error`180/// to attempt to span all tokens inside of `tokens`. While you would181/// typically be able to use the `Spanned` trait with the above `Error::new`182/// constructor, implementation limitations today mean that183/// `Error::new_spanned` may provide a higher-quality error message on184/// stable Rust.185///186/// When in doubt it's recommended to stick to `Error::new` (or187/// `ParseStream::error`)!188#[cfg(feature = "printing")]189#[cfg_attr(docsrs, doc(cfg(feature = "printing")))]190pub fn new_spanned<T: ToTokens, U: Display>(tokens: T, message: U) -> Self {191return new_spanned(tokens.into_token_stream(), message.to_string());192193fn new_spanned(tokens: TokenStream, message: String) -> Error {194let mut iter = tokens.into_iter();195let start = iter.next().map_or_else(Span::call_site, |t| t.span());196let end = iter.last().map_or(start, |t| t.span());197Error {198messages: vec![ErrorMessage {199span: ThreadBound::new(SpanRange { start, end }),200message,201}],202}203}204}205206/// The source location of the error.207///208/// Spans are not thread-safe so this function returns `Span::call_site()`209/// if called from a different thread than the one on which the `Error` was210/// originally created.211pub fn span(&self) -> Span {212let SpanRange { start, end } = match self.messages[0].span.get() {213Some(span) => *span,214None => return Span::call_site(),215};216start.join(end).unwrap_or(start)217}218219/// Render the error as an invocation of [`compile_error!`].220///221/// The [`parse_macro_input!`] macro provides a convenient way to invoke222/// this method correctly in a procedural macro.223///224/// [`compile_error!`]: std::compile_error!225/// [`parse_macro_input!`]: crate::parse_macro_input!226pub fn to_compile_error(&self) -> TokenStream {227self.messages228.iter()229.map(ErrorMessage::to_compile_error)230.collect()231}232233/// Render the error as an invocation of [`compile_error!`].234///235/// [`compile_error!`]: std::compile_error!236///237/// # Example238///239/// ```240/// # extern crate proc_macro;241/// #242/// use proc_macro::TokenStream;243/// use syn::{parse_macro_input, DeriveInput, Error};244///245/// # const _: &str = stringify! {246/// #[proc_macro_derive(MyTrait)]247/// # };248/// pub fn derive_my_trait(input: TokenStream) -> TokenStream {249/// let input = parse_macro_input!(input as DeriveInput);250/// my_trait::expand(input)251/// .unwrap_or_else(Error::into_compile_error)252/// .into()253/// }254///255/// mod my_trait {256/// use proc_macro2::TokenStream;257/// use syn::{DeriveInput, Result};258///259/// pub(crate) fn expand(input: DeriveInput) -> Result<TokenStream> {260/// /* ... */261/// # unimplemented!()262/// }263/// }264/// ```265pub fn into_compile_error(self) -> TokenStream {266self.to_compile_error()267}268269/// Add another error message to self such that when `to_compile_error()` is270/// called, both errors will be emitted together.271pub fn combine(&mut self, another: Error) {272self.messages.extend(another.messages);273}274}275276impl ErrorMessage {277fn to_compile_error(&self) -> TokenStream {278let (start, end) = match self.span.get() {279Some(range) => (range.start, range.end),280None => (Span::call_site(), Span::call_site()),281};282283// ::core::compile_error!($message)284TokenStream::from_iter([285TokenTree::Punct({286let mut punct = Punct::new(':', Spacing::Joint);287punct.set_span(start);288punct289}),290TokenTree::Punct({291let mut punct = Punct::new(':', Spacing::Alone);292punct.set_span(start);293punct294}),295TokenTree::Ident(Ident::new("core", start)),296TokenTree::Punct({297let mut punct = Punct::new(':', Spacing::Joint);298punct.set_span(start);299punct300}),301TokenTree::Punct({302let mut punct = Punct::new(':', Spacing::Alone);303punct.set_span(start);304punct305}),306TokenTree::Ident(Ident::new("compile_error", start)),307TokenTree::Punct({308let mut punct = Punct::new('!', Spacing::Alone);309punct.set_span(start);310punct311}),312TokenTree::Group({313let mut group = Group::new(Delimiter::Brace, {314TokenStream::from_iter([TokenTree::Literal({315let mut string = Literal::string(&self.message);316string.set_span(end);317string318})])319});320group.set_span(end);321group322}),323])324}325}326327#[cfg(feature = "parsing")]328pub(crate) fn new_at<T: Display>(scope: Span, cursor: Cursor, message: T) -> Error {329if cursor.eof() {330Error::new(scope, format!("unexpected end of input, {}", message))331} else {332let span = crate::buffer::open_span_of_group(cursor);333Error::new(span, message)334}335}336337#[cfg(all(feature = "parsing", any(feature = "full", feature = "derive")))]338pub(crate) fn new2<T: Display>(start: Span, end: Span, message: T) -> Error {339return new2(start, end, message.to_string());340341fn new2(start: Span, end: Span, message: String) -> Error {342Error {343messages: vec![ErrorMessage {344span: ThreadBound::new(SpanRange { start, end }),345message,346}],347}348}349}350351impl Debug for Error {352fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {353if self.messages.len() == 1 {354formatter355.debug_tuple("Error")356.field(&self.messages[0])357.finish()358} else {359formatter360.debug_tuple("Error")361.field(&self.messages)362.finish()363}364}365}366367impl Debug for ErrorMessage {368fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {369Debug::fmt(&self.message, formatter)370}371}372373impl Display for Error {374fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {375formatter.write_str(&self.messages[0].message)376}377}378379impl Clone for Error {380fn clone(&self) -> Self {381Error {382messages: self.messages.clone(),383}384}385}386387impl Clone for ErrorMessage {388fn clone(&self) -> Self {389ErrorMessage {390span: self.span,391message: self.message.clone(),392}393}394}395396impl Clone for SpanRange {397fn clone(&self) -> Self {398*self399}400}401402impl Copy for SpanRange {}403404impl std::error::Error for Error {}405406impl From<LexError> for Error {407fn from(err: LexError) -> Self {408Error::new(err.span(), err)409}410}411412impl IntoIterator for Error {413type Item = Error;414type IntoIter = IntoIter;415416fn into_iter(self) -> Self::IntoIter {417IntoIter {418messages: self.messages.into_iter(),419}420}421}422423pub struct IntoIter {424messages: vec::IntoIter<ErrorMessage>,425}426427impl Iterator for IntoIter {428type Item = Error;429430fn next(&mut self) -> Option<Self::Item> {431Some(Error {432messages: vec![self.messages.next()?],433})434}435}436437impl<'a> IntoIterator for &'a Error {438type Item = Error;439type IntoIter = Iter<'a>;440441fn into_iter(self) -> Self::IntoIter {442Iter {443messages: self.messages.iter(),444}445}446}447448pub struct Iter<'a> {449messages: slice::Iter<'a, ErrorMessage>,450}451452impl<'a> Iterator for Iter<'a> {453type Item = Error;454455fn next(&mut self) -> Option<Self::Item> {456Some(Error {457messages: vec![self.messages.next()?.clone()],458})459}460}461462impl Extend<Error> for Error {463fn extend<T: IntoIterator<Item = Error>>(&mut self, iter: T) {464for err in iter {465self.combine(err);466}467}468}469470471