1use std::ops::{Bound, Range};
2
3use ast::token::IdentIsRaw;
4use rustc_ast as ast;
5use rustc_ast::token;
6use rustc_ast::tokenstream::{self, DelimSpacing, Spacing, TokenStream};
7use rustc_ast::util::literal::escape_byte_str_symbol;
8use rustc_ast_pretty::pprust;
9use rustc_data_structures::fx::FxHashMap;
10use rustc_errors::{Diag, ErrorGuaranteed, MultiSpan};
11use rustc_parse::lexer::{StripTokens, nfc_normalize};
12use rustc_parse::parser::Parser;
13use rustc_parse::{exp, new_parser_from_source_str, source_str_to_stream, unwrap_or_emit_fatal};
14use rustc_proc_macro::bridge::{
15 DelimSpan, Diagnostic, ExpnGlobals, Group, Ident, LitKind, Literal, Punct, TokenTree, server,
16};
17use rustc_proc_macro::{Delimiter, Level};
18use rustc_session::parse::ParseSess;
19use rustc_span::def_id::CrateNum;
20use rustc_span::{BytePos, FileName, Pos, Span, Symbol, sym};
21use smallvec::{SmallVec, smallvec};
22
23use crate::base::ExtCtxt;
24
25trait FromInternal<T> {
26 fn from_internal(x: T) -> Self;
27}
28
29trait ToInternal<T> {
30 fn to_internal(self) -> T;
31}
32
33impl FromInternal<token::Delimiter> for Delimiter {
34 fn from_internal(delim: token::Delimiter) -> Delimiter {
35 match delim {
36 token::Delimiter::Parenthesis => Delimiter::Parenthesis,
37 token::Delimiter::Brace => Delimiter::Brace,
38 token::Delimiter::Bracket => Delimiter::Bracket,
39 token::Delimiter::Invisible(_) => Delimiter::None,
40 }
41 }
42}
43
44impl ToInternal<token::Delimiter> for Delimiter {
45 fn to_internal(self) -> token::Delimiter {
46 match self {
47 Delimiter::Parenthesis => token::Delimiter::Parenthesis,
48 Delimiter::Brace => token::Delimiter::Brace,
49 Delimiter::Bracket => token::Delimiter::Bracket,
50 Delimiter::None => token::Delimiter::Invisible(token::InvisibleOrigin::ProcMacro),
51 }
52 }
53}
54
55impl FromInternal<token::LitKind> for LitKind {
56 fn from_internal(kind: token::LitKind) -> Self {
57 match kind {
58 token::Byte => LitKind::Byte,
59 token::Char => LitKind::Char,
60 token::Integer => LitKind::Integer,
61 token::Float => LitKind::Float,
62 token::Str => LitKind::Str,
63 token::StrRaw(n) => LitKind::StrRaw(n),
64 token::ByteStr => LitKind::ByteStr,
65 token::ByteStrRaw(n) => LitKind::ByteStrRaw(n),
66 token::CStr => LitKind::CStr,
67 token::CStrRaw(n) => LitKind::CStrRaw(n),
68 token::Err(_guar) => {
69 LitKind::ErrWithGuar
73 }
74 token::Bool => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
75 }
76 }
77}
78
79impl ToInternal<token::LitKind> for LitKind {
80 fn to_internal(self) -> token::LitKind {
81 match self {
82 LitKind::Byte => token::Byte,
83 LitKind::Char => token::Char,
84 LitKind::Integer => token::Integer,
85 LitKind::Float => token::Float,
86 LitKind::Str => token::Str,
87 LitKind::StrRaw(n) => token::StrRaw(n),
88 LitKind::ByteStr => token::ByteStr,
89 LitKind::ByteStrRaw(n) => token::ByteStrRaw(n),
90 LitKind::CStr => token::CStr,
91 LitKind::CStrRaw(n) => token::CStrRaw(n),
92 LitKind::ErrWithGuar => {
93 #[allow(deprecated)]
99 let guar = ErrorGuaranteed::unchecked_error_guaranteed();
100 token::Err(guar)
101 }
102 }
103 }
104}
105
106impl FromInternal<TokenStream> for Vec<TokenTree<TokenStream, Span, Symbol>> {
107 fn from_internal(stream: TokenStream) -> Self {
108 use rustc_ast::token::*;
109
110 let mut trees = Vec::with_capacity(stream.len().next_power_of_two());
113 let mut iter = stream.iter();
114
115 while let Some(tree) = iter.next() {
116 let (Token { kind, span }, joint) = match tree.clone() {
117 tokenstream::TokenTree::Delimited(span, _, mut delim, mut stream) => {
118 while let Delimiter::Invisible(InvisibleOrigin::MetaVar(_)) = delim {
123 if stream.len() == 1
124 && let tree = stream.iter().next().unwrap()
125 && let tokenstream::TokenTree::Delimited(_, _, delim2, stream2) = tree
126 && let Delimiter::Invisible(InvisibleOrigin::MetaVar(_)) = delim2
127 {
128 delim = *delim2;
129 stream = stream2.clone();
130 } else {
131 break;
132 }
133 }
134
135 trees.push(TokenTree::Group(Group {
136 delimiter: rustc_proc_macro::Delimiter::from_internal(delim),
137 stream: Some(stream),
138 span: DelimSpan {
139 open: span.open,
140 close: span.close,
141 entire: span.entire(),
142 },
143 }));
144 continue;
145 }
146 tokenstream::TokenTree::Token(token, spacing) => {
147 let joint = match spacing {
157 Spacing::Alone | Spacing::JointHidden => false,
158 Spacing::Joint => true,
159 };
160 (token, joint)
161 }
162 };
163
164 let mut op = |s: &str| {
168 if !s.is_ascii() {
::core::panicking::panic("assertion failed: s.is_ascii()")
};assert!(s.is_ascii());
169 trees.extend(s.bytes().enumerate().map(|(i, ch)| {
170 let is_final = i == s.len() - 1;
171 let span = if (span.hi() - span.lo()).to_usize() == s.len() {
177 let lo = span.lo() + BytePos::from_usize(i);
178 let hi = lo + BytePos::from_usize(1);
179 span.with_lo(lo).with_hi(hi)
180 } else {
181 span
182 };
183 let joint = if is_final { joint } else { true };
184 TokenTree::Punct(Punct { ch, joint, span })
185 }));
186 };
187
188 match kind {
189 Eq => op("="),
190 Lt => op("<"),
191 Le => op("<="),
192 EqEq => op("=="),
193 Ne => op("!="),
194 Ge => op(">="),
195 Gt => op(">"),
196 AndAnd => op("&&"),
197 OrOr => op("||"),
198 Bang => op("!"),
199 Tilde => op("~"),
200 Plus => op("+"),
201 Minus => op("-"),
202 Star => op("*"),
203 Slash => op("/"),
204 Percent => op("%"),
205 Caret => op("^"),
206 And => op("&"),
207 Or => op("|"),
208 Shl => op("<<"),
209 Shr => op(">>"),
210 PlusEq => op("+="),
211 MinusEq => op("-="),
212 StarEq => op("*="),
213 SlashEq => op("/="),
214 PercentEq => op("%="),
215 CaretEq => op("^="),
216 AndEq => op("&="),
217 OrEq => op("|="),
218 ShlEq => op("<<="),
219 ShrEq => op(">>="),
220 At => op("@"),
221 Dot => op("."),
222 DotDot => op(".."),
223 DotDotDot => op("..."),
224 DotDotEq => op("..="),
225 Comma => op(","),
226 Semi => op(";"),
227 Colon => op(":"),
228 PathSep => op("::"),
229 RArrow => op("->"),
230 LArrow => op("<-"),
231 FatArrow => op("=>"),
232 Pound => op("#"),
233 Dollar => op("$"),
234 Question => op("?"),
235 SingleQuote => op("'"),
236
237 Ident(sym, is_raw) => trees.push(TokenTree::Ident(Ident {
238 sym,
239 is_raw: #[allow(non_exhaustive_omitted_patterns)] match is_raw {
IdentIsRaw::Yes => true,
_ => false,
}matches!(is_raw, IdentIsRaw::Yes),
240 span,
241 })),
242 NtIdent(ident, is_raw) => trees.push(TokenTree::Ident(Ident {
243 sym: ident.name,
244 is_raw: #[allow(non_exhaustive_omitted_patterns)] match is_raw {
IdentIsRaw::Yes => true,
_ => false,
}matches!(is_raw, IdentIsRaw::Yes),
245 span: ident.span,
246 })),
247
248 Lifetime(name, is_raw) => {
249 let ident = rustc_span::Ident::new(name, span).without_first_quote();
250 trees.extend([
251 TokenTree::Punct(Punct { ch: b'\'', joint: true, span }),
252 TokenTree::Ident(Ident {
253 sym: ident.name,
254 is_raw: #[allow(non_exhaustive_omitted_patterns)] match is_raw {
IdentIsRaw::Yes => true,
_ => false,
}matches!(is_raw, IdentIsRaw::Yes),
255 span,
256 }),
257 ]);
258 }
259 NtLifetime(ident, is_raw) => {
260 let stream =
261 TokenStream::token_alone(token::Lifetime(ident.name, is_raw), ident.span);
262 trees.push(TokenTree::Group(Group {
263 delimiter: rustc_proc_macro::Delimiter::None,
264 stream: Some(stream),
265 span: DelimSpan::from_single(span),
266 }))
267 }
268
269 Literal(token::Lit { kind, symbol, suffix }) => {
270 trees.push(TokenTree::Literal(self::Literal {
271 kind: FromInternal::from_internal(kind),
272 symbol,
273 suffix,
274 span,
275 }));
276 }
277 DocComment(_, attr_style, data) => {
278 let mut escaped = String::new();
279 for ch in data.as_str().chars() {
280 escaped.extend(ch.escape_debug());
281 }
282 let stream = [
283 Ident(sym::doc, IdentIsRaw::No),
284 Eq,
285 TokenKind::lit(token::Str, Symbol::intern(&escaped), None),
286 ]
287 .into_iter()
288 .map(|kind| tokenstream::TokenTree::token_alone(kind, span))
289 .collect();
290 trees.push(TokenTree::Punct(Punct { ch: b'#', joint: false, span }));
291 if attr_style == ast::AttrStyle::Inner {
292 trees.push(TokenTree::Punct(Punct { ch: b'!', joint: false, span }));
293 }
294 trees.push(TokenTree::Group(Group {
295 delimiter: rustc_proc_macro::Delimiter::Bracket,
296 stream: Some(stream),
297 span: DelimSpan::from_single(span),
298 }));
299 }
300
301 OpenParen | CloseParen | OpenBrace | CloseBrace | OpenBracket | CloseBracket
302 | OpenInvisible(_) | CloseInvisible(_) | Eof => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
303 }
304 }
305 trees
306 }
307}
308
309impl ToInternal<SmallVec<[tokenstream::TokenTree; 2]>>
311 for (TokenTree<TokenStream, Span, Symbol>, &mut Rustc<'_, '_>)
312{
313 fn to_internal(self) -> SmallVec<[tokenstream::TokenTree; 2]> {
314 use rustc_ast::token::*;
315
316 let (tree, rustc) = self;
322 match tree {
323 TokenTree::Punct(Punct { ch, joint, span }) => {
324 let kind = match ch {
325 b'=' => Eq,
326 b'<' => Lt,
327 b'>' => Gt,
328 b'!' => Bang,
329 b'~' => Tilde,
330 b'+' => Plus,
331 b'-' => Minus,
332 b'*' => Star,
333 b'/' => Slash,
334 b'%' => Percent,
335 b'^' => Caret,
336 b'&' => And,
337 b'|' => Or,
338 b'@' => At,
339 b'.' => Dot,
340 b',' => Comma,
341 b';' => Semi,
342 b':' => Colon,
343 b'#' => Pound,
344 b'$' => Dollar,
345 b'?' => Question,
346 b'\'' => SingleQuote,
347 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
348 };
349 {
let count = 0usize + 1usize;
let mut vec = ::smallvec::SmallVec::new();
if count <= vec.inline_size() {
vec.push(if joint {
tokenstream::TokenTree::token_joint(kind, span)
} else { tokenstream::TokenTree::token_alone(kind, span) });
vec
} else {
::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[if joint {
tokenstream::TokenTree::token_joint(kind, span)
} else {
tokenstream::TokenTree::token_alone(kind, span)
}])))
}
}smallvec![if joint {
355 tokenstream::TokenTree::token_joint(kind, span)
356 } else {
357 tokenstream::TokenTree::token_alone(kind, span)
358 }]
359 }
360 TokenTree::Group(Group { delimiter, stream, span: DelimSpan { open, close, .. } }) => {
361 {
let count = 0usize + 1usize;
let mut vec = ::smallvec::SmallVec::new();
if count <= vec.inline_size() {
vec.push(tokenstream::TokenTree::Delimited(tokenstream::DelimSpan {
open,
close,
}, DelimSpacing::new(Spacing::Alone, Spacing::Alone),
delimiter.to_internal(), stream.unwrap_or_default()));
vec
} else {
::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[tokenstream::TokenTree::Delimited(tokenstream::DelimSpan {
open,
close,
}, DelimSpacing::new(Spacing::Alone, Spacing::Alone),
delimiter.to_internal(), stream.unwrap_or_default())])))
}
}smallvec![tokenstream::TokenTree::Delimited(
362 tokenstream::DelimSpan { open, close },
363 DelimSpacing::new(Spacing::Alone, Spacing::Alone),
364 delimiter.to_internal(),
365 stream.unwrap_or_default(),
366 )]
367 }
368 TokenTree::Ident(self::Ident { sym, is_raw, span }) => {
369 rustc.psess().symbol_gallery.insert(sym, span);
370 {
let count = 0usize + 1usize;
let mut vec = ::smallvec::SmallVec::new();
if count <= vec.inline_size() {
vec.push(tokenstream::TokenTree::token_alone(Ident(sym,
is_raw.into()), span));
vec
} else {
::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[tokenstream::TokenTree::token_alone(Ident(sym,
is_raw.into()), span)])))
}
}smallvec![tokenstream::TokenTree::token_alone(Ident(sym, is_raw.into()), span)]
371 }
372 TokenTree::Literal(self::Literal {
373 kind: self::LitKind::Integer,
374 symbol,
375 suffix,
376 span,
377 }) if let Some(symbol) = symbol.as_str().strip_prefix('-') => {
378 let symbol = Symbol::intern(symbol);
379 let integer = TokenKind::lit(token::Integer, symbol, suffix);
380 let a = tokenstream::TokenTree::token_joint_hidden(Minus, span);
381 let b = tokenstream::TokenTree::token_alone(integer, span);
382 {
let count = 0usize + 1usize + 1usize;
let mut vec = ::smallvec::SmallVec::new();
if count <= vec.inline_size() {
vec.push(a);
vec.push(b);
vec
} else {
::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[a, b])))
}
}smallvec![a, b]
383 }
384 TokenTree::Literal(self::Literal {
385 kind: self::LitKind::Float,
386 symbol,
387 suffix,
388 span,
389 }) if let Some(symbol) = symbol.as_str().strip_prefix('-') => {
390 let symbol = Symbol::intern(symbol);
391 let float = TokenKind::lit(token::Float, symbol, suffix);
392 let a = tokenstream::TokenTree::token_joint_hidden(Minus, span);
393 let b = tokenstream::TokenTree::token_alone(float, span);
394 {
let count = 0usize + 1usize + 1usize;
let mut vec = ::smallvec::SmallVec::new();
if count <= vec.inline_size() {
vec.push(a);
vec.push(b);
vec
} else {
::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[a, b])))
}
}smallvec![a, b]
395 }
396 TokenTree::Literal(self::Literal { kind, symbol, suffix, span }) => {
397 {
let count = 0usize + 1usize;
let mut vec = ::smallvec::SmallVec::new();
if count <= vec.inline_size() {
vec.push(tokenstream::TokenTree::token_alone(TokenKind::lit(kind.to_internal(),
symbol, suffix), span));
vec
} else {
::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[tokenstream::TokenTree::token_alone(TokenKind::lit(kind.to_internal(),
symbol, suffix), span)])))
}
}smallvec![tokenstream::TokenTree::token_alone(
398 TokenKind::lit(kind.to_internal(), symbol, suffix),
399 span,
400 )]
401 }
402 }
403 }
404}
405
406impl ToInternal<rustc_errors::Level> for Level {
407 fn to_internal(self) -> rustc_errors::Level {
408 match self {
409 Level::Error => rustc_errors::Level::Error,
410 Level::Warning => rustc_errors::Level::Warning,
411 Level::Note => rustc_errors::Level::Note,
412 Level::Help => rustc_errors::Level::Help,
413 _ => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("unknown proc_macro::Level variant: {0:?}", self)));
}unreachable!("unknown proc_macro::Level variant: {:?}", self),
414 }
415 }
416}
417
418pub(crate) struct Rustc<'a, 'b> {
419 ecx: &'a mut ExtCtxt<'b>,
420 def_site: Span,
421 call_site: Span,
422 mixed_site: Span,
423 krate: CrateNum,
424 rebased_spans: FxHashMap<usize, Span>,
425}
426
427impl<'a, 'b> Rustc<'a, 'b> {
428 pub(crate) fn new(ecx: &'a mut ExtCtxt<'b>) -> Self {
429 let expn_data = ecx.current_expansion.id.expn_data();
430 Rustc {
431 def_site: ecx.with_def_site_ctxt(expn_data.def_site),
432 call_site: ecx.with_call_site_ctxt(expn_data.call_site),
433 mixed_site: ecx.with_mixed_site_ctxt(expn_data.call_site),
434 krate: expn_data.macro_def_id.unwrap().krate,
435 rebased_spans: FxHashMap::default(),
436 ecx,
437 }
438 }
439
440 fn psess(&self) -> &ParseSess {
441 self.ecx.psess()
442 }
443}
444
445impl server::Server for Rustc<'_, '_> {
446 type TokenStream = TokenStream;
447 type Span = Span;
448 type Symbol = Symbol;
449
450 fn globals(&mut self) -> ExpnGlobals<Self::Span> {
451 ExpnGlobals {
452 def_site: self.def_site,
453 call_site: self.call_site,
454 mixed_site: self.mixed_site,
455 }
456 }
457
458 fn intern_symbol(string: &str) -> Self::Symbol {
459 Symbol::intern(string)
460 }
461
462 fn with_symbol_string(symbol: &Self::Symbol, f: impl FnOnce(&str)) {
463 f(symbol.as_str())
464 }
465
466 fn injected_env_var(&mut self, var: &str) -> Option<String> {
467 self.ecx.sess.opts.logical_env.get(var).cloned()
468 }
469
470 fn track_env_var(&mut self, var: &str, value: Option<&str>) {
471 self.psess()
472 .env_depinfo
473 .borrow_mut()
474 .insert((Symbol::intern(var), value.map(Symbol::intern)));
475 }
476
477 fn track_path(&mut self, path: &str) {
478 self.psess().file_depinfo.borrow_mut().insert(Symbol::intern(path));
479 }
480
481 fn literal_from_str(&mut self, s: &str) -> Result<Literal<Self::Span, Self::Symbol>, ()> {
482 let name = FileName::proc_macro_source_code(s);
483
484 let mut parser = unwrap_or_emit_fatal(new_parser_from_source_str(
485 self.psess(),
486 name,
487 s.to_owned(),
488 StripTokens::Nothing,
489 ));
490
491 let first_span = parser.token.span.data();
492 let minus_present = parser.eat(::rustc_parse::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Minus,
token_type: ::rustc_parse::parser::token_type::TokenType::Minus,
}exp!(Minus));
493
494 let lit_span = parser.token.span.data();
495 let token::Literal(mut lit) = parser.token.kind else {
496 return Err(());
497 };
498
499 if (lit_span.hi.0 - first_span.lo.0) as usize != s.len() {
502 return Err(());
503 }
504
505 if minus_present {
506 if first_span.hi.0 != lit_span.lo.0 {
509 return Err(());
510 }
511
512 match lit.kind {
514 token::LitKind::Bool
515 | token::LitKind::Byte
516 | token::LitKind::Char
517 | token::LitKind::Str
518 | token::LitKind::StrRaw(_)
519 | token::LitKind::ByteStr
520 | token::LitKind::ByteStrRaw(_)
521 | token::LitKind::CStr
522 | token::LitKind::CStrRaw(_)
523 | token::LitKind::Err(_) => return Err(()),
524 token::LitKind::Integer | token::LitKind::Float => {}
525 }
526
527 let symbol = Symbol::intern(&s[..1 + lit.symbol.as_str().len()]);
529 lit = token::Lit::new(lit.kind, symbol, lit.suffix);
530 }
531 let token::Lit { kind, symbol, suffix } = lit;
532 Ok(Literal {
533 kind: FromInternal::from_internal(kind),
534 symbol,
535 suffix,
536 span: self.call_site,
537 })
538 }
539
540 fn emit_diagnostic(&mut self, diagnostic: Diagnostic<Self::Span>) {
541 let message = rustc_errors::DiagMessage::from(diagnostic.message);
542 let mut diag: Diag<'_, ()> =
543 Diag::new(self.psess().dcx(), diagnostic.level.to_internal(), message);
544 diag.span(MultiSpan::from_spans(diagnostic.spans));
545 for child in diagnostic.children {
546 diag.sub(child.level.to_internal(), child.message, MultiSpan::from_spans(child.spans));
547 }
548 diag.emit();
549 }
550
551 fn ts_drop(&mut self, stream: Self::TokenStream) {
552 drop(stream);
553 }
554
555 fn ts_clone(&mut self, stream: &Self::TokenStream) -> Self::TokenStream {
556 stream.clone()
557 }
558
559 fn ts_is_empty(&mut self, stream: &Self::TokenStream) -> bool {
560 stream.is_empty()
561 }
562
563 fn ts_from_str(&mut self, src: &str) -> Self::TokenStream {
564 unwrap_or_emit_fatal(source_str_to_stream(
565 self.psess(),
566 FileName::proc_macro_source_code(src),
567 src.to_string(),
568 Some(self.call_site),
569 ))
570 }
571
572 fn ts_to_string(&mut self, stream: &Self::TokenStream) -> String {
573 pprust::tts_to_string(stream)
574 }
575
576 fn ts_expand_expr(&mut self, stream: &Self::TokenStream) -> Result<Self::TokenStream, ()> {
577 let expr = try {
579 let mut p = Parser::new(self.psess(), stream.clone(), Some("proc_macro expand expr"));
580 let expr = p.parse_expr()?;
581 if p.token != token::Eof {
582 p.unexpected()?;
583 }
584 expr
585 };
586 let expr = expr.map_err(|err| {
587 err.emit();
588 })?;
589
590 let expr = self
592 .ecx
593 .expander()
594 .fully_expand_fragment(crate::expand::AstFragment::Expr(expr))
595 .make_expr();
596
597 match &expr.kind {
602 ast::ExprKind::Lit(token_lit) if token_lit.kind == token::Bool => {
603 Ok(tokenstream::TokenStream::token_alone(
604 token::Ident(token_lit.symbol, IdentIsRaw::No),
605 expr.span,
606 ))
607 }
608 ast::ExprKind::Lit(token_lit) => {
609 Ok(tokenstream::TokenStream::token_alone(token::Literal(*token_lit), expr.span))
610 }
611 ast::ExprKind::IncludedBytes(byte_sym) => {
612 let lit = token::Lit::new(
613 token::ByteStr,
614 escape_byte_str_symbol(byte_sym.as_byte_str()),
615 None,
616 );
617 Ok(tokenstream::TokenStream::token_alone(token::TokenKind::Literal(lit), expr.span))
618 }
619 ast::ExprKind::Unary(ast::UnOp::Neg, e) => match &e.kind {
620 ast::ExprKind::Lit(token_lit) => match token_lit {
621 token::Lit { kind: token::Integer | token::Float, .. } => {
622 Ok(Self::TokenStream::from_iter([
623 tokenstream::TokenTree::token_joint_hidden(token::Minus, e.span),
626 tokenstream::TokenTree::token_alone(token::Literal(*token_lit), e.span),
627 ]))
628 }
629 _ => Err(()),
630 },
631 _ => Err(()),
632 },
633 _ => Err(()),
634 }
635 }
636
637 fn ts_from_token_tree(
638 &mut self,
639 tree: TokenTree<Self::TokenStream, Self::Span, Self::Symbol>,
640 ) -> Self::TokenStream {
641 Self::TokenStream::new((tree, &mut *self).to_internal().into_iter().collect::<Vec<_>>())
642 }
643
644 fn ts_concat_trees(
645 &mut self,
646 base: Option<Self::TokenStream>,
647 trees: Vec<TokenTree<Self::TokenStream, Self::Span, Self::Symbol>>,
648 ) -> Self::TokenStream {
649 let mut stream = base.unwrap_or_default();
650 for tree in trees {
651 for tt in (tree, &mut *self).to_internal() {
652 stream.push_tree(tt);
653 }
654 }
655 stream
656 }
657
658 fn ts_concat_streams(
659 &mut self,
660 base: Option<Self::TokenStream>,
661 streams: Vec<Self::TokenStream>,
662 ) -> Self::TokenStream {
663 let mut stream = base.unwrap_or_default();
664 for s in streams {
665 stream.push_stream(s);
666 }
667 stream
668 }
669
670 fn ts_into_trees(
671 &mut self,
672 stream: Self::TokenStream,
673 ) -> Vec<TokenTree<Self::TokenStream, Self::Span, Self::Symbol>> {
674 FromInternal::from_internal(stream)
675 }
676
677 fn span_debug(&mut self, span: Self::Span) -> String {
678 if self.ecx.ecfg.span_debug {
679 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", span))
})format!("{span:?}")
680 } else {
681 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?} bytes({1}..{2})",
span.ctxt(), span.lo().0, span.hi().0))
})format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
682 }
683 }
684
685 fn span_file(&mut self, span: Self::Span) -> String {
686 self.psess()
687 .source_map()
688 .lookup_char_pos(span.lo())
689 .file
690 .name
691 .prefer_remapped_unconditionally()
692 .to_string()
693 }
694
695 fn span_local_file(&mut self, span: Self::Span) -> Option<String> {
696 self.psess()
697 .source_map()
698 .lookup_char_pos(span.lo())
699 .file
700 .name
701 .clone()
702 .into_local_path()
703 .map(|p| {
704 p.to_str()
705 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
706 .to_string()
707 })
708 }
709
710 fn span_parent(&mut self, span: Self::Span) -> Option<Self::Span> {
711 span.parent_callsite()
712 }
713
714 fn span_source(&mut self, span: Self::Span) -> Self::Span {
715 span.source_callsite()
716 }
717
718 fn span_byte_range(&mut self, span: Self::Span) -> Range<usize> {
719 let source_map = self.psess().source_map();
720
721 let relative_start_pos = source_map.lookup_byte_offset(span.lo()).pos;
722 let relative_end_pos = source_map.lookup_byte_offset(span.hi()).pos;
723
724 Range { start: relative_start_pos.0 as usize, end: relative_end_pos.0 as usize }
725 }
726 fn span_start(&mut self, span: Self::Span) -> Self::Span {
727 span.shrink_to_lo()
728 }
729
730 fn span_end(&mut self, span: Self::Span) -> Self::Span {
731 span.shrink_to_hi()
732 }
733
734 fn span_line(&mut self, span: Self::Span) -> usize {
735 let loc = self.psess().source_map().lookup_char_pos(span.lo());
736 loc.line
737 }
738
739 fn span_column(&mut self, span: Self::Span) -> usize {
740 let loc = self.psess().source_map().lookup_char_pos(span.lo());
741 loc.col.to_usize() + 1
742 }
743
744 fn span_join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
745 let self_loc = self.psess().source_map().lookup_char_pos(first.lo());
746 let other_loc = self.psess().source_map().lookup_char_pos(second.lo());
747
748 if self_loc.file.stable_id != other_loc.file.stable_id {
749 return None;
750 }
751
752 Some(first.to(second))
753 }
754
755 fn span_subspan(
756 &mut self,
757 span: Self::Span,
758 start: Bound<usize>,
759 end: Bound<usize>,
760 ) -> Option<Self::Span> {
761 let length = span.hi().to_usize() - span.lo().to_usize();
762
763 let start = match start {
764 Bound::Included(lo) => lo,
765 Bound::Excluded(lo) => lo.checked_add(1)?,
766 Bound::Unbounded => 0,
767 };
768
769 let end = match end {
770 Bound::Included(hi) => hi.checked_add(1)?,
771 Bound::Excluded(hi) => hi,
772 Bound::Unbounded => length,
773 };
774
775 if start > u32::MAX as usize
777 || end > u32::MAX as usize
778 || (u32::MAX - start as u32) < span.lo().to_u32()
779 || (u32::MAX - end as u32) < span.lo().to_u32()
780 || start >= end
781 || end > length
782 {
783 return None;
784 }
785
786 let new_lo = span.lo() + BytePos::from_usize(start);
787 let new_hi = span.lo() + BytePos::from_usize(end);
788 Some(span.with_lo(new_lo).with_hi(new_hi))
789 }
790
791 fn span_resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
792 span.with_ctxt(at.ctxt())
793 }
794
795 fn span_source_text(&mut self, span: Self::Span) -> Option<String> {
796 self.psess().source_map().span_to_snippet(span).ok()
797 }
798
799 fn span_save_span(&mut self, span: Self::Span) -> usize {
824 self.psess().save_proc_macro_span(span)
825 }
826
827 fn span_recover_proc_macro_span(&mut self, id: usize) -> Self::Span {
828 let (resolver, krate, def_site) = (&*self.ecx.resolver, self.krate, self.def_site);
829 *self.rebased_spans.entry(id).or_insert_with(|| {
830 resolver.get_proc_macro_quoted_span(krate, id).with_ctxt(def_site.ctxt())
833 })
834 }
835
836 fn symbol_normalize_and_validate_ident(&mut self, string: &str) -> Result<Self::Symbol, ()> {
837 let sym = nfc_normalize(string);
838 if rustc_lexer::is_ident(sym.as_str()) { Ok(sym) } else { Err(()) }
839 }
840}