• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use crate::detection::inside_proc_macro;
2 #[cfg(span_locations)]
3 use crate::location::LineColumn;
4 use crate::{fallback, Delimiter, Punct, Spacing, TokenTree};
5 use core::fmt::{self, Debug, Display};
6 use core::ops::RangeBounds;
7 use core::str::FromStr;
8 use std::panic;
9 #[cfg(super_unstable)]
10 use std::path::PathBuf;
11 
12 #[derive(Clone)]
13 pub(crate) enum TokenStream {
14     Compiler(DeferredTokenStream),
15     Fallback(fallback::TokenStream),
16 }
17 
18 // Work around https://github.com/rust-lang/rust/issues/65080.
19 // In `impl Extend<TokenTree> for TokenStream` which is used heavily by quote,
20 // we hold on to the appended tokens and do proc_macro::TokenStream::extend as
21 // late as possible to batch together consecutive uses of the Extend impl.
22 #[derive(Clone)]
23 pub(crate) struct DeferredTokenStream {
24     stream: proc_macro::TokenStream,
25     extra: Vec<proc_macro::TokenTree>,
26 }
27 
28 pub(crate) enum LexError {
29     Compiler(proc_macro::LexError),
30     Fallback(fallback::LexError),
31 }
32 
33 impl LexError {
call_site() -> Self34     fn call_site() -> Self {
35         LexError::Fallback(fallback::LexError {
36             span: fallback::Span::call_site(),
37         })
38     }
39 }
40 
mismatch() -> !41 fn mismatch() -> ! {
42     panic!("compiler/fallback mismatch")
43 }
44 
45 impl DeferredTokenStream {
new(stream: proc_macro::TokenStream) -> Self46     fn new(stream: proc_macro::TokenStream) -> Self {
47         DeferredTokenStream {
48             stream,
49             extra: Vec::new(),
50         }
51     }
52 
is_empty(&self) -> bool53     fn is_empty(&self) -> bool {
54         self.stream.is_empty() && self.extra.is_empty()
55     }
56 
evaluate_now(&mut self)57     fn evaluate_now(&mut self) {
58         // If-check provides a fast short circuit for the common case of `extra`
59         // being empty, which saves a round trip over the proc macro bridge.
60         // Improves macro expansion time in winrt by 6% in debug mode.
61         if !self.extra.is_empty() {
62             self.stream.extend(self.extra.drain(..));
63         }
64     }
65 
into_token_stream(mut self) -> proc_macro::TokenStream66     fn into_token_stream(mut self) -> proc_macro::TokenStream {
67         self.evaluate_now();
68         self.stream
69     }
70 }
71 
72 impl TokenStream {
new() -> Self73     pub fn new() -> Self {
74         if inside_proc_macro() {
75             TokenStream::Compiler(DeferredTokenStream::new(proc_macro::TokenStream::new()))
76         } else {
77             TokenStream::Fallback(fallback::TokenStream::new())
78         }
79     }
80 
is_empty(&self) -> bool81     pub fn is_empty(&self) -> bool {
82         match self {
83             TokenStream::Compiler(tts) => tts.is_empty(),
84             TokenStream::Fallback(tts) => tts.is_empty(),
85         }
86     }
87 
unwrap_nightly(self) -> proc_macro::TokenStream88     fn unwrap_nightly(self) -> proc_macro::TokenStream {
89         match self {
90             TokenStream::Compiler(s) => s.into_token_stream(),
91             TokenStream::Fallback(_) => mismatch(),
92         }
93     }
94 
unwrap_stable(self) -> fallback::TokenStream95     fn unwrap_stable(self) -> fallback::TokenStream {
96         match self {
97             TokenStream::Compiler(_) => mismatch(),
98             TokenStream::Fallback(s) => s,
99         }
100     }
101 }
102 
103 impl FromStr for TokenStream {
104     type Err = LexError;
105 
from_str(src: &str) -> Result<TokenStream, LexError>106     fn from_str(src: &str) -> Result<TokenStream, LexError> {
107         if inside_proc_macro() {
108             Ok(TokenStream::Compiler(DeferredTokenStream::new(
109                 proc_macro_parse(src)?,
110             )))
111         } else {
112             Ok(TokenStream::Fallback(src.parse()?))
113         }
114     }
115 }
116 
117 // Work around https://github.com/rust-lang/rust/issues/58736.
proc_macro_parse(src: &str) -> Result<proc_macro::TokenStream, LexError>118 fn proc_macro_parse(src: &str) -> Result<proc_macro::TokenStream, LexError> {
119     let result = panic::catch_unwind(|| src.parse().map_err(LexError::Compiler));
120     result.unwrap_or_else(|_| Err(LexError::call_site()))
121 }
122 
123 impl Display for TokenStream {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result124     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
125         match self {
126             TokenStream::Compiler(tts) => Display::fmt(&tts.clone().into_token_stream(), f),
127             TokenStream::Fallback(tts) => Display::fmt(tts, f),
128         }
129     }
130 }
131 
132 impl From<proc_macro::TokenStream> for TokenStream {
from(inner: proc_macro::TokenStream) -> Self133     fn from(inner: proc_macro::TokenStream) -> Self {
134         TokenStream::Compiler(DeferredTokenStream::new(inner))
135     }
136 }
137 
138 impl From<TokenStream> for proc_macro::TokenStream {
from(inner: TokenStream) -> Self139     fn from(inner: TokenStream) -> Self {
140         match inner {
141             TokenStream::Compiler(inner) => inner.into_token_stream(),
142             TokenStream::Fallback(inner) => inner.to_string().parse().unwrap(),
143         }
144     }
145 }
146 
147 impl From<fallback::TokenStream> for TokenStream {
from(inner: fallback::TokenStream) -> Self148     fn from(inner: fallback::TokenStream) -> Self {
149         TokenStream::Fallback(inner)
150     }
151 }
152 
153 // Assumes inside_proc_macro().
into_compiler_token(token: TokenTree) -> proc_macro::TokenTree154 fn into_compiler_token(token: TokenTree) -> proc_macro::TokenTree {
155     match token {
156         TokenTree::Group(tt) => tt.inner.unwrap_nightly().into(),
157         TokenTree::Punct(tt) => {
158             let spacing = match tt.spacing() {
159                 Spacing::Joint => proc_macro::Spacing::Joint,
160                 Spacing::Alone => proc_macro::Spacing::Alone,
161             };
162             let mut punct = proc_macro::Punct::new(tt.as_char(), spacing);
163             punct.set_span(tt.span().inner.unwrap_nightly());
164             punct.into()
165         }
166         TokenTree::Ident(tt) => tt.inner.unwrap_nightly().into(),
167         TokenTree::Literal(tt) => tt.inner.unwrap_nightly().into(),
168     }
169 }
170 
171 impl From<TokenTree> for TokenStream {
from(token: TokenTree) -> Self172     fn from(token: TokenTree) -> Self {
173         if inside_proc_macro() {
174             TokenStream::Compiler(DeferredTokenStream::new(into_compiler_token(token).into()))
175         } else {
176             TokenStream::Fallback(token.into())
177         }
178     }
179 }
180 
181 impl FromIterator<TokenTree> for TokenStream {
from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self182     fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
183         if inside_proc_macro() {
184             TokenStream::Compiler(DeferredTokenStream::new(
185                 trees.into_iter().map(into_compiler_token).collect(),
186             ))
187         } else {
188             TokenStream::Fallback(trees.into_iter().collect())
189         }
190     }
191 }
192 
193 impl FromIterator<TokenStream> for TokenStream {
from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self194     fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
195         let mut streams = streams.into_iter();
196         match streams.next() {
197             Some(TokenStream::Compiler(mut first)) => {
198                 first.evaluate_now();
199                 first.stream.extend(streams.map(|s| match s {
200                     TokenStream::Compiler(s) => s.into_token_stream(),
201                     TokenStream::Fallback(_) => mismatch(),
202                 }));
203                 TokenStream::Compiler(first)
204             }
205             Some(TokenStream::Fallback(mut first)) => {
206                 first.extend(streams.map(|s| match s {
207                     TokenStream::Fallback(s) => s,
208                     TokenStream::Compiler(_) => mismatch(),
209                 }));
210                 TokenStream::Fallback(first)
211             }
212             None => TokenStream::new(),
213         }
214     }
215 }
216 
217 impl Extend<TokenTree> for TokenStream {
extend<I: IntoIterator<Item = TokenTree>>(&mut self, stream: I)218     fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, stream: I) {
219         match self {
220             TokenStream::Compiler(tts) => {
221                 // Here is the reason for DeferredTokenStream.
222                 for token in stream {
223                     tts.extra.push(into_compiler_token(token));
224                 }
225             }
226             TokenStream::Fallback(tts) => tts.extend(stream),
227         }
228     }
229 }
230 
231 impl Extend<TokenStream> for TokenStream {
extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I)232     fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
233         match self {
234             TokenStream::Compiler(tts) => {
235                 tts.evaluate_now();
236                 tts.stream
237                     .extend(streams.into_iter().map(TokenStream::unwrap_nightly));
238             }
239             TokenStream::Fallback(tts) => {
240                 tts.extend(streams.into_iter().map(TokenStream::unwrap_stable));
241             }
242         }
243     }
244 }
245 
246 impl Debug for TokenStream {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result247     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
248         match self {
249             TokenStream::Compiler(tts) => Debug::fmt(&tts.clone().into_token_stream(), f),
250             TokenStream::Fallback(tts) => Debug::fmt(tts, f),
251         }
252     }
253 }
254 
255 impl LexError {
span(&self) -> Span256     pub(crate) fn span(&self) -> Span {
257         match self {
258             LexError::Compiler(_) => Span::call_site(),
259             LexError::Fallback(e) => Span::Fallback(e.span()),
260         }
261     }
262 }
263 
264 impl From<proc_macro::LexError> for LexError {
from(e: proc_macro::LexError) -> Self265     fn from(e: proc_macro::LexError) -> Self {
266         LexError::Compiler(e)
267     }
268 }
269 
270 impl From<fallback::LexError> for LexError {
from(e: fallback::LexError) -> Self271     fn from(e: fallback::LexError) -> Self {
272         LexError::Fallback(e)
273     }
274 }
275 
276 impl Debug for LexError {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result277     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
278         match self {
279             LexError::Compiler(e) => Debug::fmt(e, f),
280             LexError::Fallback(e) => Debug::fmt(e, f),
281         }
282     }
283 }
284 
285 impl Display for LexError {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result286     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
287         match self {
288             LexError::Compiler(e) => Display::fmt(e, f),
289             LexError::Fallback(e) => Display::fmt(e, f),
290         }
291     }
292 }
293 
294 #[derive(Clone)]
295 pub(crate) enum TokenTreeIter {
296     Compiler(proc_macro::token_stream::IntoIter),
297     Fallback(fallback::TokenTreeIter),
298 }
299 
300 impl IntoIterator for TokenStream {
301     type Item = TokenTree;
302     type IntoIter = TokenTreeIter;
303 
into_iter(self) -> TokenTreeIter304     fn into_iter(self) -> TokenTreeIter {
305         match self {
306             TokenStream::Compiler(tts) => {
307                 TokenTreeIter::Compiler(tts.into_token_stream().into_iter())
308             }
309             TokenStream::Fallback(tts) => TokenTreeIter::Fallback(tts.into_iter()),
310         }
311     }
312 }
313 
314 impl Iterator for TokenTreeIter {
315     type Item = TokenTree;
316 
next(&mut self) -> Option<TokenTree>317     fn next(&mut self) -> Option<TokenTree> {
318         let token = match self {
319             TokenTreeIter::Compiler(iter) => iter.next()?,
320             TokenTreeIter::Fallback(iter) => return iter.next(),
321         };
322         Some(match token {
323             proc_macro::TokenTree::Group(tt) => crate::Group::_new(Group::Compiler(tt)).into(),
324             proc_macro::TokenTree::Punct(tt) => {
325                 let spacing = match tt.spacing() {
326                     proc_macro::Spacing::Joint => Spacing::Joint,
327                     proc_macro::Spacing::Alone => Spacing::Alone,
328                 };
329                 let mut o = Punct::new(tt.as_char(), spacing);
330                 o.set_span(crate::Span::_new(Span::Compiler(tt.span())));
331                 o.into()
332             }
333             proc_macro::TokenTree::Ident(s) => crate::Ident::_new(Ident::Compiler(s)).into(),
334             proc_macro::TokenTree::Literal(l) => crate::Literal::_new(Literal::Compiler(l)).into(),
335         })
336     }
337 
size_hint(&self) -> (usize, Option<usize>)338     fn size_hint(&self) -> (usize, Option<usize>) {
339         match self {
340             TokenTreeIter::Compiler(tts) => tts.size_hint(),
341             TokenTreeIter::Fallback(tts) => tts.size_hint(),
342         }
343     }
344 }
345 
346 #[derive(Clone, PartialEq, Eq)]
347 #[cfg(super_unstable)]
348 pub(crate) enum SourceFile {
349     Compiler(proc_macro::SourceFile),
350     Fallback(fallback::SourceFile),
351 }
352 
353 #[cfg(super_unstable)]
354 impl SourceFile {
nightly(sf: proc_macro::SourceFile) -> Self355     fn nightly(sf: proc_macro::SourceFile) -> Self {
356         SourceFile::Compiler(sf)
357     }
358 
359     /// Get the path to this source file as a string.
path(&self) -> PathBuf360     pub fn path(&self) -> PathBuf {
361         match self {
362             SourceFile::Compiler(a) => a.path(),
363             SourceFile::Fallback(a) => a.path(),
364         }
365     }
366 
is_real(&self) -> bool367     pub fn is_real(&self) -> bool {
368         match self {
369             SourceFile::Compiler(a) => a.is_real(),
370             SourceFile::Fallback(a) => a.is_real(),
371         }
372     }
373 }
374 
375 #[cfg(super_unstable)]
376 impl Debug for SourceFile {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result377     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
378         match self {
379             SourceFile::Compiler(a) => Debug::fmt(a, f),
380             SourceFile::Fallback(a) => Debug::fmt(a, f),
381         }
382     }
383 }
384 
385 #[derive(Copy, Clone)]
386 pub(crate) enum Span {
387     Compiler(proc_macro::Span),
388     Fallback(fallback::Span),
389 }
390 
391 impl Span {
call_site() -> Self392     pub fn call_site() -> Self {
393         if inside_proc_macro() {
394             Span::Compiler(proc_macro::Span::call_site())
395         } else {
396             Span::Fallback(fallback::Span::call_site())
397         }
398     }
399 
mixed_site() -> Self400     pub fn mixed_site() -> Self {
401         if inside_proc_macro() {
402             Span::Compiler(proc_macro::Span::mixed_site())
403         } else {
404             Span::Fallback(fallback::Span::mixed_site())
405         }
406     }
407 
408     #[cfg(super_unstable)]
def_site() -> Self409     pub fn def_site() -> Self {
410         if inside_proc_macro() {
411             Span::Compiler(proc_macro::Span::def_site())
412         } else {
413             Span::Fallback(fallback::Span::def_site())
414         }
415     }
416 
resolved_at(&self, other: Span) -> Span417     pub fn resolved_at(&self, other: Span) -> Span {
418         match (self, other) {
419             (Span::Compiler(a), Span::Compiler(b)) => Span::Compiler(a.resolved_at(b)),
420             (Span::Fallback(a), Span::Fallback(b)) => Span::Fallback(a.resolved_at(b)),
421             _ => mismatch(),
422         }
423     }
424 
located_at(&self, other: Span) -> Span425     pub fn located_at(&self, other: Span) -> Span {
426         match (self, other) {
427             (Span::Compiler(a), Span::Compiler(b)) => Span::Compiler(a.located_at(b)),
428             (Span::Fallback(a), Span::Fallback(b)) => Span::Fallback(a.located_at(b)),
429             _ => mismatch(),
430         }
431     }
432 
unwrap(self) -> proc_macro::Span433     pub fn unwrap(self) -> proc_macro::Span {
434         match self {
435             Span::Compiler(s) => s,
436             Span::Fallback(_) => panic!("proc_macro::Span is only available in procedural macros"),
437         }
438     }
439 
440     #[cfg(super_unstable)]
source_file(&self) -> SourceFile441     pub fn source_file(&self) -> SourceFile {
442         match self {
443             Span::Compiler(s) => SourceFile::nightly(s.source_file()),
444             Span::Fallback(s) => SourceFile::Fallback(s.source_file()),
445         }
446     }
447 
448     #[cfg(span_locations)]
start(&self) -> LineColumn449     pub fn start(&self) -> LineColumn {
450         match self {
451             Span::Compiler(_) => LineColumn { line: 0, column: 0 },
452             Span::Fallback(s) => s.start(),
453         }
454     }
455 
456     #[cfg(span_locations)]
end(&self) -> LineColumn457     pub fn end(&self) -> LineColumn {
458         match self {
459             Span::Compiler(_) => LineColumn { line: 0, column: 0 },
460             Span::Fallback(s) => s.end(),
461         }
462     }
463 
join(&self, other: Span) -> Option<Span>464     pub fn join(&self, other: Span) -> Option<Span> {
465         let ret = match (self, other) {
466             #[cfg(proc_macro_span)]
467             (Span::Compiler(a), Span::Compiler(b)) => Span::Compiler(a.join(b)?),
468             (Span::Fallback(a), Span::Fallback(b)) => Span::Fallback(a.join(b)?),
469             _ => return None,
470         };
471         Some(ret)
472     }
473 
474     #[cfg(super_unstable)]
eq(&self, other: &Span) -> bool475     pub fn eq(&self, other: &Span) -> bool {
476         match (self, other) {
477             (Span::Compiler(a), Span::Compiler(b)) => a.eq(b),
478             (Span::Fallback(a), Span::Fallback(b)) => a.eq(b),
479             _ => false,
480         }
481     }
482 
source_text(&self) -> Option<String>483     pub fn source_text(&self) -> Option<String> {
484         match self {
485             #[cfg(not(no_source_text))]
486             Span::Compiler(s) => s.source_text(),
487             #[cfg(no_source_text)]
488             Span::Compiler(_) => None,
489             Span::Fallback(s) => s.source_text(),
490         }
491     }
492 
unwrap_nightly(self) -> proc_macro::Span493     fn unwrap_nightly(self) -> proc_macro::Span {
494         match self {
495             Span::Compiler(s) => s,
496             Span::Fallback(_) => mismatch(),
497         }
498     }
499 }
500 
501 impl From<proc_macro::Span> for crate::Span {
from(proc_span: proc_macro::Span) -> Self502     fn from(proc_span: proc_macro::Span) -> Self {
503         crate::Span::_new(Span::Compiler(proc_span))
504     }
505 }
506 
507 impl From<fallback::Span> for Span {
from(inner: fallback::Span) -> Self508     fn from(inner: fallback::Span) -> Self {
509         Span::Fallback(inner)
510     }
511 }
512 
513 impl Debug for Span {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result514     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
515         match self {
516             Span::Compiler(s) => Debug::fmt(s, f),
517             Span::Fallback(s) => Debug::fmt(s, f),
518         }
519     }
520 }
521 
debug_span_field_if_nontrivial(debug: &mut fmt::DebugStruct, span: Span)522 pub(crate) fn debug_span_field_if_nontrivial(debug: &mut fmt::DebugStruct, span: Span) {
523     match span {
524         Span::Compiler(s) => {
525             debug.field("span", &s);
526         }
527         Span::Fallback(s) => fallback::debug_span_field_if_nontrivial(debug, s),
528     }
529 }
530 
531 #[derive(Clone)]
532 pub(crate) enum Group {
533     Compiler(proc_macro::Group),
534     Fallback(fallback::Group),
535 }
536 
537 impl Group {
new(delimiter: Delimiter, stream: TokenStream) -> Self538     pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self {
539         match stream {
540             TokenStream::Compiler(tts) => {
541                 let delimiter = match delimiter {
542                     Delimiter::Parenthesis => proc_macro::Delimiter::Parenthesis,
543                     Delimiter::Bracket => proc_macro::Delimiter::Bracket,
544                     Delimiter::Brace => proc_macro::Delimiter::Brace,
545                     Delimiter::None => proc_macro::Delimiter::None,
546                 };
547                 Group::Compiler(proc_macro::Group::new(delimiter, tts.into_token_stream()))
548             }
549             TokenStream::Fallback(stream) => {
550                 Group::Fallback(fallback::Group::new(delimiter, stream))
551             }
552         }
553     }
554 
delimiter(&self) -> Delimiter555     pub fn delimiter(&self) -> Delimiter {
556         match self {
557             Group::Compiler(g) => match g.delimiter() {
558                 proc_macro::Delimiter::Parenthesis => Delimiter::Parenthesis,
559                 proc_macro::Delimiter::Bracket => Delimiter::Bracket,
560                 proc_macro::Delimiter::Brace => Delimiter::Brace,
561                 proc_macro::Delimiter::None => Delimiter::None,
562             },
563             Group::Fallback(g) => g.delimiter(),
564         }
565     }
566 
stream(&self) -> TokenStream567     pub fn stream(&self) -> TokenStream {
568         match self {
569             Group::Compiler(g) => TokenStream::Compiler(DeferredTokenStream::new(g.stream())),
570             Group::Fallback(g) => TokenStream::Fallback(g.stream()),
571         }
572     }
573 
span(&self) -> Span574     pub fn span(&self) -> Span {
575         match self {
576             Group::Compiler(g) => Span::Compiler(g.span()),
577             Group::Fallback(g) => Span::Fallback(g.span()),
578         }
579     }
580 
span_open(&self) -> Span581     pub fn span_open(&self) -> Span {
582         match self {
583             Group::Compiler(g) => Span::Compiler(g.span_open()),
584             Group::Fallback(g) => Span::Fallback(g.span_open()),
585         }
586     }
587 
span_close(&self) -> Span588     pub fn span_close(&self) -> Span {
589         match self {
590             Group::Compiler(g) => Span::Compiler(g.span_close()),
591             Group::Fallback(g) => Span::Fallback(g.span_close()),
592         }
593     }
594 
set_span(&mut self, span: Span)595     pub fn set_span(&mut self, span: Span) {
596         match (self, span) {
597             (Group::Compiler(g), Span::Compiler(s)) => g.set_span(s),
598             (Group::Fallback(g), Span::Fallback(s)) => g.set_span(s),
599             _ => mismatch(),
600         }
601     }
602 
unwrap_nightly(self) -> proc_macro::Group603     fn unwrap_nightly(self) -> proc_macro::Group {
604         match self {
605             Group::Compiler(g) => g,
606             Group::Fallback(_) => mismatch(),
607         }
608     }
609 }
610 
611 impl From<fallback::Group> for Group {
from(g: fallback::Group) -> Self612     fn from(g: fallback::Group) -> Self {
613         Group::Fallback(g)
614     }
615 }
616 
617 impl Display for Group {
fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result618     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
619         match self {
620             Group::Compiler(group) => Display::fmt(group, formatter),
621             Group::Fallback(group) => Display::fmt(group, formatter),
622         }
623     }
624 }
625 
626 impl Debug for Group {
fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result627     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
628         match self {
629             Group::Compiler(group) => Debug::fmt(group, formatter),
630             Group::Fallback(group) => Debug::fmt(group, formatter),
631         }
632     }
633 }
634 
635 #[derive(Clone)]
636 pub(crate) enum Ident {
637     Compiler(proc_macro::Ident),
638     Fallback(fallback::Ident),
639 }
640 
641 impl Ident {
new(string: &str, span: Span) -> Self642     pub fn new(string: &str, span: Span) -> Self {
643         match span {
644             Span::Compiler(s) => Ident::Compiler(proc_macro::Ident::new(string, s)),
645             Span::Fallback(s) => Ident::Fallback(fallback::Ident::new(string, s)),
646         }
647     }
648 
new_raw(string: &str, span: Span) -> Self649     pub fn new_raw(string: &str, span: Span) -> Self {
650         match span {
651             Span::Compiler(s) => Ident::Compiler(proc_macro::Ident::new_raw(string, s)),
652             Span::Fallback(s) => Ident::Fallback(fallback::Ident::new_raw(string, s)),
653         }
654     }
655 
span(&self) -> Span656     pub fn span(&self) -> Span {
657         match self {
658             Ident::Compiler(t) => Span::Compiler(t.span()),
659             Ident::Fallback(t) => Span::Fallback(t.span()),
660         }
661     }
662 
set_span(&mut self, span: Span)663     pub fn set_span(&mut self, span: Span) {
664         match (self, span) {
665             (Ident::Compiler(t), Span::Compiler(s)) => t.set_span(s),
666             (Ident::Fallback(t), Span::Fallback(s)) => t.set_span(s),
667             _ => mismatch(),
668         }
669     }
670 
unwrap_nightly(self) -> proc_macro::Ident671     fn unwrap_nightly(self) -> proc_macro::Ident {
672         match self {
673             Ident::Compiler(s) => s,
674             Ident::Fallback(_) => mismatch(),
675         }
676     }
677 }
678 
679 impl PartialEq for Ident {
eq(&self, other: &Ident) -> bool680     fn eq(&self, other: &Ident) -> bool {
681         match (self, other) {
682             (Ident::Compiler(t), Ident::Compiler(o)) => t.to_string() == o.to_string(),
683             (Ident::Fallback(t), Ident::Fallback(o)) => t == o,
684             _ => mismatch(),
685         }
686     }
687 }
688 
689 impl<T> PartialEq<T> for Ident
690 where
691     T: ?Sized + AsRef<str>,
692 {
eq(&self, other: &T) -> bool693     fn eq(&self, other: &T) -> bool {
694         let other = other.as_ref();
695         match self {
696             Ident::Compiler(t) => t.to_string() == other,
697             Ident::Fallback(t) => t == other,
698         }
699     }
700 }
701 
702 impl Display for Ident {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result703     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
704         match self {
705             Ident::Compiler(t) => Display::fmt(t, f),
706             Ident::Fallback(t) => Display::fmt(t, f),
707         }
708     }
709 }
710 
711 impl Debug for Ident {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result712     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
713         match self {
714             Ident::Compiler(t) => Debug::fmt(t, f),
715             Ident::Fallback(t) => Debug::fmt(t, f),
716         }
717     }
718 }
719 
720 #[derive(Clone)]
721 pub(crate) enum Literal {
722     Compiler(proc_macro::Literal),
723     Fallback(fallback::Literal),
724 }
725 
726 macro_rules! suffixed_numbers {
727     ($($name:ident => $kind:ident,)*) => ($(
728         pub fn $name(n: $kind) -> Literal {
729             if inside_proc_macro() {
730                 Literal::Compiler(proc_macro::Literal::$name(n))
731             } else {
732                 Literal::Fallback(fallback::Literal::$name(n))
733             }
734         }
735     )*)
736 }
737 
738 macro_rules! unsuffixed_integers {
739     ($($name:ident => $kind:ident,)*) => ($(
740         pub fn $name(n: $kind) -> Literal {
741             if inside_proc_macro() {
742                 Literal::Compiler(proc_macro::Literal::$name(n))
743             } else {
744                 Literal::Fallback(fallback::Literal::$name(n))
745             }
746         }
747     )*)
748 }
749 
750 impl Literal {
from_str_unchecked(repr: &str) -> Self751     pub unsafe fn from_str_unchecked(repr: &str) -> Self {
752         if inside_proc_macro() {
753             Literal::Compiler(proc_macro::Literal::from_str(repr).expect("invalid literal"))
754         } else {
755             Literal::Fallback(fallback::Literal::from_str_unchecked(repr))
756         }
757     }
758 
759     suffixed_numbers! {
760         u8_suffixed => u8,
761         u16_suffixed => u16,
762         u32_suffixed => u32,
763         u64_suffixed => u64,
764         u128_suffixed => u128,
765         usize_suffixed => usize,
766         i8_suffixed => i8,
767         i16_suffixed => i16,
768         i32_suffixed => i32,
769         i64_suffixed => i64,
770         i128_suffixed => i128,
771         isize_suffixed => isize,
772 
773         f32_suffixed => f32,
774         f64_suffixed => f64,
775     }
776 
777     unsuffixed_integers! {
778         u8_unsuffixed => u8,
779         u16_unsuffixed => u16,
780         u32_unsuffixed => u32,
781         u64_unsuffixed => u64,
782         u128_unsuffixed => u128,
783         usize_unsuffixed => usize,
784         i8_unsuffixed => i8,
785         i16_unsuffixed => i16,
786         i32_unsuffixed => i32,
787         i64_unsuffixed => i64,
788         i128_unsuffixed => i128,
789         isize_unsuffixed => isize,
790     }
791 
f32_unsuffixed(f: f32) -> Literal792     pub fn f32_unsuffixed(f: f32) -> Literal {
793         if inside_proc_macro() {
794             Literal::Compiler(proc_macro::Literal::f32_unsuffixed(f))
795         } else {
796             Literal::Fallback(fallback::Literal::f32_unsuffixed(f))
797         }
798     }
799 
f64_unsuffixed(f: f64) -> Literal800     pub fn f64_unsuffixed(f: f64) -> Literal {
801         if inside_proc_macro() {
802             Literal::Compiler(proc_macro::Literal::f64_unsuffixed(f))
803         } else {
804             Literal::Fallback(fallback::Literal::f64_unsuffixed(f))
805         }
806     }
807 
string(t: &str) -> Literal808     pub fn string(t: &str) -> Literal {
809         if inside_proc_macro() {
810             Literal::Compiler(proc_macro::Literal::string(t))
811         } else {
812             Literal::Fallback(fallback::Literal::string(t))
813         }
814     }
815 
character(t: char) -> Literal816     pub fn character(t: char) -> Literal {
817         if inside_proc_macro() {
818             Literal::Compiler(proc_macro::Literal::character(t))
819         } else {
820             Literal::Fallback(fallback::Literal::character(t))
821         }
822     }
823 
byte_string(bytes: &[u8]) -> Literal824     pub fn byte_string(bytes: &[u8]) -> Literal {
825         if inside_proc_macro() {
826             Literal::Compiler(proc_macro::Literal::byte_string(bytes))
827         } else {
828             Literal::Fallback(fallback::Literal::byte_string(bytes))
829         }
830     }
831 
span(&self) -> Span832     pub fn span(&self) -> Span {
833         match self {
834             Literal::Compiler(lit) => Span::Compiler(lit.span()),
835             Literal::Fallback(lit) => Span::Fallback(lit.span()),
836         }
837     }
838 
set_span(&mut self, span: Span)839     pub fn set_span(&mut self, span: Span) {
840         match (self, span) {
841             (Literal::Compiler(lit), Span::Compiler(s)) => lit.set_span(s),
842             (Literal::Fallback(lit), Span::Fallback(s)) => lit.set_span(s),
843             _ => mismatch(),
844         }
845     }
846 
subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span>847     pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
848         match self {
849             #[cfg(proc_macro_span)]
850             Literal::Compiler(lit) => lit.subspan(range).map(Span::Compiler),
851             #[cfg(not(proc_macro_span))]
852             Literal::Compiler(_lit) => None,
853             Literal::Fallback(lit) => lit.subspan(range).map(Span::Fallback),
854         }
855     }
856 
unwrap_nightly(self) -> proc_macro::Literal857     fn unwrap_nightly(self) -> proc_macro::Literal {
858         match self {
859             Literal::Compiler(s) => s,
860             Literal::Fallback(_) => mismatch(),
861         }
862     }
863 }
864 
865 impl From<fallback::Literal> for Literal {
from(s: fallback::Literal) -> Self866     fn from(s: fallback::Literal) -> Self {
867         Literal::Fallback(s)
868     }
869 }
870 
871 impl FromStr for Literal {
872     type Err = LexError;
873 
from_str(repr: &str) -> Result<Self, Self::Err>874     fn from_str(repr: &str) -> Result<Self, Self::Err> {
875         if inside_proc_macro() {
876             let literal = proc_macro::Literal::from_str(repr)?;
877             Ok(Literal::Compiler(literal))
878         } else {
879             let literal = fallback::Literal::from_str(repr)?;
880             Ok(Literal::Fallback(literal))
881         }
882     }
883 }
884 
885 impl Display for Literal {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result886     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
887         match self {
888             Literal::Compiler(t) => Display::fmt(t, f),
889             Literal::Fallback(t) => Display::fmt(t, f),
890         }
891     }
892 }
893 
894 impl Debug for Literal {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result895     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
896         match self {
897             Literal::Compiler(t) => Debug::fmt(t, f),
898             Literal::Fallback(t) => Debug::fmt(t, f),
899         }
900     }
901 }
902