Skip to main content

quote_respanned/
lib.rs

1//! A crate for easily changing the span for [`TokenTree`]s, possibly recursing over [`Group`]s,
2//! usable with [`quote`].
3//!
4//! ```rust
5//! use proc_macro2::{
6//! 	Ident,
7//! 	Span,
8//! };
9//! use quote_respanned::QuoteRespanned;
10//!
11//! let my_ident = Ident::new("my_variable", Span::call_site());
12//!
13//! let original = quote::quote! {
14//! 	fn my_function() {
15//! 		let #my_ident = 42;
16//! 	}
17//! };
18//!
19//! // Now everything, including `my_ident`, will have the mixed_site span.
20//! QuoteRespanned::new(original, Span::mixed_site());
21//! ```
22#![no_std]
23#![cfg_attr(feature = "unstable-doc-cfg", feature(doc_cfg))]
24
25extern crate proc_macro2;
26extern crate quote;
27
28use core::{
29	fmt::{
30		self,
31		Formatter,
32	},
33	iter::FusedIterator,
34};
35
36use proc_macro2::{
37	Group,
38	Span,
39	TokenStream,
40	TokenTree,
41};
42use quote::{
43	IdentFragment,
44	ToTokens,
45};
46
47#[cfg(has_macros_in_doc)]
48macro_rules! create_wrapper {
49	(
50		[ $($prefix:tt)* ]
51		[ $($desc:tt)* ]
52		$name:ident,
53		$iter_name:ident,
54		$f_name:ident,
55		$respan_single:path
56	) => {
57		$($prefix)*
58		#[doc = $($desc)*]
59		/// 
60		/// This function changes the span of a single [`TokenTree`], optionally recursing into [`Group`]s.
61		#[must_use = "only the returned TokenTree has its span changed."]
62		pub fn $f_name(mut token: TokenTree, span: Span, apply_to_groups: bool) -> TokenTree {
63			let mut new_span = token.span();
64			$respan_single(&mut new_span, span);
65
66			let mut token = if apply_to_groups {
67				if let TokenTree::Group(group) = &mut token {
68					TokenTree::Group(Group::new(
69						group.delimiter(),
70						$iter_name::new(group.stream().into_iter(), span).collect(),
71					))
72				} else {
73					token
74				}
75			} else {
76				token
77			};
78
79			token.set_span(new_span);
80			token
81		}
82
83		$($prefix)*
84		#[doc = $($desc)*]
85		///
86		/// This type wraps any [`ToTokens`] type and applies the transformation when converted to tokens.
87		/// 
88		/// You can use [`quote`]'s [`ToTokens`] or [`IdentFragment`] to print out the [`TokenTree`]s with
89		/// your desired [`Span`]. (Usually, with [the macros](https://docs.rs/quote/latest/quote/index.html#macros))
90		///
91		/// Alternatively, you can iterate over the contained [`TokenTree`]s with 
92		#[doc = concat!("[`", stringify!($name), "::iter`]")]
93		///.
94		///
95		/// You can construct 
96		#[doc = concat!("[`", stringify!($name), "`]")]
97		/// manually, but it might be more ergonomic to use
98		#[doc = concat!("[`", stringify!($name), "::new`]")]
99		/// if you plainly want to change spans of all tokens, including those
100		/// inside groups.
101		#[derive(Debug, Clone, Copy)]
102		pub struct $name<T: ToTokens> {
103			/// The original contained tokens.
104			pub inner: T,
105
106			/// The span to apply to the tokens.
107			pub span: Span,
108
109			pub apply_to_groups: bool,
110		}
111
112		$($prefix)*
113		impl<T: ToTokens> $name<T> {
114			#[inline]
115			#[must_use = "construction doesn't change the spans of the original tokens."]
116			pub fn new(tokens: T, span: Span) -> Self {
117				$name {
118					inner: tokens,
119					span,
120					apply_to_groups: true,
121				}
122			}
123
124			#[inline]
125			#[must_use = "construction doesn't change the spans of the original value."]
126			pub fn new_without_groups(tokens: T, span: Span) -> Self {
127				$name {
128					inner: tokens,
129					span,
130					apply_to_groups: false,
131				}
132			}
133
134			#[inline]
135			#[must_use = "unwrapping this type doesn't change any spans."]
136			pub fn undo(self) -> T {
137				self.inner
138			}
139
140			#[inline]
141			#[must_use = "iterators do nothing unless consumed."]
142			pub fn iter(&self) -> $iter_name<<TokenStream as IntoIterator>::IntoIter> {
143				$iter_name {
144					inner: self.to_token_stream().into_iter(),
145					span: self.span,
146					apply_to_groups: self.apply_to_groups,
147				}
148			}
149		}
150
151		$($prefix)*
152		impl<T: ToTokens> ToTokens for $name<T> {
153			#[inline]
154			fn to_tokens(&self, tokens: &mut TokenStream) {
155				tokens.extend(self.iter());
156			}
157
158			#[inline]
159			fn to_token_stream(&self) -> TokenStream {
160				self.iter().collect()
161			}
162
163			#[inline]
164			fn into_token_stream(self) -> TokenStream
165			where
166				Self: Sized,
167			{
168				self.into_iter().collect()
169			}
170		}
171
172		$($prefix)*
173		impl<T: ToTokens> IntoIterator for $name<T> {
174			type IntoIter = $iter_name<<TokenStream as IntoIterator>::IntoIter>;
175			type Item = TokenTree;
176
177			#[inline]
178			fn into_iter(self) -> Self::IntoIter {
179				let span = self.span;
180				let apply_to_groups = self.apply_to_groups;
181
182				$iter_name {
183					inner: self.into_token_stream().into_iter(),
184					span,
185					apply_to_groups,
186				}
187			}
188		}
189
190		$($prefix)*
191		impl<T: ToTokens + IdentFragment> IdentFragment for $name<T> {
192			#[inline]
193			fn fmt(&self, f: &mut Formatter) -> fmt::Result {
194				self.inner.fmt(f)
195			}
196
197			#[inline]
198			fn span(&self) -> Option<Span> {
199				self.inner.span().map(|mut span| {
200					$respan_single(&mut span, self.span);
201					span
202				})
203			}
204		}
205
206		$($prefix)*
207		///
208		/// This iterator is used by
209		#[doc = concat!("[`", stringify!($name), "`]")]
210		/// .
211		#[derive(Debug, Clone, Copy)]
212		pub struct $iter_name<T: Iterator<Item = TokenTree>> {
213			pub inner: T,
214			pub span: Span,
215			pub apply_to_groups: bool,
216		}
217
218		$($prefix)*
219		impl<T: Iterator<Item = TokenTree>> $iter_name<T> {
220			#[inline]
221			#[must_use = "unwrapping doesn't change any spans."]
222			pub fn unrespanned(self) -> T {
223				self.inner
224			}
225		}
226
227		$($prefix)*
228		impl<T: Iterator<Item = TokenTree>> $iter_name<T> {
229			#[inline]
230			#[must_use = "construction doesn't change the spans of the original value."]
231			pub fn new(inner: T, span: Span) -> Self {
232				$iter_name {
233					inner,
234					span,
235					apply_to_groups: true,
236				}
237			}
238
239			#[inline]
240			#[must_use = "construction doesn't change the spans of the original value."]
241			pub fn new_without_groups(inner: T, span: Span) -> Self {
242				$iter_name {
243					inner,
244					span,
245					apply_to_groups: false,
246				}
247			}
248		}
249
250		$($prefix)*
251		impl<T: Iterator<Item = TokenTree>> Iterator for $iter_name<T> {
252			type Item = TokenTree;
253
254			#[inline]
255			fn next(&mut self) -> Option<Self::Item> {
256				self.inner
257					.next()
258					.map(|token| $f_name(token, self.span, self.apply_to_groups))
259			}
260
261			#[inline]
262			fn size_hint(&self) -> (usize, Option<usize>) {
263				self.inner.size_hint()
264			}
265
266			#[inline]
267			fn count(self) -> usize
268			where
269				Self: Sized,
270			{
271				self.inner.count()
272			}
273
274			#[inline]
275			fn last(self) -> Option<Self::Item>
276			where
277				Self: Sized,
278			{
279				let span = self.span;
280				let apply_to_groups = self.apply_to_groups;
281
282				self.inner
283					.last()
284					.map(|token| $f_name(token, span, apply_to_groups))
285			}
286
287			#[inline]
288			fn nth(&mut self, n: usize) -> Option<Self::Item> {
289				if n > 0 {
290					if self.inner.nth(n - 1).is_none() {
291						return None
292					}
293				}
294
295				self.next()
296			}
297		}
298
299		$($prefix)*
300		impl<T: DoubleEndedIterator<Item = TokenTree>> DoubleEndedIterator for $iter_name<T> {
301			#[inline]
302			fn next_back(&mut self) -> Option<Self::Item> {
303				self.inner
304					.next_back()
305					.map(|token| $f_name(token, self.span, self.apply_to_groups))
306			}
307
308			#[inline]
309			fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
310				if n > 0 {
311					if self.inner.nth_back(n - 1).is_none() {
312						return None
313					}
314				}
315
316				self.next_back()
317			}
318		}
319
320		$($prefix)*
321		impl<T: ExactSizeIterator<Item = TokenTree>> ExactSizeIterator for $iter_name<T> {
322			#[inline]
323			fn len(&self) -> usize {
324				self.inner.len()
325			}
326		}
327
328		$($prefix)*
329		impl<T: FusedIterator<Item = TokenTree>> FusedIterator for $iter_name<T> {}
330
331		$($prefix)*
332		impl<T: Iterator<Item = TokenTree> + Clone> ToTokens for $iter_name<T> {
333			#[inline]
334			fn to_tokens(&self, tokens: &mut TokenStream) {
335				tokens.extend(self.clone());
336			}
337
338			#[inline]
339			fn to_token_stream(&self) -> TokenStream {
340				self.clone().collect()
341			}
342
343			#[inline]
344			fn into_token_stream(self) -> TokenStream
345			where
346				Self: Sized,
347			{
348				self.collect()
349			}
350		}
351	};
352}
353
354#[cfg(not(has_macros_in_doc))]
355macro_rules! create_wrapper {
356	(
357		[ $($prefix:tt)* ]
358		[ $($desc:tt)* ]
359		$name:ident,
360		$iter_name:ident,
361		$f_name:ident,
362		$respan_single:path
363	) => {
364		$($prefix)*
365		#[doc = $($desc)*]
366		/// 
367		/// This function changes the span of a single [`TokenTree`], optionally recursing into [`Group`]s.
368		#[must_use = "only the returned TokenTree has its span changed."]
369		pub fn $f_name(mut token: TokenTree, span: Span, apply_to_groups: bool) -> TokenTree {
370			let mut new_span = token.span();
371			$respan_single(&mut new_span, span);
372
373			let mut token = if apply_to_groups {
374				if let TokenTree::Group(group) = &mut token {
375					TokenTree::Group(Group::new(
376						group.delimiter(),
377						$iter_name::new(group.stream().into_iter(), span).collect(),
378					))
379				} else {
380					token
381				}
382			} else {
383				token
384			};
385
386			token.set_span(new_span);
387			token
388		}
389
390		$($prefix)*
391		#[doc = $($desc)*]
392		///
393		/// This type wraps any [`ToTokens`] type and applies the transformation when converted to tokens.
394		/// 
395		/// You can use [`quote`]'s [`ToTokens`] or [`IdentFragment`] to print out the [`TokenTree`]s with
396		/// your desired [`Span`]. (Usually, with [the macros](https://docs.rs/quote/latest/quote/index.html#macros))
397		///
398		/// Alternatively, you can iterate over the contained [`TokenTree`]s with 
399		#[doc = "`iter`"]
400		///.
401		///
402		/// You can construct 
403		#[doc = "this type"]
404		/// manually, but it might be more ergonomic to use
405		#[doc = "`new`"]
406		/// if you plainly want to change spans of all tokens, including those
407		/// inside groups.
408		#[derive(Debug, Clone, Copy)]
409		pub struct $name<T: ToTokens> {
410			/// The original contained tokens.
411			pub inner: T,
412
413			/// The span to apply to the tokens.
414			pub span: Span,
415
416			pub apply_to_groups: bool,
417		}
418
419		$($prefix)*
420		impl<T: ToTokens> $name<T> {
421			#[inline]
422			#[must_use = "construction doesn't change the spans of the original tokens."]
423			pub fn new(tokens: T, span: Span) -> Self {
424				$name {
425					inner: tokens,
426					span,
427					apply_to_groups: true,
428				}
429			}
430
431			#[inline]
432			#[must_use = "construction doesn't change the spans of the original value."]
433			pub fn new_without_groups(tokens: T, span: Span) -> Self {
434				$name {
435					inner: tokens,
436					span,
437					apply_to_groups: false,
438				}
439			}
440
441			#[inline]
442			#[must_use = "unwrapping this type doesn't change any spans."]
443			pub fn undo(self) -> T {
444				self.inner
445			}
446
447			#[inline]
448			#[must_use = "iterators do nothing unless consumed."]
449			pub fn iter(&self) -> $iter_name<<TokenStream as IntoIterator>::IntoIter> {
450				$iter_name {
451					inner: self.to_token_stream().into_iter(),
452					span: self.span,
453					apply_to_groups: self.apply_to_groups,
454				}
455			}
456		}
457
458		$($prefix)*
459		impl<T: ToTokens> ToTokens for $name<T> {
460			#[inline]
461			fn to_tokens(&self, tokens: &mut TokenStream) {
462				tokens.extend(self.iter());
463			}
464
465			#[inline]
466			fn to_token_stream(&self) -> TokenStream {
467				self.iter().collect()
468			}
469
470			#[inline]
471			fn into_token_stream(self) -> TokenStream
472			where
473				Self: Sized,
474			{
475				self.into_iter().collect()
476			}
477		}
478
479		$($prefix)*
480		impl<T: ToTokens> IntoIterator for $name<T> {
481			type IntoIter = $iter_name<<TokenStream as IntoIterator>::IntoIter>;
482			type Item = TokenTree;
483
484			#[inline]
485			fn into_iter(self) -> Self::IntoIter {
486				let span = self.span;
487				let apply_to_groups = self.apply_to_groups;
488
489				$iter_name {
490					inner: self.into_token_stream().into_iter(),
491					span,
492					apply_to_groups,
493				}
494			}
495		}
496
497		$($prefix)*
498		impl<T: ToTokens + IdentFragment> IdentFragment for $name<T> {
499			#[inline]
500			fn fmt(&self, f: &mut Formatter) -> fmt::Result {
501				self.inner.fmt(f)
502			}
503
504			#[inline]
505			fn span(&self) -> Option<Span> {
506				self.inner.span().map(|mut span| {
507					$respan_single(&mut span, self.span);
508					span
509				})
510			}
511		}
512
513		$($prefix)*
514		///
515		/// This iterator is used by
516		#[doc = "the wrapper type"]
517		/// .
518		#[derive(Debug, Clone, Copy)]
519		pub struct $iter_name<T: Iterator<Item = TokenTree>> {
520			pub inner: T,
521			pub span: Span,
522			pub apply_to_groups: bool,
523		}
524
525		$($prefix)*
526		impl<T: Iterator<Item = TokenTree>> $iter_name<T> {
527			#[inline]
528			#[must_use = "unwrapping doesn't change any spans."]
529			pub fn unrespanned(self) -> T {
530				self.inner
531			}
532		}
533
534		$($prefix)*
535		impl<T: Iterator<Item = TokenTree>> $iter_name<T> {
536			#[inline]
537			#[must_use = "construction doesn't change the spans of the original value."]
538			pub fn new(inner: T, span: Span) -> Self {
539				$iter_name {
540					inner,
541					span,
542					apply_to_groups: true,
543				}
544			}
545
546			#[inline]
547			#[must_use = "construction doesn't change the spans of the original value."]
548			pub fn new_without_groups(inner: T, span: Span) -> Self {
549				$iter_name {
550					inner,
551					span,
552					apply_to_groups: false,
553				}
554			}
555		}
556
557		$($prefix)*
558		impl<T: Iterator<Item = TokenTree>> Iterator for $iter_name<T> {
559			type Item = TokenTree;
560
561			#[inline]
562			fn next(&mut self) -> Option<Self::Item> {
563				self.inner
564					.next()
565					.map(|token| $f_name(token, self.span, self.apply_to_groups))
566			}
567
568			#[inline]
569			fn size_hint(&self) -> (usize, Option<usize>) {
570				self.inner.size_hint()
571			}
572
573			#[inline]
574			fn count(self) -> usize
575			where
576				Self: Sized,
577			{
578				self.inner.count()
579			}
580
581			#[inline]
582			fn last(self) -> Option<Self::Item>
583			where
584				Self: Sized,
585			{
586				let span = self.span;
587				let apply_to_groups = self.apply_to_groups;
588
589				self.inner
590					.last()
591					.map(|token| $f_name(token, span, apply_to_groups))
592			}
593
594			#[inline]
595			fn nth(&mut self, n: usize) -> Option<Self::Item> {
596				if n > 0 {
597					if self.inner.nth(n - 1).is_none() {
598						return None
599					}
600				}
601
602				self.next()
603			}
604		}
605
606		$($prefix)*
607		impl<T: DoubleEndedIterator<Item = TokenTree>> DoubleEndedIterator for $iter_name<T> {
608			#[inline]
609			fn next_back(&mut self) -> Option<Self::Item> {
610				self.inner
611					.next_back()
612					.map(|token| $f_name(token, self.span, self.apply_to_groups))
613			}
614
615			#[cfg(has_nth_back)]
616			#[inline]
617			fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
618				if n > 0 {
619					if self.inner.nth_back(n - 1).is_none() {
620						return None
621					}
622				}
623
624				self.next_back()
625			}
626		}
627
628		$($prefix)*
629		impl<T: ExactSizeIterator<Item = TokenTree>> ExactSizeIterator for $iter_name<T> {
630			#[inline]
631			fn len(&self) -> usize {
632				self.inner.len()
633			}
634		}
635
636		$($prefix)*
637		impl<T: FusedIterator<Item = TokenTree>> FusedIterator for $iter_name<T> {}
638
639		$($prefix)*
640		impl<T: Iterator<Item = TokenTree> + Clone> ToTokens for $iter_name<T> {
641			#[inline]
642			fn to_tokens(&self, tokens: &mut TokenStream) {
643				tokens.extend(self.clone());
644			}
645
646			#[inline]
647			fn to_token_stream(&self) -> TokenStream {
648				self.clone().collect()
649			}
650
651			#[inline]
652			fn into_token_stream(self) -> TokenStream
653			where
654				Self: Sized,
655			{
656				self.collect()
657			}
658		}
659	};
660}
661
662fn respan_single(original: &mut Span, with: Span) {
663	*original = with;
664}
665
666#[cfg(has_span_resolution)]
667fn reresolve_single(original: &mut Span, with: Span) {
668	*original = original.resolved_at(with);
669}
670
671#[cfg(has_span_resolution)]
672fn relocate_single(original: &mut Span, with: Span) {
673	*original = original.located_at(with);
674}
675
676create_wrapper! {
677	[]
678	["Replaces the span entirely."]
679	QuoteRespanned,
680	QuoteRespannedIter,
681	respan,
682	respan_single
683}
684
685create_wrapper! {
686	[ #[cfg(has_span_resolution)] ]
687	[ "Changes the resolution site for [`Span`]s." ]
688	QuoteReresolved,
689	QuoteReresolvedIter,
690	reresolve,
691	reresolve_single
692}
693
694create_wrapper! {
695	[ #[cfg(has_span_resolution)] ]
696	[ "Changes the resolution site for [`Span`]s." ]
697	QuoteRelocated,
698	QuoteRelocatedIter,
699	relocate,
700	relocate_single
701}