1 use crate::base::ExtCtxt;
4 use rustc_ast::token::{self, Nonterminal, NtIdent};
5 use rustc_ast::tokenstream::{self, CanSynthesizeMissingTokens};
6 use rustc_ast::tokenstream::{DelimSpan, Spacing::*, TokenStream, TreeAndSpacing};
7 use rustc_ast_pretty::pprust;
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc_data_structures::sync::Lrc;
10 use rustc_errors::{Diagnostic, PResult};
11 use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT;
12 use rustc_lint_defs::BuiltinLintDiagnostics;
13 use rustc_parse::lexer::nfc_normalize;
14 use rustc_parse::{nt_to_tokenstream, parse_stream_from_source_str};
15 use rustc_session::parse::ParseSess;
16 use rustc_span::def_id::CrateNum;
17 use rustc_span::hygiene::ExpnKind;
18 use rustc_span::symbol::{self, kw, sym, Symbol};
19 use rustc_span::{BytePos, FileName, MultiSpan, Pos, RealFileName, SourceFile, Span};
21 use pm::bridge::{server, TokenTree};
22 use pm::{Delimiter, Level, LineColumn, Spacing};
24 use std::{ascii, panic};
26 trait FromInternal<T> {
27 fn from_internal(x: T) -> Self;
31 fn to_internal(self) -> T;
34 impl FromInternal<token::DelimToken> for Delimiter {
35 fn from_internal(delim: token::DelimToken) -> Delimiter {
37 token::Paren => Delimiter::Parenthesis,
38 token::Brace => Delimiter::Brace,
39 token::Bracket => Delimiter::Bracket,
40 token::NoDelim => Delimiter::None,
45 impl ToInternal<token::DelimToken> for Delimiter {
46 fn to_internal(self) -> token::DelimToken {
48 Delimiter::Parenthesis => token::Paren,
49 Delimiter::Brace => token::Brace,
50 Delimiter::Bracket => token::Bracket,
51 Delimiter::None => token::NoDelim,
56 impl FromInternal<(TreeAndSpacing, &'_ mut Vec<Self>, &mut Rustc<'_, '_>)>
57 for TokenTree<Group, Punct, Ident, Literal>
60 ((tree, spacing), stack, rustc): (TreeAndSpacing, &mut Vec<Self>, &mut Rustc<'_, '_>),
62 use rustc_ast::token::*;
64 let joint = spacing == Joint;
65 let Token { kind, span } = match tree {
66 tokenstream::TokenTree::Delimited(span, delim, tts) => {
67 let delimiter = Delimiter::from_internal(delim);
68 return TokenTree::Group(Group { delimiter, stream: tts, span, flatten: false });
70 tokenstream::TokenTree::Token(token) => token,
74 ($ty:ident { $($field:ident $(: $value:expr)*),+ $(,)? }) => (
75 TokenTree::$ty(self::$ty {
76 $($field $(: $value)*,)+
80 ($ty:ident::$method:ident($($value:expr),*)) => (
81 TokenTree::$ty(self::$ty::$method($($value,)* span))
86 tt!(Punct::new($a, joint))
88 ($a:expr, $b:expr) => {{
89 stack.push(tt!(Punct::new($b, joint)));
90 tt!(Punct::new($a, true))
92 ($a:expr, $b:expr, $c:expr) => {{
93 stack.push(tt!(Punct::new($c, joint)));
94 stack.push(tt!(Punct::new($b, true)));
95 tt!(Punct::new($a, true))
103 EqEq => op!('=', '='),
107 AndAnd => op!('&', '&'),
108 OrOr => op!('|', '|'),
111 BinOp(Plus) => op!('+'),
112 BinOp(Minus) => op!('-'),
113 BinOp(Star) => op!('*'),
114 BinOp(Slash) => op!('/'),
115 BinOp(Percent) => op!('%'),
116 BinOp(Caret) => op!('^'),
117 BinOp(And) => op!('&'),
118 BinOp(Or) => op!('|'),
119 BinOp(Shl) => op!('<', '<'),
120 BinOp(Shr) => op!('>', '>'),
121 BinOpEq(Plus) => op!('+', '='),
122 BinOpEq(Minus) => op!('-', '='),
123 BinOpEq(Star) => op!('*', '='),
124 BinOpEq(Slash) => op!('/', '='),
125 BinOpEq(Percent) => op!('%', '='),
126 BinOpEq(Caret) => op!('^', '='),
127 BinOpEq(And) => op!('&', '='),
128 BinOpEq(Or) => op!('|', '='),
129 BinOpEq(Shl) => op!('<', '<', '='),
130 BinOpEq(Shr) => op!('>', '>', '='),
133 DotDot => op!('.', '.'),
134 DotDotDot => op!('.', '.', '.'),
135 DotDotEq => op!('.', '.', '='),
139 ModSep => op!(':', ':'),
140 RArrow => op!('-', '>'),
141 LArrow => op!('<', '-'),
142 FatArrow => op!('=', '>'),
145 Question => op!('?'),
146 SingleQuote => op!('\''),
148 Ident(name, false) if name == kw::DollarCrate => tt!(Ident::dollar_crate()),
149 Ident(name, is_raw) => tt!(Ident::new(rustc.sess(), name, is_raw)),
151 let ident = symbol::Ident::new(name, span).without_first_quote();
152 stack.push(tt!(Ident::new(rustc.sess(), ident.name, false)));
153 tt!(Punct::new('\'', true))
155 Literal(lit) => tt!(Literal { lit }),
156 DocComment(_, attr_style, data) => {
157 let mut escaped = String::new();
158 for ch in data.as_str().chars() {
159 escaped.extend(ch.escape_debug());
162 Ident(sym::doc, false),
164 TokenKind::lit(token::Str, Symbol::intern(&escaped), None),
167 .map(|kind| tokenstream::TokenTree::token(kind, span))
169 stack.push(TokenTree::Group(Group {
170 delimiter: Delimiter::Bracket,
172 span: DelimSpan::from_single(span),
175 if attr_style == ast::AttrStyle::Inner {
176 stack.push(tt!(Punct::new('!', false)));
178 tt!(Punct::new('#', false))
182 if let Some((name, is_raw)) = ident_name_compatibility_hack(&nt, span, rustc) =>
184 TokenTree::Ident(Ident::new(rustc.sess(), name.name, is_raw, name.span))
186 Interpolated(nt) => {
187 let stream = nt_to_tokenstream(&nt, rustc.sess(), CanSynthesizeMissingTokens::No);
188 TokenTree::Group(Group {
189 delimiter: Delimiter::None,
191 span: DelimSpan::from_single(span),
192 flatten: crate::base::pretty_printing_compatibility_hack(&nt, rustc.sess()),
196 OpenDelim(..) | CloseDelim(..) => unreachable!(),
197 Eof => unreachable!(),
202 impl ToInternal<TokenStream> for TokenTree<Group, Punct, Ident, Literal> {
203 fn to_internal(self) -> TokenStream {
204 use rustc_ast::token::*;
206 let (ch, joint, span) = match self {
207 TokenTree::Punct(Punct { ch, joint, span }) => (ch, joint, span),
208 TokenTree::Group(Group { delimiter, stream, span, .. }) => {
209 return tokenstream::TokenTree::Delimited(span, delimiter.to_internal(), stream)
212 TokenTree::Ident(self::Ident { sym, is_raw, span }) => {
213 return tokenstream::TokenTree::token(Ident(sym, is_raw), span).into();
215 TokenTree::Literal(self::Literal {
216 lit: token::Lit { kind: token::Integer, symbol, suffix },
218 }) if symbol.as_str().starts_with('-') => {
219 let minus = BinOp(BinOpToken::Minus);
220 let symbol = Symbol::intern(&symbol.as_str()[1..]);
221 let integer = TokenKind::lit(token::Integer, symbol, suffix);
222 let a = tokenstream::TokenTree::token(minus, span);
223 let b = tokenstream::TokenTree::token(integer, span);
224 return [a, b].into_iter().collect();
226 TokenTree::Literal(self::Literal {
227 lit: token::Lit { kind: token::Float, symbol, suffix },
229 }) if symbol.as_str().starts_with('-') => {
230 let minus = BinOp(BinOpToken::Minus);
231 let symbol = Symbol::intern(&symbol.as_str()[1..]);
232 let float = TokenKind::lit(token::Float, symbol, suffix);
233 let a = tokenstream::TokenTree::token(minus, span);
234 let b = tokenstream::TokenTree::token(float, span);
235 return [a, b].into_iter().collect();
237 TokenTree::Literal(self::Literal { lit, span }) => {
238 return tokenstream::TokenTree::token(Literal(lit), span).into();
242 let kind = match ch {
252 '%' => BinOp(Percent),
268 let tree = tokenstream::TokenTree::token(kind, span);
269 TokenStream::new(vec![(tree, if joint { Joint } else { Alone })])
273 impl ToInternal<rustc_errors::Level> for Level {
274 fn to_internal(self) -> rustc_errors::Level {
276 Level::Error => rustc_errors::Level::Error { lint: false },
277 Level::Warning => rustc_errors::Level::Warning,
278 Level::Note => rustc_errors::Level::Note,
279 Level::Help => rustc_errors::Level::Help,
280 _ => unreachable!("unknown proc_macro::Level variant: {:?}", self),
285 pub struct FreeFunctions;
288 pub struct TokenStreamIter {
289 cursor: tokenstream::Cursor,
290 stack: Vec<TokenTree<Group, Punct, Ident, Literal>>,
295 delimiter: Delimiter,
298 /// A hack used to pass AST fragments to attribute and derive macros
299 /// as a single nonterminal token instead of a token stream.
300 /// FIXME: It needs to be removed, but there are some compatibility issues (see #73345).
304 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
307 // NB. not using `Spacing` here because it doesn't implement `Hash`.
313 fn new(ch: char, joint: bool, span: Span) -> Punct {
314 const LEGAL_CHARS: &[char] = &[
315 '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
316 ':', '#', '$', '?', '\'',
318 if !LEGAL_CHARS.contains(&ch) {
319 panic!("unsupported character `{:?}`", ch)
321 Punct { ch, joint, span }
325 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
333 fn new(sess: &ParseSess, sym: Symbol, is_raw: bool, span: Span) -> Ident {
334 let sym = nfc_normalize(sym.as_str());
335 let string = sym.as_str();
336 if !rustc_lexer::is_ident(string) {
337 panic!("`{:?}` is not a valid identifier", string)
339 if is_raw && !sym.can_be_raw() {
340 panic!("`{}` cannot be a raw identifier", string);
342 sess.symbol_gallery.insert(sym, span);
343 Ident { sym, is_raw, span }
345 fn dollar_crate(span: Span) -> Ident {
346 // `$crate` is accepted as an ident only if it comes from the compiler.
347 Ident { sym: kw::DollarCrate, is_raw: false, span }
351 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
352 #[derive(Clone, Debug)]
358 pub(crate) struct Rustc<'a, 'b> {
359 ecx: &'a mut ExtCtxt<'b>,
364 rebased_spans: FxHashMap<usize, Span>,
367 impl<'a, 'b> Rustc<'a, 'b> {
368 pub fn new(ecx: &'a mut ExtCtxt<'b>) -> Self {
369 let expn_data = ecx.current_expansion.id.expn_data();
371 def_site: ecx.with_def_site_ctxt(expn_data.def_site),
372 call_site: ecx.with_call_site_ctxt(expn_data.call_site),
373 mixed_site: ecx.with_mixed_site_ctxt(expn_data.call_site),
374 krate: expn_data.macro_def_id.unwrap().krate,
375 rebased_spans: FxHashMap::default(),
380 fn sess(&self) -> &ParseSess {
381 self.ecx.parse_sess()
384 fn lit(&mut self, kind: token::LitKind, symbol: Symbol, suffix: Option<Symbol>) -> Literal {
385 Literal { lit: token::Lit::new(kind, symbol, suffix), span: server::Span::call_site(self) }
389 impl server::Types for Rustc<'_, '_> {
390 type FreeFunctions = FreeFunctions;
391 type TokenStream = TokenStream;
392 type TokenStreamBuilder = tokenstream::TokenStreamBuilder;
393 type TokenStreamIter = TokenStreamIter;
397 type Literal = Literal;
398 type SourceFile = Lrc<SourceFile>;
399 type MultiSpan = Vec<Span>;
400 type Diagnostic = Diagnostic;
404 impl server::FreeFunctions for Rustc<'_, '_> {
405 fn track_env_var(&mut self, var: &str, value: Option<&str>) {
409 .insert((Symbol::intern(var), value.map(Symbol::intern)));
412 fn track_path(&mut self, path: &str) {
413 self.sess().file_depinfo.borrow_mut().insert(Symbol::intern(path));
417 impl server::TokenStream for Rustc<'_, '_> {
418 fn new(&mut self) -> Self::TokenStream {
419 TokenStream::default()
421 fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
424 fn from_str(&mut self, src: &str) -> Self::TokenStream {
425 parse_stream_from_source_str(
426 FileName::proc_macro_source_code(src),
429 Some(self.call_site),
432 fn to_string(&mut self, stream: &Self::TokenStream) -> String {
433 pprust::tts_to_string(stream)
435 fn expand_expr(&mut self, stream: &Self::TokenStream) -> Result<Self::TokenStream, ()> {
436 // Parse the expression from our tokenstream.
437 let expr: PResult<'_, _> = try {
438 let mut p = rustc_parse::stream_to_parser(
441 Some("proc_macro expand expr"),
443 let expr = p.parse_expr()?;
444 if p.token != token::Eof {
449 let expr = expr.map_err(|mut err| {
453 // Perform eager expansion on the expression.
457 .fully_expand_fragment(crate::expand::AstFragment::Expr(expr))
460 // NOTE: For now, limit `expand_expr` to exclusively expand to literals.
461 // This may be relaxed in the future.
462 // We don't use `nt_to_tokenstream` as the tokenstream currently cannot
463 // be recovered in the general case.
465 ast::ExprKind::Lit(l) => {
466 Ok(tokenstream::TokenTree::token(token::Literal(l.token), l.span).into())
468 ast::ExprKind::Unary(ast::UnOp::Neg, e) => match &e.kind {
469 ast::ExprKind::Lit(l) => match l.token {
470 token::Lit { kind: token::Integer | token::Float, .. } => {
471 Ok(Self::TokenStream::from_iter([
472 // FIXME: The span of the `-` token is lost when
473 // parsing, so we cannot faithfully recover it here.
474 tokenstream::TokenTree::token(token::BinOp(token::Minus), e.span),
475 tokenstream::TokenTree::token(token::Literal(l.token), l.span),
487 tree: TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>,
488 ) -> Self::TokenStream {
491 fn into_iter(&mut self, stream: Self::TokenStream) -> Self::TokenStreamIter {
492 TokenStreamIter { cursor: stream.trees(), stack: vec![] }
496 impl server::TokenStreamBuilder for Rustc<'_, '_> {
497 fn new(&mut self) -> Self::TokenStreamBuilder {
498 tokenstream::TokenStreamBuilder::new()
500 fn push(&mut self, builder: &mut Self::TokenStreamBuilder, stream: Self::TokenStream) {
501 builder.push(stream);
503 fn build(&mut self, builder: Self::TokenStreamBuilder) -> Self::TokenStream {
508 impl server::TokenStreamIter for Rustc<'_, '_> {
511 iter: &mut Self::TokenStreamIter,
512 ) -> Option<TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>> {
514 let tree = iter.stack.pop().or_else(|| {
515 let next = iter.cursor.next_with_spacing()?;
516 Some(TokenTree::from_internal((next, &mut iter.stack, self)))
518 // A hack used to pass AST fragments to attribute and derive macros
519 // as a single nonterminal token instead of a token stream.
520 // Such token needs to be "unwrapped" and not represented as a delimited group.
521 // FIXME: It needs to be removed, but there are some compatibility issues (see #73345).
522 if let TokenTree::Group(ref group) = tree {
524 iter.cursor.append(group.stream.clone());
533 impl server::Group for Rustc<'_, '_> {
534 fn new(&mut self, delimiter: Delimiter, stream: Self::TokenStream) -> Self::Group {
538 span: DelimSpan::from_single(server::Span::call_site(self)),
542 fn delimiter(&mut self, group: &Self::Group) -> Delimiter {
545 fn stream(&mut self, group: &Self::Group) -> Self::TokenStream {
548 fn span(&mut self, group: &Self::Group) -> Self::Span {
551 fn span_open(&mut self, group: &Self::Group) -> Self::Span {
554 fn span_close(&mut self, group: &Self::Group) -> Self::Span {
557 fn set_span(&mut self, group: &mut Self::Group, span: Self::Span) {
558 group.span = DelimSpan::from_single(span);
562 impl server::Punct for Rustc<'_, '_> {
563 fn new(&mut self, ch: char, spacing: Spacing) -> Self::Punct {
564 Punct::new(ch, spacing == Spacing::Joint, server::Span::call_site(self))
566 fn as_char(&mut self, punct: Self::Punct) -> char {
569 fn spacing(&mut self, punct: Self::Punct) -> Spacing {
570 if punct.joint { Spacing::Joint } else { Spacing::Alone }
572 fn span(&mut self, punct: Self::Punct) -> Self::Span {
575 fn with_span(&mut self, punct: Self::Punct, span: Self::Span) -> Self::Punct {
576 Punct { span, ..punct }
580 impl server::Ident for Rustc<'_, '_> {
581 fn new(&mut self, string: &str, span: Self::Span, is_raw: bool) -> Self::Ident {
582 Ident::new(self.sess(), Symbol::intern(string), is_raw, span)
584 fn span(&mut self, ident: Self::Ident) -> Self::Span {
587 fn with_span(&mut self, ident: Self::Ident, span: Self::Span) -> Self::Ident {
588 Ident { span, ..ident }
592 impl server::Literal for Rustc<'_, '_> {
593 fn from_str(&mut self, s: &str) -> Result<Self::Literal, ()> {
594 let name = FileName::proc_macro_source_code(s);
595 let mut parser = rustc_parse::new_parser_from_source_str(self.sess(), name, s.to_owned());
597 let first_span = parser.token.span.data();
598 let minus_present = parser.eat(&token::BinOp(token::Minus));
600 let lit_span = parser.token.span.data();
601 let token::Literal(mut lit) = parser.token.kind else {
605 // Check no comment or whitespace surrounding the (possibly negative)
606 // literal, or more tokens after it.
607 if (lit_span.hi.0 - first_span.lo.0) as usize != s.len() {
612 // If minus is present, check no comment or whitespace in between it
613 // and the literal token.
614 if first_span.hi.0 != lit_span.lo.0 {
618 // Check literal is a kind we allow to be negated in a proc macro token.
621 | token::LitKind::Byte
622 | token::LitKind::Char
623 | token::LitKind::Str
624 | token::LitKind::StrRaw(_)
625 | token::LitKind::ByteStr
626 | token::LitKind::ByteStrRaw(_)
627 | token::LitKind::Err => return Err(()),
628 token::LitKind::Integer | token::LitKind::Float => {}
631 // Synthesize a new symbol that includes the minus sign.
632 let symbol = Symbol::intern(&s[..1 + lit.symbol.as_str().len()]);
633 lit = token::Lit::new(lit.kind, symbol, lit.suffix);
636 Ok(Literal { lit, span: self.call_site })
638 fn to_string(&mut self, literal: &Self::Literal) -> String {
639 literal.lit.to_string()
641 fn debug_kind(&mut self, literal: &Self::Literal) -> String {
642 format!("{:?}", literal.lit.kind)
644 fn symbol(&mut self, literal: &Self::Literal) -> String {
645 literal.lit.symbol.to_string()
647 fn suffix(&mut self, literal: &Self::Literal) -> Option<String> {
648 literal.lit.suffix.as_ref().map(Symbol::to_string)
650 fn integer(&mut self, n: &str) -> Self::Literal {
651 self.lit(token::Integer, Symbol::intern(n), None)
653 fn typed_integer(&mut self, n: &str, kind: &str) -> Self::Literal {
654 self.lit(token::Integer, Symbol::intern(n), Some(Symbol::intern(kind)))
656 fn float(&mut self, n: &str) -> Self::Literal {
657 self.lit(token::Float, Symbol::intern(n), None)
659 fn f32(&mut self, n: &str) -> Self::Literal {
660 self.lit(token::Float, Symbol::intern(n), Some(sym::f32))
662 fn f64(&mut self, n: &str) -> Self::Literal {
663 self.lit(token::Float, Symbol::intern(n), Some(sym::f64))
665 fn string(&mut self, string: &str) -> Self::Literal {
666 let mut escaped = String::new();
667 for ch in string.chars() {
668 escaped.extend(ch.escape_debug());
670 self.lit(token::Str, Symbol::intern(&escaped), None)
672 fn character(&mut self, ch: char) -> Self::Literal {
673 let mut escaped = String::new();
674 escaped.extend(ch.escape_unicode());
675 self.lit(token::Char, Symbol::intern(&escaped), None)
677 fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
681 .flat_map(ascii::escape_default)
682 .map(Into::<char>::into)
683 .collect::<String>();
684 self.lit(token::ByteStr, Symbol::intern(&string), None)
686 fn span(&mut self, literal: &Self::Literal) -> Self::Span {
689 fn set_span(&mut self, literal: &mut Self::Literal, span: Self::Span) {
694 literal: &Self::Literal,
697 ) -> Option<Self::Span> {
698 let span = literal.span;
699 let length = span.hi().to_usize() - span.lo().to_usize();
701 let start = match start {
702 Bound::Included(lo) => lo,
703 Bound::Excluded(lo) => lo.checked_add(1)?,
704 Bound::Unbounded => 0,
707 let end = match end {
708 Bound::Included(hi) => hi.checked_add(1)?,
709 Bound::Excluded(hi) => hi,
710 Bound::Unbounded => length,
713 // Bounds check the values, preventing addition overflow and OOB spans.
714 if start > u32::MAX as usize
715 || end > u32::MAX as usize
716 || (u32::MAX - start as u32) < span.lo().to_u32()
717 || (u32::MAX - end as u32) < span.lo().to_u32()
724 let new_lo = span.lo() + BytePos::from_usize(start);
725 let new_hi = span.lo() + BytePos::from_usize(end);
726 Some(span.with_lo(new_lo).with_hi(new_hi))
730 impl server::SourceFile for Rustc<'_, '_> {
731 fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
732 Lrc::ptr_eq(file1, file2)
734 fn path(&mut self, file: &Self::SourceFile) -> String {
736 FileName::Real(ref name) => name
738 .expect("attempting to get a file path in an imported file in `proc_macro::SourceFile::path`")
740 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
742 _ => file.name.prefer_local().to_string(),
745 fn is_real(&mut self, file: &Self::SourceFile) -> bool {
750 impl server::MultiSpan for Rustc<'_, '_> {
751 fn new(&mut self) -> Self::MultiSpan {
754 fn push(&mut self, spans: &mut Self::MultiSpan, span: Self::Span) {
759 impl server::Diagnostic for Rustc<'_, '_> {
760 fn new(&mut self, level: Level, msg: &str, spans: Self::MultiSpan) -> Self::Diagnostic {
761 let mut diag = Diagnostic::new(level.to_internal(), msg);
762 diag.set_span(MultiSpan::from_spans(spans));
767 diag: &mut Self::Diagnostic,
770 spans: Self::MultiSpan,
772 diag.sub(level.to_internal(), msg, MultiSpan::from_spans(spans), None);
774 fn emit(&mut self, diag: Self::Diagnostic) {
775 self.sess().span_diagnostic.emit_diagnostic(&diag);
779 impl server::Span for Rustc<'_, '_> {
780 fn debug(&mut self, span: Self::Span) -> String {
781 if self.ecx.ecfg.span_debug {
782 format!("{:?}", span)
784 format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
787 fn def_site(&mut self) -> Self::Span {
790 fn call_site(&mut self) -> Self::Span {
793 fn mixed_site(&mut self) -> Self::Span {
796 fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
797 self.sess().source_map().lookup_char_pos(span.lo()).file
799 fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
800 span.parent_callsite()
802 fn source(&mut self, span: Self::Span) -> Self::Span {
803 span.source_callsite()
805 fn start(&mut self, span: Self::Span) -> LineColumn {
806 let loc = self.sess().source_map().lookup_char_pos(span.lo());
807 LineColumn { line: loc.line, column: loc.col.to_usize() }
809 fn end(&mut self, span: Self::Span) -> LineColumn {
810 let loc = self.sess().source_map().lookup_char_pos(span.hi());
811 LineColumn { line: loc.line, column: loc.col.to_usize() }
813 fn before(&mut self, span: Self::Span) -> Self::Span {
816 fn after(&mut self, span: Self::Span) -> Self::Span {
819 fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
820 let self_loc = self.sess().source_map().lookup_char_pos(first.lo());
821 let other_loc = self.sess().source_map().lookup_char_pos(second.lo());
823 if self_loc.file.name != other_loc.file.name {
827 Some(first.to(second))
829 fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
830 span.with_ctxt(at.ctxt())
832 fn source_text(&mut self, span: Self::Span) -> Option<String> {
833 self.sess().source_map().span_to_snippet(span).ok()
835 /// Saves the provided span into the metadata of
836 /// *the crate we are currently compiling*, which must
837 /// be a proc-macro crate. This id can be passed to
838 /// `recover_proc_macro_span` when our current crate
839 /// is *run* as a proc-macro.
841 /// Let's suppose that we have two crates - `my_client`
842 /// and `my_proc_macro`. The `my_proc_macro` crate
843 /// contains a procedural macro `my_macro`, which
844 /// is implemented as: `quote! { "hello" }`
846 /// When we *compile* `my_proc_macro`, we will execute
847 /// the `quote` proc-macro. This will save the span of
848 /// "hello" into the metadata of `my_proc_macro`. As a result,
849 /// the body of `my_proc_macro` (after expansion) will end
850 /// up containg a call that looks like this:
851 /// `proc_macro::Ident::new("hello", proc_macro::Span::recover_proc_macro_span(0))`
853 /// where `0` is the id returned by this function.
854 /// When `my_proc_macro` *executes* (during the compilation of `my_client`),
855 /// the call to `recover_proc_macro_span` will load the corresponding
856 /// span from the metadata of `my_proc_macro` (which we have access to,
857 /// since we've loaded `my_proc_macro` from disk in order to execute it).
858 /// In this way, we have obtained a span pointing into `my_proc_macro`
859 fn save_span(&mut self, span: Self::Span) -> usize {
860 self.sess().save_proc_macro_span(span)
862 fn recover_proc_macro_span(&mut self, id: usize) -> Self::Span {
863 let (resolver, krate, def_site) = (&*self.ecx.resolver, self.krate, self.def_site);
864 *self.rebased_spans.entry(id).or_insert_with(|| {
865 // FIXME: `SyntaxContext` for spans from proc macro crates is lost during encoding,
866 // replace it with a def-site context until we are encoding it properly.
867 resolver.get_proc_macro_quoted_span(krate, id).with_ctxt(def_site.ctxt())
872 // See issue #74616 for details
873 fn ident_name_compatibility_hack(
876 rustc: &mut Rustc<'_, '_>,
877 ) -> Option<(rustc_span::symbol::Ident, bool)> {
878 if let NtIdent(ident, is_raw) = nt {
879 if let ExpnKind::Macro(_, macro_name) = orig_span.ctxt().outer_expn_data().kind {
880 let source_map = rustc.sess().source_map();
881 let filename = source_map.span_to_filename(orig_span);
882 if let FileName::Real(RealFileName::LocalPath(path)) = filename {
883 let matches_prefix = |prefix, filename| {
884 // Check for a path that ends with 'prefix*/src/<filename>'
885 let mut iter = path.components().rev();
886 iter.next().and_then(|p| p.as_os_str().to_str()) == Some(filename)
887 && iter.next().and_then(|p| p.as_os_str().to_str()) == Some("src")
890 .and_then(|p| p.as_os_str().to_str())
891 .map_or(false, |p| p.starts_with(prefix))
894 let time_macros_impl =
895 macro_name == sym::impl_macros && matches_prefix("time-macros-impl", "lib.rs");
896 let js_sys = macro_name == sym::arrays && matches_prefix("js-sys", "lib.rs");
897 if time_macros_impl || js_sys {
898 let snippet = source_map.span_to_snippet(orig_span);
899 if snippet.as_deref() == Ok("$name") {
900 if time_macros_impl {
901 rustc.sess().buffer_lint_with_diagnostic(
902 &PROC_MACRO_BACK_COMPAT,
905 "using an old version of `time-macros-impl`",
906 BuiltinLintDiagnostics::ProcMacroBackCompat(
907 "the `time-macros-impl` crate will stop compiling in futures version of Rust. \
908 Please update to the latest version of the `time` crate to avoid breakage".to_string())
910 return Some((*ident, *is_raw));
913 if let Some(c) = path
915 .flat_map(|c| c.as_os_str().to_str())
916 .find(|c| c.starts_with("js-sys"))
918 let mut version = c.trim_start_matches("js-sys-").split('.');
919 if version.next() == Some("0")
920 && version.next() == Some("3")
923 .and_then(|c| c.parse::<u32>().ok())
924 .map_or(false, |v| v < 40)
926 rustc.sess().buffer_lint_with_diagnostic(
927 &PROC_MACRO_BACK_COMPAT,
930 "using an old version of `js-sys`",
931 BuiltinLintDiagnostics::ProcMacroBackCompat(
932 "older versions of the `js-sys` crate will stop compiling in future versions of Rust; \
933 please update to `js-sys` v0.3.40 or above".to_string())
935 return Some((*ident, *is_raw));
942 if macro_name == sym::tuple_from_req && matches_prefix("actix-web", "extract.rs") {
943 let snippet = source_map.span_to_snippet(orig_span);
944 if snippet.as_deref() == Ok("$T") {
945 if let FileName::Real(RealFileName::LocalPath(macro_path)) =
946 source_map.span_to_filename(rustc.def_site)
948 if macro_path.to_string_lossy().contains("pin-project-internal-0.") {
949 rustc.sess().buffer_lint_with_diagnostic(
950 &PROC_MACRO_BACK_COMPAT,
953 "using an old version of `actix-web`",
954 BuiltinLintDiagnostics::ProcMacroBackCompat(
955 "the version of `actix-web` you are using might stop compiling in future versions of Rust; \
956 please update to the latest version of the `actix-web` crate to avoid breakage".to_string())
958 return Some((*ident, *is_raw));