blob: 6e2215d2843a95195f62528b9f52482ef60a9795 [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 Tolnay0a6deb22018-01-06 18:26:05 -080032//! #[macro_use]
33//! extern crate quote;
34//!
35//! extern crate syn;
36//! extern crate proc_macro;
37//! extern crate proc_macro2;
38//!
39//! use syn::Type;
40//! use syn::spanned::Spanned;
41//! use proc_macro::TokenStream;
42//! use proc_macro2::Span;
43//!
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///
91/// [`ToTokens`]: https://docs.rs/quote/0.4/quote/trait.ToTokens.html
92///
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 Tolnay66bb8d52018-01-08 08:22:31 -0800103 /// [`Span::call_site()`]: https://docs.rs/proc-macro2/0.2/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{
David Tolnay4d942b42018-01-02 22:14:04 -0800117 #[cfg(procmacro2_semver_exempt)]
David Tolnayf790b612017-12-31 18:46:57 -0500118 fn span(&self) -> Span {
hcplaa511792018-05-29 07:13:01 +0300119 let mut tokens = TokenStream::new();
David Tolnayf790b612017-12-31 18:46:57 -0500120 self.to_tokens(&mut tokens);
David Tolnay106db5e2018-05-20 19:56:38 -0700121 let mut iter = tokens.into_iter();
David Tolnayf790b612017-12-31 18:46:57 -0500122 let mut span = match iter.next() {
David Tolnay4fbab462018-03-31 17:15:56 +0200123 Some(tt) => tt.span(),
David Tolnayf790b612017-12-31 18:46:57 -0500124 None => {
125 return Span::call_site();
126 }
127 };
128 for tt in iter {
David Tolnay4fbab462018-03-31 17:15:56 +0200129 if let Some(joined) = span.join(tt.span()) {
David Tolnayf790b612017-12-31 18:46:57 -0500130 span = joined;
131 }
132 }
133 span
134 }
David Tolnay4d942b42018-01-02 22:14:04 -0800135
136 #[cfg(not(procmacro2_semver_exempt))]
137 fn span(&self) -> Span {
hcplaa511792018-05-29 07:13:01 +0300138 let mut tokens = TokenStream::new();
David Tolnay4d942b42018-01-02 22:14:04 -0800139 self.to_tokens(&mut tokens);
David Tolnay106db5e2018-05-20 19:56:38 -0700140 let mut iter = tokens.into_iter();
David Tolnay4d942b42018-01-02 22:14:04 -0800141
142 // We can't join spans without procmacro2_semver_exempt so just grab the
143 // first one.
144 match iter.next() {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700145 Some(tt) => tt.span(),
David Tolnay4d942b42018-01-02 22:14:04 -0800146 None => Span::call_site(),
147 }
148 }
David Tolnayf790b612017-12-31 18:46:57 -0500149}