blob: a6f9aea9dd79bd37f56165e7075c4c144278a33d [file] [log] [blame]
David Tolnay55535012018-01-05 16:39:23 -08001// Copyright 2018 Syn Developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
David Tolnaya9221302018-01-06 18:20:54 -08009//! A trait that can provide the `Span` of the complete contents of a syntax
10//! tree node.
11//!
David Tolnay461d98e2018-01-07 11:07:19 -080012//! *This module is available if Syn is built with both the `"parsing"` and
13//! `"printing"` features.*
14//!
David Tolnaya9221302018-01-06 18:20:54 -080015//! # Example
16//!
17//! Suppose in a procedural macro we have a [`Type`] that we want to assert
18//! implements the [`Sync`] trait. Maybe this is the type of one of the fields
19//! of a struct for which we are deriving a trait implementation, and we need to
20//! be able to pass a reference to one of those fields across threads.
21//!
22//! [`Type`]: ../enum.Type.html
23//! [`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html
24//!
25//! If the field type does *not* implement `Sync` as required, we want the
26//! compiler to report an error pointing out exactly which type it was.
27//!
28//! The following macro code takes a variable `ty` of type `Type` and produces a
29//! static assertion that `Sync` is implemented for that type.
30//!
31//! ```
David Tolnay9b00f652018-09-01 10:31:02 -070032//! # extern crate proc_macro;
33//! # extern crate proc_macro2;
David Tolnay9b00f652018-09-01 10:31:02 -070034//! # extern crate syn;
35//! #
David Tolnaya1c98072018-09-06 08:58:10 -070036//! #[macro_use]
37//! extern crate quote;
38//!
David Tolnay0a6deb22018-01-06 18:26:05 -080039//! use proc_macro::TokenStream;
40//! use proc_macro2::Span;
David Tolnay9b00f652018-09-01 10:31:02 -070041//! use syn::Type;
42//! use syn::spanned::Spanned;
David Tolnay0a6deb22018-01-06 18:26:05 -080043//!
44//! # const IGNORE_TOKENS: &str = stringify! {
45//! #[proc_macro_derive(MyMacro)]
46//! # };
47//! pub fn my_macro(input: TokenStream) -> TokenStream {
48//! # let ty = get_a_type();
49//! /* ... */
50//!
Alex Crichton9a4dca22018-03-28 06:32:19 -070051//! let assert_sync = quote_spanned! {ty.span()=>
David Tolnay0a6deb22018-01-06 18:26:05 -080052//! struct _AssertSync where #ty: Sync;
53//! };
54//!
55//! /* ... */
56//! # input
57//! }
David Tolnaya9221302018-01-06 18:20:54 -080058//! #
David Tolnay0a6deb22018-01-06 18:26:05 -080059//! # fn get_a_type() -> Type {
60//! # unimplemented!()
David Tolnaya9221302018-01-06 18:20:54 -080061//! # }
62//! #
63//! # fn main() {}
64//! ```
65//!
66//! By inserting this `assert_sync` fragment into the output code generated by
67//! our macro, the user's code will fail to compile if `ty` does not implement
68//! `Sync`. The errors they would see look like the following.
69//!
70//! ```text
71//! error[E0277]: the trait bound `*const i32: std::marker::Sync` is not satisfied
72//! --> src/main.rs:10:21
73//! |
74//! 10 | bad_field: *const i32,
75//! | ^^^^^^^^^^ `*const i32` cannot be shared between threads safely
76//! ```
77//!
78//! In this technique, using the `Type`'s span for the error message makes the
Alex Crichton9a4dca22018-03-28 06:32:19 -070079//! error appear in the correct place underlining the right type.
David Tolnaya9221302018-01-06 18:20:54 -080080
David Tolnayf790b612017-12-31 18:46:57 -050081use proc_macro2::{Span, TokenStream};
Alex Crichtona74a1c82018-05-16 10:20:44 -070082use quote::ToTokens;
David Tolnayf790b612017-12-31 18:46:57 -050083
David Tolnaya9221302018-01-06 18:20:54 -080084/// A trait that can provide the `Span` of the complete contents of a syntax
85/// tree node.
86///
87/// This trait is automatically implemented for all types that implement
David Tolnay6315c652018-08-24 16:05:45 -040088/// [`ToTokens`] from the `quote` crate. It is sealed and cannot be implemented
89/// outside of the Syn crate other than by implementing `ToTokens`.
David Tolnaya9221302018-01-06 18:20:54 -080090///
David Tolnay442cf762018-08-31 11:08:24 -070091/// [`ToTokens`]: https://docs.rs/quote/0.6/quote/trait.ToTokens.html
David Tolnaya9221302018-01-06 18:20:54 -080092///
93/// See the [module documentation] for an example.
94///
95/// [module documentation]: index.html
David Tolnay461d98e2018-01-07 11:07:19 -080096///
97/// *This trait is available if Syn is built with both the `"parsing"` and
98/// `"printing"` features.*
David Tolnay6315c652018-08-24 16:05:45 -040099pub trait Spanned: private::Sealed {
David Tolnaya9221302018-01-06 18:20:54 -0800100 /// Returns a `Span` covering the complete contents of this syntax tree
101 /// node, or [`Span::call_site()`] if this node is empty.
102 ///
David Tolnay442cf762018-08-31 11:08:24 -0700103 /// [`Span::call_site()`]: https://docs.rs/proc-macro2/0.4/proc_macro2/struct.Span.html#method.call_site
David Tolnayf790b612017-12-31 18:46:57 -0500104 fn span(&self) -> Span;
105}
106
David Tolnay6315c652018-08-24 16:05:45 -0400107mod private {
108 use quote::ToTokens;
109 pub trait Sealed {}
110 impl<T: ToTokens> Sealed for T {}
111}
112
David Tolnayf790b612017-12-31 18:46:57 -0500113impl<T> Spanned for T
114where
115 T: ToTokens,
116{
117 fn span(&self) -> Span {
David Tolnay785a79a2018-10-02 21:28:24 -0700118 join_spans(self.into_token_stream())
119 }
120}
121
122fn join_spans(tokens: TokenStream) -> Span {
123 let mut iter = tokens
124 .into_iter()
125 .filter_map(|tt| {
126 // FIXME: This shouldn't be required, since optimally spans should
127 // never be invalid. This filter_map can probably be removed when
128 // https://github.com/rust-lang/rust/issues/43081 is resolved.
129 let span = tt.span();
130 let debug = format!("{:?}", span);
131 if debug.ends_with("bytes(0..0)") {
132 None
133 } else {
134 Some(span)
135 }
136 });
137
138 let mut joined = match iter.next() {
139 Some(span) => span,
140 None => return Span::call_site(),
141 };
142
143 #[cfg(procmacro2_semver_exempt)]
144 {
145 for next in iter {
146 if let Some(span) = joined.join(next) {
147 joined = span;
148 }
149 }
David Tolnayf790b612017-12-31 18:46:57 -0500150 }
David Tolnay4d942b42018-01-02 22:14:04 -0800151
152 #[cfg(not(procmacro2_semver_exempt))]
David Tolnay785a79a2018-10-02 21:28:24 -0700153 {
David Tolnay4d942b42018-01-02 22:14:04 -0800154 // We can't join spans without procmacro2_semver_exempt so just grab the
155 // first one.
David Tolnay785a79a2018-10-02 21:28:24 -0700156 joined = joined;
David Tolnay4d942b42018-01-02 22:14:04 -0800157 }
David Tolnay785a79a2018-10-02 21:28:24 -0700158
159 joined
David Tolnayf790b612017-12-31 18:46:57 -0500160}