blob: 72c47985c63da96ed1ffd12af5f22b5167ed6aa9 [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
88/// [`ToTokens`] from the `quote` crate.
89///
90/// [`ToTokens`]: https://docs.rs/quote/0.4/quote/trait.ToTokens.html
91///
92/// See the [module documentation] for an example.
93///
94/// [module documentation]: index.html
David Tolnay461d98e2018-01-07 11:07:19 -080095///
96/// *This trait is available if Syn is built with both the `"parsing"` and
97/// `"printing"` features.*
David Tolnayf790b612017-12-31 18:46:57 -050098pub trait Spanned {
David Tolnaya9221302018-01-06 18:20:54 -080099 /// Returns a `Span` covering the complete contents of this syntax tree
100 /// node, or [`Span::call_site()`] if this node is empty.
101 ///
David Tolnay66bb8d52018-01-08 08:22:31 -0800102 /// [`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 -0500103 fn span(&self) -> Span;
104}
105
106impl<T> Spanned for T
107where
108 T: ToTokens,
109{
David Tolnay4d942b42018-01-02 22:14:04 -0800110 #[cfg(procmacro2_semver_exempt)]
David Tolnayf790b612017-12-31 18:46:57 -0500111 fn span(&self) -> Span {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700112 let mut tokens = TokenStream::empty();
David Tolnayf790b612017-12-31 18:46:57 -0500113 self.to_tokens(&mut tokens);
David Tolnay106db5e2018-05-20 19:56:38 -0700114 let mut iter = tokens.into_iter();
David Tolnayf790b612017-12-31 18:46:57 -0500115 let mut span = match iter.next() {
David Tolnay4fbab462018-03-31 17:15:56 +0200116 Some(tt) => tt.span(),
David Tolnayf790b612017-12-31 18:46:57 -0500117 None => {
118 return Span::call_site();
119 }
120 };
121 for tt in iter {
David Tolnay4fbab462018-03-31 17:15:56 +0200122 if let Some(joined) = span.join(tt.span()) {
David Tolnayf790b612017-12-31 18:46:57 -0500123 span = joined;
124 }
125 }
126 span
127 }
David Tolnay4d942b42018-01-02 22:14:04 -0800128
129 #[cfg(not(procmacro2_semver_exempt))]
130 fn span(&self) -> Span {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700131 let mut tokens = TokenStream::empty();
David Tolnay4d942b42018-01-02 22:14:04 -0800132 self.to_tokens(&mut tokens);
David Tolnay106db5e2018-05-20 19:56:38 -0700133 let mut iter = tokens.into_iter();
David Tolnay4d942b42018-01-02 22:14:04 -0800134
135 // We can't join spans without procmacro2_semver_exempt so just grab the
136 // first one.
137 match iter.next() {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700138 Some(tt) => tt.span(),
David Tolnay4d942b42018-01-02 22:14:04 -0800139 None => Span::call_site(),
140 }
141 }
David Tolnayf790b612017-12-31 18:46:57 -0500142}