blob: 2da45d796bb125a0b666d624bc1c272d5ea7d282 [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//!
12//! # Example
13//!
14//! Suppose in a procedural macro we have a [`Type`] that we want to assert
15//! implements the [`Sync`] trait. Maybe this is the type of one of the fields
16//! of a struct for which we are deriving a trait implementation, and we need to
17//! be able to pass a reference to one of those fields across threads.
18//!
19//! [`Type`]: ../enum.Type.html
20//! [`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html
21//!
22//! If the field type does *not* implement `Sync` as required, we want the
23//! compiler to report an error pointing out exactly which type it was.
24//!
25//! The following macro code takes a variable `ty` of type `Type` and produces a
26//! static assertion that `Sync` is implemented for that type.
27//!
28//! ```
David Tolnay0a6deb22018-01-06 18:26:05 -080029//! #[macro_use]
30//! extern crate quote;
31//!
32//! extern crate syn;
33//! extern crate proc_macro;
34//! extern crate proc_macro2;
35//!
36//! use syn::Type;
37//! use syn::spanned::Spanned;
38//! use proc_macro::TokenStream;
39//! use proc_macro2::Span;
40//!
41//! # const IGNORE_TOKENS: &str = stringify! {
42//! #[proc_macro_derive(MyMacro)]
43//! # };
44//! pub fn my_macro(input: TokenStream) -> TokenStream {
45//! # let ty = get_a_type();
46//! /* ... */
47//!
48//! let def_site = Span::def_site();
49//! let ty_span = ty.span().resolved_at(def_site);
50//! let assert_sync = quote_spanned! {ty_span=>
51//! struct _AssertSync where #ty: Sync;
52//! };
53//!
54//! /* ... */
55//! # input
56//! }
David Tolnaya9221302018-01-06 18:20:54 -080057//! #
David Tolnay0a6deb22018-01-06 18:26:05 -080058//! # fn get_a_type() -> Type {
59//! # unimplemented!()
David Tolnaya9221302018-01-06 18:20:54 -080060//! # }
61//! #
62//! # fn main() {}
63//! ```
64//!
65//! By inserting this `assert_sync` fragment into the output code generated by
66//! our macro, the user's code will fail to compile if `ty` does not implement
67//! `Sync`. The errors they would see look like the following.
68//!
69//! ```text
70//! error[E0277]: the trait bound `*const i32: std::marker::Sync` is not satisfied
71//! --> src/main.rs:10:21
72//! |
73//! 10 | bad_field: *const i32,
74//! | ^^^^^^^^^^ `*const i32` cannot be shared between threads safely
75//! ```
76//!
77//! In this technique, using the `Type`'s span for the error message makes the
78//! error appear in the correct place underlining the right type. But it is
79//! **incredibly important** that the span for the assertion is **resolved** at
80//! the procedural macro definition site rather than at the `Type`'s span. This
81//! way we guarantee that it refers to the `Sync` trait that we expect. If the
82//! assertion were **resolved** at the same place that `ty` is resolved, the
83//! user could circumvent the check by defining their own `Sync` trait that is
84//! implemented for their type.
85
David Tolnayf790b612017-12-31 18:46:57 -050086use proc_macro2::{Span, TokenStream};
David Tolnay61037c62018-01-05 16:21:03 -080087use quote::{ToTokens, Tokens};
David Tolnayf790b612017-12-31 18:46:57 -050088
David Tolnaya9221302018-01-06 18:20:54 -080089/// A trait that can provide the `Span` of the complete contents of a syntax
90/// tree node.
91///
92/// This trait is automatically implemented for all types that implement
93/// [`ToTokens`] from the `quote` crate.
94///
95/// [`ToTokens`]: https://docs.rs/quote/0.4/quote/trait.ToTokens.html
96///
97/// See the [module documentation] for an example.
98///
99/// [module documentation]: index.html
David Tolnayf790b612017-12-31 18:46:57 -0500100pub trait Spanned {
David Tolnaya9221302018-01-06 18:20:54 -0800101 /// Returns a `Span` covering the complete contents of this syntax tree
102 /// node, or [`Span::call_site()`] if this node is empty.
103 ///
104 /// [`Span::call_site()`]: https://docs.rs/proc-macro2/0.1/proc_macro2/struct.Span.html#method.call_site
David Tolnayf790b612017-12-31 18:46:57 -0500105 fn span(&self) -> Span;
106}
107
108impl<T> Spanned for T
109where
110 T: ToTokens,
111{
David Tolnay4d942b42018-01-02 22:14:04 -0800112 #[cfg(procmacro2_semver_exempt)]
David Tolnayf790b612017-12-31 18:46:57 -0500113 fn span(&self) -> Span {
114 let mut tokens = Tokens::new();
115 self.to_tokens(&mut tokens);
116 let token_stream = TokenStream::from(tokens);
117 let mut iter = token_stream.into_iter();
118 let mut span = match iter.next() {
119 Some(tt) => tt.span,
120 None => {
121 return Span::call_site();
122 }
123 };
124 for tt in iter {
125 if let Some(joined) = span.join(tt.span) {
126 span = joined;
127 }
128 }
129 span
130 }
David Tolnay4d942b42018-01-02 22:14:04 -0800131
132 #[cfg(not(procmacro2_semver_exempt))]
133 fn span(&self) -> Span {
134 let mut tokens = Tokens::new();
135 self.to_tokens(&mut tokens);
136 let token_stream = TokenStream::from(tokens);
137 let mut iter = token_stream.into_iter();
138
139 // We can't join spans without procmacro2_semver_exempt so just grab the
140 // first one.
141 match iter.next() {
142 Some(tt) => tt.span,
143 None => Span::call_site(),
144 }
145 }
David Tolnayf790b612017-12-31 18:46:57 -0500146}