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::iter::FromIterator;
7 use core::ops::RangeBounds;
8 use core::str::FromStr;
9 use std::panic;
10 #[cfg(super_unstable)]
11 use std::path::PathBuf;
12
13 #[derive(Clone)]
14 pub(crate) enum TokenStream {
15 Compiler(DeferredTokenStream),
16 Fallback(fallback::TokenStream),
17 }
18
19 // Work around https://github.com/rust-lang/rust/issues/65080.
20 // In `impl Extend<TokenTree> for TokenStream` which is used heavily by quote,
21 // we hold on to the appended tokens and do proc_macro::TokenStream::extend as
22 // late as possible to batch together consecutive uses of the Extend impl.
23 #[derive(Clone)]
24 pub(crate) struct DeferredTokenStream {
25 stream: proc_macro::TokenStream,
26 extra: Vec<proc_macro::TokenTree>,
27 }
28
29 pub(crate) enum LexError {
30 Compiler(proc_macro::LexError),
31 Fallback(fallback::LexError),
32 }
33
34 impl LexError {
call_site() -> Self35 fn call_site() -> Self {
36 LexError::Fallback(fallback::LexError {
37 span: fallback::Span::call_site(),
38 })
39 }
40 }
41
mismatch() -> !42 fn mismatch() -> ! {
43 panic!("compiler/fallback mismatch")
44 }
45
46 impl DeferredTokenStream {
new(stream: proc_macro::TokenStream) -> Self47 fn new(stream: proc_macro::TokenStream) -> Self {
48 DeferredTokenStream {
49 stream,
50 extra: Vec::new(),
51 }
52 }
53
is_empty(&self) -> bool54 fn is_empty(&self) -> bool {
55 self.stream.is_empty() && self.extra.is_empty()
56 }
57
evaluate_now(&mut self)58 fn evaluate_now(&mut self) {
59 // If-check provides a fast short circuit for the common case of `extra`
60 // being empty, which saves a round trip over the proc macro bridge.
61 // Improves macro expansion time in winrt by 6% in debug mode.
62 if !self.extra.is_empty() {
63 self.stream.extend(self.extra.drain(..));
64 }
65 }
66
into_token_stream(mut self) -> proc_macro::TokenStream67 fn into_token_stream(mut self) -> proc_macro::TokenStream {
68 self.evaluate_now();
69 self.stream
70 }
71 }
72
73 impl TokenStream {
new() -> Self74 pub fn new() -> Self {
75 if inside_proc_macro() {
76 TokenStream::Compiler(DeferredTokenStream::new(proc_macro::TokenStream::new()))
77 } else {
78 TokenStream::Fallback(fallback::TokenStream::new())
79 }
80 }
81
is_empty(&self) -> bool82 pub fn is_empty(&self) -> bool {
83 match self {
84 TokenStream::Compiler(tts) => tts.is_empty(),
85 TokenStream::Fallback(tts) => tts.is_empty(),
86 }
87 }
88
unwrap_nightly(self) -> proc_macro::TokenStream89 fn unwrap_nightly(self) -> proc_macro::TokenStream {
90 match self {
91 TokenStream::Compiler(s) => s.into_token_stream(),
92 TokenStream::Fallback(_) => mismatch(),
93 }
94 }
95
unwrap_stable(self) -> fallback::TokenStream96 fn unwrap_stable(self) -> fallback::TokenStream {
97 match self {
98 TokenStream::Compiler(_) => mismatch(),
99 TokenStream::Fallback(s) => s,
100 }
101 }
102 }
103
104 impl FromStr for TokenStream {
105 type Err = LexError;
106
from_str(src: &str) -> Result<TokenStream, LexError>107 fn from_str(src: &str) -> Result<TokenStream, LexError> {
108 if inside_proc_macro() {
109 Ok(TokenStream::Compiler(DeferredTokenStream::new(
110 proc_macro_parse(src)?,
111 )))
112 } else {
113 Ok(TokenStream::Fallback(src.parse()?))
114 }
115 }
116 }
117
118 // Work around https://github.com/rust-lang/rust/issues/58736.
proc_macro_parse(src: &str) -> Result<proc_macro::TokenStream, LexError>119 fn proc_macro_parse(src: &str) -> Result<proc_macro::TokenStream, LexError> {
120 let result = panic::catch_unwind(|| src.parse().map_err(LexError::Compiler));
121 result.unwrap_or_else(|_| Err(LexError::call_site()))
122 }
123
124 impl Display for TokenStream {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result125 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
126 match self {
127 TokenStream::Compiler(tts) => Display::fmt(&tts.clone().into_token_stream(), f),
128 TokenStream::Fallback(tts) => Display::fmt(tts, f),
129 }
130 }
131 }
132
133 impl From<proc_macro::TokenStream> for TokenStream {
from(inner: proc_macro::TokenStream) -> Self134 fn from(inner: proc_macro::TokenStream) -> Self {
135 TokenStream::Compiler(DeferredTokenStream::new(inner))
136 }
137 }
138
139 impl From<TokenStream> for proc_macro::TokenStream {
from(inner: TokenStream) -> Self140 fn from(inner: TokenStream) -> Self {
141 match inner {
142 TokenStream::Compiler(inner) => inner.into_token_stream(),
143 TokenStream::Fallback(inner) => inner.to_string().parse().unwrap(),
144 }
145 }
146 }
147
148 impl From<fallback::TokenStream> for TokenStream {
from(inner: fallback::TokenStream) -> Self149 fn from(inner: fallback::TokenStream) -> Self {
150 TokenStream::Fallback(inner)
151 }
152 }
153
154 // Assumes inside_proc_macro().
into_compiler_token(token: TokenTree) -> proc_macro::TokenTree155 fn into_compiler_token(token: TokenTree) -> proc_macro::TokenTree {
156 match token {
157 TokenTree::Group(tt) => tt.inner.unwrap_nightly().into(),
158 TokenTree::Punct(tt) => {
159 let spacing = match tt.spacing() {
160 Spacing::Joint => proc_macro::Spacing::Joint,
161 Spacing::Alone => proc_macro::Spacing::Alone,
162 };
163 let mut punct = proc_macro::Punct::new(tt.as_char(), spacing);
164 punct.set_span(tt.span().inner.unwrap_nightly());
165 punct.into()
166 }
167 TokenTree::Ident(tt) => tt.inner.unwrap_nightly().into(),
168 TokenTree::Literal(tt) => tt.inner.unwrap_nightly().into(),
169 }
170 }
171
172 impl From<TokenTree> for TokenStream {
from(token: TokenTree) -> Self173 fn from(token: TokenTree) -> Self {
174 if inside_proc_macro() {
175 TokenStream::Compiler(DeferredTokenStream::new(into_compiler_token(token).into()))
176 } else {
177 TokenStream::Fallback(token.into())
178 }
179 }
180 }
181
182 impl FromIterator<TokenTree> for TokenStream {
from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self183 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
184 if inside_proc_macro() {
185 TokenStream::Compiler(DeferredTokenStream::new(
186 trees.into_iter().map(into_compiler_token).collect(),
187 ))
188 } else {
189 TokenStream::Fallback(trees.into_iter().collect())
190 }
191 }
192 }
193
194 impl FromIterator<TokenStream> for TokenStream {
from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self195 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
196 let mut streams = streams.into_iter();
197 match streams.next() {
198 Some(TokenStream::Compiler(mut first)) => {
199 first.evaluate_now();
200 first.stream.extend(streams.map(|s| match s {
201 TokenStream::Compiler(s) => s.into_token_stream(),
202 TokenStream::Fallback(_) => mismatch(),
203 }));
204 TokenStream::Compiler(first)
205 }
206 Some(TokenStream::Fallback(mut first)) => {
207 first.extend(streams.map(|s| match s {
208 TokenStream::Fallback(s) => s,
209 TokenStream::Compiler(_) => mismatch(),
210 }));
211 TokenStream::Fallback(first)
212 }
213 None => TokenStream::new(),
214 }
215 }
216 }
217
218 impl Extend<TokenTree> for TokenStream {
extend<I: IntoIterator<Item = TokenTree>>(&mut self, stream: I)219 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, stream: I) {
220 match self {
221 TokenStream::Compiler(tts) => {
222 // Here is the reason for DeferredTokenStream.
223 for token in stream {
224 tts.extra.push(into_compiler_token(token));
225 }
226 }
227 TokenStream::Fallback(tts) => tts.extend(stream),
228 }
229 }
230 }
231
232 impl Extend<TokenStream> for TokenStream {
extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I)233 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
234 match self {
235 TokenStream::Compiler(tts) => {
236 tts.evaluate_now();
237 tts.stream
238 .extend(streams.into_iter().map(TokenStream::unwrap_nightly));
239 }
240 TokenStream::Fallback(tts) => {
241 tts.extend(streams.into_iter().map(TokenStream::unwrap_stable));
242 }
243 }
244 }
245 }
246
247 impl Debug for TokenStream {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result248 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
249 match self {
250 TokenStream::Compiler(tts) => Debug::fmt(&tts.clone().into_token_stream(), f),
251 TokenStream::Fallback(tts) => Debug::fmt(tts, f),
252 }
253 }
254 }
255
256 impl LexError {
span(&self) -> Span257 pub(crate) fn span(&self) -> Span {
258 match self {
259 LexError::Compiler(_) => Span::call_site(),
260 LexError::Fallback(e) => Span::Fallback(e.span()),
261 }
262 }
263 }
264
265 impl From<proc_macro::LexError> for LexError {
from(e: proc_macro::LexError) -> Self266 fn from(e: proc_macro::LexError) -> Self {
267 LexError::Compiler(e)
268 }
269 }
270
271 impl From<fallback::LexError> for LexError {
from(e: fallback::LexError) -> Self272 fn from(e: fallback::LexError) -> Self {
273 LexError::Fallback(e)
274 }
275 }
276
277 impl Debug for LexError {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result278 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
279 match self {
280 LexError::Compiler(e) => Debug::fmt(e, f),
281 LexError::Fallback(e) => Debug::fmt(e, f),
282 }
283 }
284 }
285
286 impl Display for LexError {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result287 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
288 match self {
289 #[cfg(not(no_lexerror_display))]
290 LexError::Compiler(e) => Display::fmt(e, f),
291 #[cfg(no_lexerror_display)]
292 LexError::Compiler(_e) => Display::fmt(
293 &fallback::LexError {
294 span: fallback::Span::call_site(),
295 },
296 f,
297 ),
298 LexError::Fallback(e) => Display::fmt(e, f),
299 }
300 }
301 }
302
303 #[derive(Clone)]
304 pub(crate) enum TokenTreeIter {
305 Compiler(proc_macro::token_stream::IntoIter),
306 Fallback(fallback::TokenTreeIter),
307 }
308
309 impl IntoIterator for TokenStream {
310 type Item = TokenTree;
311 type IntoIter = TokenTreeIter;
312
into_iter(self) -> TokenTreeIter313 fn into_iter(self) -> TokenTreeIter {
314 match self {
315 TokenStream::Compiler(tts) => {
316 TokenTreeIter::Compiler(tts.into_token_stream().into_iter())
317 }
318 TokenStream::Fallback(tts) => TokenTreeIter::Fallback(tts.into_iter()),
319 }
320 }
321 }
322
323 impl Iterator for TokenTreeIter {
324 type Item = TokenTree;
325
next(&mut self) -> Option<TokenTree>326 fn next(&mut self) -> Option<TokenTree> {
327 let token = match self {
328 TokenTreeIter::Compiler(iter) => iter.next()?,
329 TokenTreeIter::Fallback(iter) => return iter.next(),
330 };
331 Some(match token {
332 proc_macro::TokenTree::Group(tt) => crate::Group::_new(Group::Compiler(tt)).into(),
333 proc_macro::TokenTree::Punct(tt) => {
334 let spacing = match tt.spacing() {
335 proc_macro::Spacing::Joint => Spacing::Joint,
336 proc_macro::Spacing::Alone => Spacing::Alone,
337 };
338 let mut o = Punct::new(tt.as_char(), spacing);
339 o.set_span(crate::Span::_new(Span::Compiler(tt.span())));
340 o.into()
341 }
342 proc_macro::TokenTree::Ident(s) => crate::Ident::_new(Ident::Compiler(s)).into(),
343 proc_macro::TokenTree::Literal(l) => crate::Literal::_new(Literal::Compiler(l)).into(),
344 })
345 }
346
size_hint(&self) -> (usize, Option<usize>)347 fn size_hint(&self) -> (usize, Option<usize>) {
348 match self {
349 TokenTreeIter::Compiler(tts) => tts.size_hint(),
350 TokenTreeIter::Fallback(tts) => tts.size_hint(),
351 }
352 }
353 }
354
355 #[derive(Clone, PartialEq, Eq)]
356 #[cfg(super_unstable)]
357 pub(crate) enum SourceFile {
358 Compiler(proc_macro::SourceFile),
359 Fallback(fallback::SourceFile),
360 }
361
362 #[cfg(super_unstable)]
363 impl SourceFile {
nightly(sf: proc_macro::SourceFile) -> Self364 fn nightly(sf: proc_macro::SourceFile) -> Self {
365 SourceFile::Compiler(sf)
366 }
367
368 /// Get the path to this source file as a string.
path(&self) -> PathBuf369 pub fn path(&self) -> PathBuf {
370 match self {
371 SourceFile::Compiler(a) => a.path(),
372 SourceFile::Fallback(a) => a.path(),
373 }
374 }
375
is_real(&self) -> bool376 pub fn is_real(&self) -> bool {
377 match self {
378 SourceFile::Compiler(a) => a.is_real(),
379 SourceFile::Fallback(a) => a.is_real(),
380 }
381 }
382 }
383
384 #[cfg(super_unstable)]
385 impl Debug for SourceFile {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result386 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
387 match self {
388 SourceFile::Compiler(a) => Debug::fmt(a, f),
389 SourceFile::Fallback(a) => Debug::fmt(a, f),
390 }
391 }
392 }
393
394 #[derive(Copy, Clone)]
395 pub(crate) enum Span {
396 Compiler(proc_macro::Span),
397 Fallback(fallback::Span),
398 }
399
400 impl Span {
call_site() -> Self401 pub fn call_site() -> Self {
402 if inside_proc_macro() {
403 Span::Compiler(proc_macro::Span::call_site())
404 } else {
405 Span::Fallback(fallback::Span::call_site())
406 }
407 }
408
409 #[cfg(not(no_hygiene))]
mixed_site() -> Self410 pub fn mixed_site() -> Self {
411 if inside_proc_macro() {
412 Span::Compiler(proc_macro::Span::mixed_site())
413 } else {
414 Span::Fallback(fallback::Span::mixed_site())
415 }
416 }
417
418 #[cfg(super_unstable)]
def_site() -> Self419 pub fn def_site() -> Self {
420 if inside_proc_macro() {
421 Span::Compiler(proc_macro::Span::def_site())
422 } else {
423 Span::Fallback(fallback::Span::def_site())
424 }
425 }
426
resolved_at(&self, other: Span) -> Span427 pub fn resolved_at(&self, other: Span) -> Span {
428 match (self, other) {
429 #[cfg(not(no_hygiene))]
430 (Span::Compiler(a), Span::Compiler(b)) => Span::Compiler(a.resolved_at(b)),
431
432 // Name resolution affects semantics, but location is only cosmetic
433 #[cfg(no_hygiene)]
434 (Span::Compiler(_), Span::Compiler(_)) => other,
435
436 (Span::Fallback(a), Span::Fallback(b)) => Span::Fallback(a.resolved_at(b)),
437 _ => mismatch(),
438 }
439 }
440
located_at(&self, other: Span) -> Span441 pub fn located_at(&self, other: Span) -> Span {
442 match (self, other) {
443 #[cfg(not(no_hygiene))]
444 (Span::Compiler(a), Span::Compiler(b)) => Span::Compiler(a.located_at(b)),
445
446 // Name resolution affects semantics, but location is only cosmetic
447 #[cfg(no_hygiene)]
448 (Span::Compiler(_), Span::Compiler(_)) => *self,
449
450 (Span::Fallback(a), Span::Fallback(b)) => Span::Fallback(a.located_at(b)),
451 _ => mismatch(),
452 }
453 }
454
unwrap(self) -> proc_macro::Span455 pub fn unwrap(self) -> proc_macro::Span {
456 match self {
457 Span::Compiler(s) => s,
458 Span::Fallback(_) => panic!("proc_macro::Span is only available in procedural macros"),
459 }
460 }
461
462 #[cfg(super_unstable)]
source_file(&self) -> SourceFile463 pub fn source_file(&self) -> SourceFile {
464 match self {
465 Span::Compiler(s) => SourceFile::nightly(s.source_file()),
466 Span::Fallback(s) => SourceFile::Fallback(s.source_file()),
467 }
468 }
469
470 #[cfg(span_locations)]
start(&self) -> LineColumn471 pub fn start(&self) -> LineColumn {
472 match self {
473 #[cfg(proc_macro_span)]
474 Span::Compiler(s) => {
475 let proc_macro::LineColumn { line, column } = s.start();
476 LineColumn { line, column }
477 }
478 #[cfg(not(proc_macro_span))]
479 Span::Compiler(_) => LineColumn { line: 0, column: 0 },
480 Span::Fallback(s) => s.start(),
481 }
482 }
483
484 #[cfg(span_locations)]
end(&self) -> LineColumn485 pub fn end(&self) -> LineColumn {
486 match self {
487 #[cfg(proc_macro_span)]
488 Span::Compiler(s) => {
489 let proc_macro::LineColumn { line, column } = s.end();
490 LineColumn { line, column }
491 }
492 #[cfg(not(proc_macro_span))]
493 Span::Compiler(_) => LineColumn { line: 0, column: 0 },
494 Span::Fallback(s) => s.end(),
495 }
496 }
497
498 #[cfg(super_unstable)]
before(&self) -> Span499 pub fn before(&self) -> Span {
500 match self {
501 Span::Compiler(s) => Span::Compiler(s.before()),
502 Span::Fallback(s) => Span::Fallback(s.before()),
503 }
504 }
505
506 #[cfg(super_unstable)]
after(&self) -> Span507 pub fn after(&self) -> Span {
508 match self {
509 Span::Compiler(s) => Span::Compiler(s.after()),
510 Span::Fallback(s) => Span::Fallback(s.after()),
511 }
512 }
513
join(&self, other: Span) -> Option<Span>514 pub fn join(&self, other: Span) -> Option<Span> {
515 let ret = match (self, other) {
516 #[cfg(proc_macro_span)]
517 (Span::Compiler(a), Span::Compiler(b)) => Span::Compiler(a.join(b)?),
518 (Span::Fallback(a), Span::Fallback(b)) => Span::Fallback(a.join(b)?),
519 _ => return None,
520 };
521 Some(ret)
522 }
523
524 #[cfg(super_unstable)]
eq(&self, other: &Span) -> bool525 pub fn eq(&self, other: &Span) -> bool {
526 match (self, other) {
527 (Span::Compiler(a), Span::Compiler(b)) => a.eq(b),
528 (Span::Fallback(a), Span::Fallback(b)) => a.eq(b),
529 _ => false,
530 }
531 }
532
source_text(&self) -> Option<String>533 pub fn source_text(&self) -> Option<String> {
534 match self {
535 #[cfg(not(no_source_text))]
536 Span::Compiler(s) => s.source_text(),
537 #[cfg(no_source_text)]
538 Span::Compiler(_) => None,
539 Span::Fallback(s) => s.source_text(),
540 }
541 }
542
unwrap_nightly(self) -> proc_macro::Span543 fn unwrap_nightly(self) -> proc_macro::Span {
544 match self {
545 Span::Compiler(s) => s,
546 Span::Fallback(_) => mismatch(),
547 }
548 }
549 }
550
551 impl From<proc_macro::Span> for crate::Span {
from(proc_span: proc_macro::Span) -> Self552 fn from(proc_span: proc_macro::Span) -> Self {
553 crate::Span::_new(Span::Compiler(proc_span))
554 }
555 }
556
557 impl From<fallback::Span> for Span {
from(inner: fallback::Span) -> Self558 fn from(inner: fallback::Span) -> Self {
559 Span::Fallback(inner)
560 }
561 }
562
563 impl Debug for Span {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result564 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
565 match self {
566 Span::Compiler(s) => Debug::fmt(s, f),
567 Span::Fallback(s) => Debug::fmt(s, f),
568 }
569 }
570 }
571
debug_span_field_if_nontrivial(debug: &mut fmt::DebugStruct, span: Span)572 pub(crate) fn debug_span_field_if_nontrivial(debug: &mut fmt::DebugStruct, span: Span) {
573 match span {
574 Span::Compiler(s) => {
575 debug.field("span", &s);
576 }
577 Span::Fallback(s) => fallback::debug_span_field_if_nontrivial(debug, s),
578 }
579 }
580
581 #[derive(Clone)]
582 pub(crate) enum Group {
583 Compiler(proc_macro::Group),
584 Fallback(fallback::Group),
585 }
586
587 impl Group {
new(delimiter: Delimiter, stream: TokenStream) -> Self588 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self {
589 match stream {
590 TokenStream::Compiler(tts) => {
591 let delimiter = match delimiter {
592 Delimiter::Parenthesis => proc_macro::Delimiter::Parenthesis,
593 Delimiter::Bracket => proc_macro::Delimiter::Bracket,
594 Delimiter::Brace => proc_macro::Delimiter::Brace,
595 Delimiter::None => proc_macro::Delimiter::None,
596 };
597 Group::Compiler(proc_macro::Group::new(delimiter, tts.into_token_stream()))
598 }
599 TokenStream::Fallback(stream) => {
600 Group::Fallback(fallback::Group::new(delimiter, stream))
601 }
602 }
603 }
604
delimiter(&self) -> Delimiter605 pub fn delimiter(&self) -> Delimiter {
606 match self {
607 Group::Compiler(g) => match g.delimiter() {
608 proc_macro::Delimiter::Parenthesis => Delimiter::Parenthesis,
609 proc_macro::Delimiter::Bracket => Delimiter::Bracket,
610 proc_macro::Delimiter::Brace => Delimiter::Brace,
611 proc_macro::Delimiter::None => Delimiter::None,
612 },
613 Group::Fallback(g) => g.delimiter(),
614 }
615 }
616
stream(&self) -> TokenStream617 pub fn stream(&self) -> TokenStream {
618 match self {
619 Group::Compiler(g) => TokenStream::Compiler(DeferredTokenStream::new(g.stream())),
620 Group::Fallback(g) => TokenStream::Fallback(g.stream()),
621 }
622 }
623
span(&self) -> Span624 pub fn span(&self) -> Span {
625 match self {
626 Group::Compiler(g) => Span::Compiler(g.span()),
627 Group::Fallback(g) => Span::Fallback(g.span()),
628 }
629 }
630
span_open(&self) -> Span631 pub fn span_open(&self) -> Span {
632 match self {
633 #[cfg(not(no_group_open_close))]
634 Group::Compiler(g) => Span::Compiler(g.span_open()),
635 #[cfg(no_group_open_close)]
636 Group::Compiler(g) => Span::Compiler(g.span()),
637 Group::Fallback(g) => Span::Fallback(g.span_open()),
638 }
639 }
640
span_close(&self) -> Span641 pub fn span_close(&self) -> Span {
642 match self {
643 #[cfg(not(no_group_open_close))]
644 Group::Compiler(g) => Span::Compiler(g.span_close()),
645 #[cfg(no_group_open_close)]
646 Group::Compiler(g) => Span::Compiler(g.span()),
647 Group::Fallback(g) => Span::Fallback(g.span_close()),
648 }
649 }
650
set_span(&mut self, span: Span)651 pub fn set_span(&mut self, span: Span) {
652 match (self, span) {
653 (Group::Compiler(g), Span::Compiler(s)) => g.set_span(s),
654 (Group::Fallback(g), Span::Fallback(s)) => g.set_span(s),
655 _ => mismatch(),
656 }
657 }
658
unwrap_nightly(self) -> proc_macro::Group659 fn unwrap_nightly(self) -> proc_macro::Group {
660 match self {
661 Group::Compiler(g) => g,
662 Group::Fallback(_) => mismatch(),
663 }
664 }
665 }
666
667 impl From<fallback::Group> for Group {
from(g: fallback::Group) -> Self668 fn from(g: fallback::Group) -> Self {
669 Group::Fallback(g)
670 }
671 }
672
673 impl Display for Group {
fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result674 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
675 match self {
676 Group::Compiler(group) => Display::fmt(group, formatter),
677 Group::Fallback(group) => Display::fmt(group, formatter),
678 }
679 }
680 }
681
682 impl Debug for Group {
fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result683 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
684 match self {
685 Group::Compiler(group) => Debug::fmt(group, formatter),
686 Group::Fallback(group) => Debug::fmt(group, formatter),
687 }
688 }
689 }
690
691 #[derive(Clone)]
692 pub(crate) enum Ident {
693 Compiler(proc_macro::Ident),
694 Fallback(fallback::Ident),
695 }
696
697 impl Ident {
new(string: &str, span: Span) -> Self698 pub fn new(string: &str, span: Span) -> Self {
699 match span {
700 Span::Compiler(s) => Ident::Compiler(proc_macro::Ident::new(string, s)),
701 Span::Fallback(s) => Ident::Fallback(fallback::Ident::new(string, s)),
702 }
703 }
704
new_raw(string: &str, span: Span) -> Self705 pub fn new_raw(string: &str, span: Span) -> Self {
706 match span {
707 #[cfg(not(no_ident_new_raw))]
708 Span::Compiler(s) => Ident::Compiler(proc_macro::Ident::new_raw(string, s)),
709 #[cfg(no_ident_new_raw)]
710 Span::Compiler(s) => {
711 let _ = proc_macro::Ident::new(string, s);
712 // At this point the un-r#-prefixed string is known to be a
713 // valid identifier. Try to produce a valid raw identifier by
714 // running the `TokenStream` parser, and unwrapping the first
715 // token as an `Ident`.
716 let raw_prefixed = format!("r#{}", string);
717 if let Ok(ts) = raw_prefixed.parse::<proc_macro::TokenStream>() {
718 let mut iter = ts.into_iter();
719 if let (Some(proc_macro::TokenTree::Ident(mut id)), None) =
720 (iter.next(), iter.next())
721 {
722 id.set_span(s);
723 return Ident::Compiler(id);
724 }
725 }
726 panic!("not allowed as a raw identifier: `{}`", raw_prefixed)
727 }
728 Span::Fallback(s) => Ident::Fallback(fallback::Ident::new_raw(string, s)),
729 }
730 }
731
span(&self) -> Span732 pub fn span(&self) -> Span {
733 match self {
734 Ident::Compiler(t) => Span::Compiler(t.span()),
735 Ident::Fallback(t) => Span::Fallback(t.span()),
736 }
737 }
738
set_span(&mut self, span: Span)739 pub fn set_span(&mut self, span: Span) {
740 match (self, span) {
741 (Ident::Compiler(t), Span::Compiler(s)) => t.set_span(s),
742 (Ident::Fallback(t), Span::Fallback(s)) => t.set_span(s),
743 _ => mismatch(),
744 }
745 }
746
unwrap_nightly(self) -> proc_macro::Ident747 fn unwrap_nightly(self) -> proc_macro::Ident {
748 match self {
749 Ident::Compiler(s) => s,
750 Ident::Fallback(_) => mismatch(),
751 }
752 }
753 }
754
755 impl PartialEq for Ident {
eq(&self, other: &Ident) -> bool756 fn eq(&self, other: &Ident) -> bool {
757 match (self, other) {
758 (Ident::Compiler(t), Ident::Compiler(o)) => t.to_string() == o.to_string(),
759 (Ident::Fallback(t), Ident::Fallback(o)) => t == o,
760 _ => mismatch(),
761 }
762 }
763 }
764
765 impl<T> PartialEq<T> for Ident
766 where
767 T: ?Sized + AsRef<str>,
768 {
eq(&self, other: &T) -> bool769 fn eq(&self, other: &T) -> bool {
770 let other = other.as_ref();
771 match self {
772 Ident::Compiler(t) => t.to_string() == other,
773 Ident::Fallback(t) => t == other,
774 }
775 }
776 }
777
778 impl Display for Ident {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result779 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
780 match self {
781 Ident::Compiler(t) => Display::fmt(t, f),
782 Ident::Fallback(t) => Display::fmt(t, f),
783 }
784 }
785 }
786
787 impl Debug for Ident {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result788 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
789 match self {
790 Ident::Compiler(t) => Debug::fmt(t, f),
791 Ident::Fallback(t) => Debug::fmt(t, f),
792 }
793 }
794 }
795
796 #[derive(Clone)]
797 pub(crate) enum Literal {
798 Compiler(proc_macro::Literal),
799 Fallback(fallback::Literal),
800 }
801
802 macro_rules! suffixed_numbers {
803 ($($name:ident => $kind:ident,)*) => ($(
804 pub fn $name(n: $kind) -> Literal {
805 if inside_proc_macro() {
806 Literal::Compiler(proc_macro::Literal::$name(n))
807 } else {
808 Literal::Fallback(fallback::Literal::$name(n))
809 }
810 }
811 )*)
812 }
813
814 macro_rules! unsuffixed_integers {
815 ($($name:ident => $kind:ident,)*) => ($(
816 pub fn $name(n: $kind) -> Literal {
817 if inside_proc_macro() {
818 Literal::Compiler(proc_macro::Literal::$name(n))
819 } else {
820 Literal::Fallback(fallback::Literal::$name(n))
821 }
822 }
823 )*)
824 }
825
826 impl Literal {
from_str_unchecked(repr: &str) -> Self827 pub unsafe fn from_str_unchecked(repr: &str) -> Self {
828 if inside_proc_macro() {
829 Literal::Compiler(compiler_literal_from_str(repr).expect("invalid literal"))
830 } else {
831 Literal::Fallback(fallback::Literal::from_str_unchecked(repr))
832 }
833 }
834
835 suffixed_numbers! {
836 u8_suffixed => u8,
837 u16_suffixed => u16,
838 u32_suffixed => u32,
839 u64_suffixed => u64,
840 u128_suffixed => u128,
841 usize_suffixed => usize,
842 i8_suffixed => i8,
843 i16_suffixed => i16,
844 i32_suffixed => i32,
845 i64_suffixed => i64,
846 i128_suffixed => i128,
847 isize_suffixed => isize,
848
849 f32_suffixed => f32,
850 f64_suffixed => f64,
851 }
852
853 unsuffixed_integers! {
854 u8_unsuffixed => u8,
855 u16_unsuffixed => u16,
856 u32_unsuffixed => u32,
857 u64_unsuffixed => u64,
858 u128_unsuffixed => u128,
859 usize_unsuffixed => usize,
860 i8_unsuffixed => i8,
861 i16_unsuffixed => i16,
862 i32_unsuffixed => i32,
863 i64_unsuffixed => i64,
864 i128_unsuffixed => i128,
865 isize_unsuffixed => isize,
866 }
867
f32_unsuffixed(f: f32) -> Literal868 pub fn f32_unsuffixed(f: f32) -> Literal {
869 if inside_proc_macro() {
870 Literal::Compiler(proc_macro::Literal::f32_unsuffixed(f))
871 } else {
872 Literal::Fallback(fallback::Literal::f32_unsuffixed(f))
873 }
874 }
875
f64_unsuffixed(f: f64) -> Literal876 pub fn f64_unsuffixed(f: f64) -> Literal {
877 if inside_proc_macro() {
878 Literal::Compiler(proc_macro::Literal::f64_unsuffixed(f))
879 } else {
880 Literal::Fallback(fallback::Literal::f64_unsuffixed(f))
881 }
882 }
883
string(t: &str) -> Literal884 pub fn string(t: &str) -> Literal {
885 if inside_proc_macro() {
886 Literal::Compiler(proc_macro::Literal::string(t))
887 } else {
888 Literal::Fallback(fallback::Literal::string(t))
889 }
890 }
891
character(t: char) -> Literal892 pub fn character(t: char) -> Literal {
893 if inside_proc_macro() {
894 Literal::Compiler(proc_macro::Literal::character(t))
895 } else {
896 Literal::Fallback(fallback::Literal::character(t))
897 }
898 }
899
byte_string(bytes: &[u8]) -> Literal900 pub fn byte_string(bytes: &[u8]) -> Literal {
901 if inside_proc_macro() {
902 Literal::Compiler(proc_macro::Literal::byte_string(bytes))
903 } else {
904 Literal::Fallback(fallback::Literal::byte_string(bytes))
905 }
906 }
907
span(&self) -> Span908 pub fn span(&self) -> Span {
909 match self {
910 Literal::Compiler(lit) => Span::Compiler(lit.span()),
911 Literal::Fallback(lit) => Span::Fallback(lit.span()),
912 }
913 }
914
set_span(&mut self, span: Span)915 pub fn set_span(&mut self, span: Span) {
916 match (self, span) {
917 (Literal::Compiler(lit), Span::Compiler(s)) => lit.set_span(s),
918 (Literal::Fallback(lit), Span::Fallback(s)) => lit.set_span(s),
919 _ => mismatch(),
920 }
921 }
922
subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span>923 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
924 match self {
925 #[cfg(proc_macro_span)]
926 Literal::Compiler(lit) => lit.subspan(range).map(Span::Compiler),
927 #[cfg(not(proc_macro_span))]
928 Literal::Compiler(_lit) => None,
929 Literal::Fallback(lit) => lit.subspan(range).map(Span::Fallback),
930 }
931 }
932
unwrap_nightly(self) -> proc_macro::Literal933 fn unwrap_nightly(self) -> proc_macro::Literal {
934 match self {
935 Literal::Compiler(s) => s,
936 Literal::Fallback(_) => mismatch(),
937 }
938 }
939 }
940
941 impl From<fallback::Literal> for Literal {
from(s: fallback::Literal) -> Self942 fn from(s: fallback::Literal) -> Self {
943 Literal::Fallback(s)
944 }
945 }
946
947 impl FromStr for Literal {
948 type Err = LexError;
949
from_str(repr: &str) -> Result<Self, Self::Err>950 fn from_str(repr: &str) -> Result<Self, Self::Err> {
951 if inside_proc_macro() {
952 compiler_literal_from_str(repr).map(Literal::Compiler)
953 } else {
954 let literal = fallback::Literal::from_str(repr)?;
955 Ok(Literal::Fallback(literal))
956 }
957 }
958 }
959
compiler_literal_from_str(repr: &str) -> Result<proc_macro::Literal, LexError>960 fn compiler_literal_from_str(repr: &str) -> Result<proc_macro::Literal, LexError> {
961 #[cfg(not(no_literal_from_str))]
962 {
963 proc_macro::Literal::from_str(repr).map_err(LexError::Compiler)
964 }
965 #[cfg(no_literal_from_str)]
966 {
967 let tokens = proc_macro_parse(repr)?;
968 let mut iter = tokens.into_iter();
969 if let (Some(proc_macro::TokenTree::Literal(literal)), None) = (iter.next(), iter.next()) {
970 if literal.to_string().len() == repr.len() {
971 return Ok(literal);
972 }
973 }
974 Err(LexError::call_site())
975 }
976 }
977
978 impl Display for Literal {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result979 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
980 match self {
981 Literal::Compiler(t) => Display::fmt(t, f),
982 Literal::Fallback(t) => Display::fmt(t, f),
983 }
984 }
985 }
986
987 impl Debug for Literal {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result988 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
989 match self {
990 Literal::Compiler(t) => Debug::fmt(t, f),
991 Literal::Fallback(t) => Debug::fmt(t, f),
992 }
993 }
994 }
995