1 use crate::base::{ExtCtxt, ResolverExpand};
4 use rustc_ast::token::{self, Nonterminal, NtIdent, TokenKind};
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;
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::ExpnId;
18 use rustc_span::hygiene::ExpnKind;
19 use rustc_span::symbol::{self, kw, sym, Symbol};
20 use rustc_span::{BytePos, FileName, MultiSpan, Pos, RealFileName, SourceFile, Span};
22 use pm::bridge::{server, TokenTree};
23 use pm::{Delimiter, Level, LineColumn, Spacing};
25 use std::{ascii, panic};
27 trait FromInternal<T> {
28 fn from_internal(x: T) -> Self;
32 fn to_internal(self) -> T;
35 impl FromInternal<token::DelimToken> for Delimiter {
36 fn from_internal(delim: token::DelimToken) -> Delimiter {
38 token::Paren => Delimiter::Parenthesis,
39 token::Brace => Delimiter::Brace,
40 token::Bracket => Delimiter::Bracket,
41 token::NoDelim => Delimiter::None,
46 impl ToInternal<token::DelimToken> for Delimiter {
47 fn to_internal(self) -> token::DelimToken {
49 Delimiter::Parenthesis => token::Paren,
50 Delimiter::Brace => token::Brace,
51 Delimiter::Bracket => token::Bracket,
52 Delimiter::None => token::NoDelim,
57 impl FromInternal<(TreeAndSpacing, &'_ mut Vec<Self>, &mut Rustc<'_>)>
58 for TokenTree<Group, Punct, Ident, Literal>
61 ((tree, spacing), stack, rustc): (TreeAndSpacing, &mut Vec<Self>, &mut Rustc<'_>),
63 use rustc_ast::token::*;
65 let joint = spacing == Joint;
66 let Token { kind, span } = match tree {
67 tokenstream::TokenTree::Delimited(span, delim, tts) => {
68 let delimiter = Delimiter::from_internal(delim);
69 return TokenTree::Group(Group { delimiter, stream: tts, span, flatten: false });
71 tokenstream::TokenTree::Token(token) => token,
75 ($ty:ident { $($field:ident $(: $value:expr)*),+ $(,)? }) => (
76 TokenTree::$ty(self::$ty {
77 $($field $(: $value)*,)+
81 ($ty:ident::$method:ident($($value:expr),*)) => (
82 TokenTree::$ty(self::$ty::$method($($value,)* span))
87 tt!(Punct::new($a, joint))
89 ($a:expr, $b:expr) => {{
90 stack.push(tt!(Punct::new($b, joint)));
91 tt!(Punct::new($a, true))
93 ($a:expr, $b:expr, $c:expr) => {{
94 stack.push(tt!(Punct::new($c, joint)));
95 stack.push(tt!(Punct::new($b, true)));
96 tt!(Punct::new($a, true))
104 EqEq => op!('=', '='),
108 AndAnd => op!('&', '&'),
109 OrOr => op!('|', '|'),
112 BinOp(Plus) => op!('+'),
113 BinOp(Minus) => op!('-'),
114 BinOp(Star) => op!('*'),
115 BinOp(Slash) => op!('/'),
116 BinOp(Percent) => op!('%'),
117 BinOp(Caret) => op!('^'),
118 BinOp(And) => op!('&'),
119 BinOp(Or) => op!('|'),
120 BinOp(Shl) => op!('<', '<'),
121 BinOp(Shr) => op!('>', '>'),
122 BinOpEq(Plus) => op!('+', '='),
123 BinOpEq(Minus) => op!('-', '='),
124 BinOpEq(Star) => op!('*', '='),
125 BinOpEq(Slash) => op!('/', '='),
126 BinOpEq(Percent) => op!('%', '='),
127 BinOpEq(Caret) => op!('^', '='),
128 BinOpEq(And) => op!('&', '='),
129 BinOpEq(Or) => op!('|', '='),
130 BinOpEq(Shl) => op!('<', '<', '='),
131 BinOpEq(Shr) => op!('>', '>', '='),
134 DotDot => op!('.', '.'),
135 DotDotDot => op!('.', '.', '.'),
136 DotDotEq => op!('.', '.', '='),
140 ModSep => op!(':', ':'),
141 RArrow => op!('-', '>'),
142 LArrow => op!('<', '-'),
143 FatArrow => op!('=', '>'),
146 Question => op!('?'),
147 SingleQuote => op!('\''),
149 Ident(name, false) if name == kw::DollarCrate => tt!(Ident::dollar_crate()),
150 Ident(name, is_raw) => tt!(Ident::new(rustc.sess, name, is_raw)),
152 let ident = symbol::Ident::new(name, span).without_first_quote();
153 stack.push(tt!(Ident::new(rustc.sess, ident.name, false)));
154 tt!(Punct::new('\'', true))
156 Literal(lit) => tt!(Literal { lit }),
157 DocComment(_, attr_style, data) => {
158 let mut escaped = String::new();
159 for ch in data.as_str().chars() {
160 escaped.extend(ch.escape_debug());
163 Ident(sym::doc, false),
165 TokenKind::lit(token::Str, Symbol::intern(&escaped), None),
168 .map(|kind| tokenstream::TokenTree::token(kind, span))
170 stack.push(TokenTree::Group(Group {
171 delimiter: Delimiter::Bracket,
173 span: DelimSpan::from_single(span),
176 if attr_style == ast::AttrStyle::Inner {
177 stack.push(tt!(Punct::new('!', false)));
179 tt!(Punct::new('#', false))
182 Interpolated(nt) => {
183 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 let stream = nt_to_tokenstream(&nt, rustc.sess, CanSynthesizeMissingTokens::No);
187 TokenTree::Group(Group {
188 delimiter: Delimiter::None,
190 span: DelimSpan::from_single(span),
191 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 vec![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 vec![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,
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> {
359 resolver: &'a dyn ResolverExpand,
367 rebased_spans: FxHashMap<usize, Span>,
371 pub fn new(cx: &'a ExtCtxt<'_>, krate: CrateNum) -> Self {
372 let expn_data = cx.current_expansion.id.expn_data();
373 let def_site = cx.with_def_site_ctxt(expn_data.def_site);
374 let call_site = cx.with_call_site_ctxt(expn_data.call_site);
375 let mixed_site = cx.with_mixed_site_ctxt(expn_data.call_site);
376 let sess = cx.parse_sess();
378 resolver: cx.resolver,
383 span_debug: cx.ecfg.span_debug,
385 expn_id: cx.current_expansion.id,
386 rebased_spans: FxHashMap::default(),
390 fn lit(&mut self, kind: token::LitKind, symbol: Symbol, suffix: Option<Symbol>) -> Literal {
391 Literal { lit: token::Lit::new(kind, symbol, suffix), span: server::Span::call_site(self) }
395 impl server::Types for Rustc<'_> {
396 type FreeFunctions = FreeFunctions;
397 type TokenStream = TokenStream;
398 type TokenStreamBuilder = tokenstream::TokenStreamBuilder;
399 type TokenStreamIter = TokenStreamIter;
403 type Literal = Literal;
404 type SourceFile = Lrc<SourceFile>;
405 type MultiSpan = Vec<Span>;
406 type Diagnostic = Diagnostic;
410 impl server::FreeFunctions for Rustc<'_> {
411 fn track_env_var(&mut self, var: &str, value: Option<&str>) {
412 self.sess.env_depinfo.borrow_mut().insert((Symbol::intern(var), value.map(Symbol::intern)));
415 fn track_path(&mut self, path: &str) {
416 self.sess.file_depinfo.borrow_mut().insert(Symbol::intern(path));
420 impl server::TokenStream for Rustc<'_> {
421 fn new(&mut self) -> Self::TokenStream {
422 TokenStream::default()
424 fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
427 fn from_str(&mut self, src: &str) -> Self::TokenStream {
428 parse_stream_from_source_str(
429 FileName::proc_macro_source_code(src),
432 Some(self.call_site),
435 fn to_string(&mut self, stream: &Self::TokenStream) -> String {
436 pprust::tts_to_string(stream)
440 tree: TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>,
441 ) -> Self::TokenStream {
444 fn into_iter(&mut self, stream: Self::TokenStream) -> Self::TokenStreamIter {
445 TokenStreamIter { cursor: stream.trees(), stack: vec![] }
449 impl server::TokenStreamBuilder for Rustc<'_> {
450 fn new(&mut self) -> Self::TokenStreamBuilder {
451 tokenstream::TokenStreamBuilder::new()
453 fn push(&mut self, builder: &mut Self::TokenStreamBuilder, stream: Self::TokenStream) {
454 builder.push(stream);
456 fn build(&mut self, builder: Self::TokenStreamBuilder) -> Self::TokenStream {
461 impl server::TokenStreamIter for Rustc<'_> {
464 iter: &mut Self::TokenStreamIter,
465 ) -> Option<TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>> {
467 let tree = iter.stack.pop().or_else(|| {
468 let next = iter.cursor.next_with_spacing()?;
469 Some(TokenTree::from_internal((next, &mut iter.stack, self)))
471 // A hack used to pass AST fragments to attribute and derive macros
472 // as a single nonterminal token instead of a token stream.
473 // Such token needs to be "unwrapped" and not represented as a delimited group.
474 // FIXME: It needs to be removed, but there are some compatibility issues (see #73345).
475 if let TokenTree::Group(ref group) = tree {
477 iter.cursor.append(group.stream.clone());
486 impl server::Group for Rustc<'_> {
487 fn new(&mut self, delimiter: Delimiter, stream: Self::TokenStream) -> Self::Group {
491 span: DelimSpan::from_single(server::Span::call_site(self)),
495 fn delimiter(&mut self, group: &Self::Group) -> Delimiter {
498 fn stream(&mut self, group: &Self::Group) -> Self::TokenStream {
501 fn span(&mut self, group: &Self::Group) -> Self::Span {
504 fn span_open(&mut self, group: &Self::Group) -> Self::Span {
507 fn span_close(&mut self, group: &Self::Group) -> Self::Span {
510 fn set_span(&mut self, group: &mut Self::Group, span: Self::Span) {
511 group.span = DelimSpan::from_single(span);
515 impl server::Punct for Rustc<'_> {
516 fn new(&mut self, ch: char, spacing: Spacing) -> Self::Punct {
517 Punct::new(ch, spacing == Spacing::Joint, server::Span::call_site(self))
519 fn as_char(&mut self, punct: Self::Punct) -> char {
522 fn spacing(&mut self, punct: Self::Punct) -> Spacing {
523 if punct.joint { Spacing::Joint } else { Spacing::Alone }
525 fn span(&mut self, punct: Self::Punct) -> Self::Span {
528 fn with_span(&mut self, punct: Self::Punct, span: Self::Span) -> Self::Punct {
529 Punct { span, ..punct }
533 impl server::Ident for Rustc<'_> {
534 fn new(&mut self, string: &str, span: Self::Span, is_raw: bool) -> Self::Ident {
535 Ident::new(self.sess, Symbol::intern(string), is_raw, span)
537 fn span(&mut self, ident: Self::Ident) -> Self::Span {
540 fn with_span(&mut self, ident: Self::Ident, span: Self::Span) -> Self::Ident {
541 Ident { span, ..ident }
545 impl server::Literal for Rustc<'_> {
546 fn from_str(&mut self, s: &str) -> Result<Self::Literal, ()> {
547 let override_span = None;
548 let stream = parse_stream_from_source_str(
549 FileName::proc_macro_source_code(s),
554 if stream.len() != 1 {
557 let tree = stream.into_trees().next().unwrap();
558 let token = match tree {
559 tokenstream::TokenTree::Token(token) => token,
560 tokenstream::TokenTree::Delimited { .. } => return Err(()),
562 let span_data = token.span.data();
563 if (span_data.hi.0 - span_data.lo.0) as usize != s.len() {
564 // There is a comment or whitespace adjacent to the literal.
567 let lit = match token.kind {
568 TokenKind::Literal(lit) => lit,
571 Ok(Literal { lit, span: self.call_site })
573 fn debug_kind(&mut self, literal: &Self::Literal) -> String {
574 format!("{:?}", literal.lit.kind)
576 fn symbol(&mut self, literal: &Self::Literal) -> String {
577 literal.lit.symbol.to_string()
579 fn suffix(&mut self, literal: &Self::Literal) -> Option<String> {
580 literal.lit.suffix.as_ref().map(Symbol::to_string)
582 fn integer(&mut self, n: &str) -> Self::Literal {
583 self.lit(token::Integer, Symbol::intern(n), None)
585 fn typed_integer(&mut self, n: &str, kind: &str) -> Self::Literal {
586 self.lit(token::Integer, Symbol::intern(n), Some(Symbol::intern(kind)))
588 fn float(&mut self, n: &str) -> Self::Literal {
589 self.lit(token::Float, Symbol::intern(n), None)
591 fn f32(&mut self, n: &str) -> Self::Literal {
592 self.lit(token::Float, Symbol::intern(n), Some(sym::f32))
594 fn f64(&mut self, n: &str) -> Self::Literal {
595 self.lit(token::Float, Symbol::intern(n), Some(sym::f64))
597 fn string(&mut self, string: &str) -> Self::Literal {
598 let mut escaped = String::new();
599 for ch in string.chars() {
600 escaped.extend(ch.escape_debug());
602 self.lit(token::Str, Symbol::intern(&escaped), None)
604 fn character(&mut self, ch: char) -> Self::Literal {
605 let mut escaped = String::new();
606 escaped.extend(ch.escape_unicode());
607 self.lit(token::Char, Symbol::intern(&escaped), None)
609 fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
613 .flat_map(ascii::escape_default)
614 .map(Into::<char>::into)
615 .collect::<String>();
616 self.lit(token::ByteStr, Symbol::intern(&string), None)
618 fn span(&mut self, literal: &Self::Literal) -> Self::Span {
621 fn set_span(&mut self, literal: &mut Self::Literal, span: Self::Span) {
626 literal: &Self::Literal,
629 ) -> Option<Self::Span> {
630 let span = literal.span;
631 let length = span.hi().to_usize() - span.lo().to_usize();
633 let start = match start {
634 Bound::Included(lo) => lo,
635 Bound::Excluded(lo) => lo.checked_add(1)?,
636 Bound::Unbounded => 0,
639 let end = match end {
640 Bound::Included(hi) => hi.checked_add(1)?,
641 Bound::Excluded(hi) => hi,
642 Bound::Unbounded => length,
645 // Bounds check the values, preventing addition overflow and OOB spans.
646 if start > u32::MAX as usize
647 || end > u32::MAX as usize
648 || (u32::MAX - start as u32) < span.lo().to_u32()
649 || (u32::MAX - end as u32) < span.lo().to_u32()
656 let new_lo = span.lo() + BytePos::from_usize(start);
657 let new_hi = span.lo() + BytePos::from_usize(end);
658 Some(span.with_lo(new_lo).with_hi(new_hi))
662 impl server::SourceFile for Rustc<'_> {
663 fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
664 Lrc::ptr_eq(file1, file2)
666 fn path(&mut self, file: &Self::SourceFile) -> String {
668 FileName::Real(ref name) => name
670 .expect("attempting to get a file path in an imported file in `proc_macro::SourceFile::path`")
672 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
674 _ => file.name.prefer_local().to_string(),
677 fn is_real(&mut self, file: &Self::SourceFile) -> bool {
682 impl server::MultiSpan for Rustc<'_> {
683 fn new(&mut self) -> Self::MultiSpan {
686 fn push(&mut self, spans: &mut Self::MultiSpan, span: Self::Span) {
691 impl server::Diagnostic for Rustc<'_> {
692 fn new(&mut self, level: Level, msg: &str, spans: Self::MultiSpan) -> Self::Diagnostic {
693 let mut diag = Diagnostic::new(level.to_internal(), msg);
694 diag.set_span(MultiSpan::from_spans(spans));
699 diag: &mut Self::Diagnostic,
702 spans: Self::MultiSpan,
704 diag.sub(level.to_internal(), msg, MultiSpan::from_spans(spans), None);
706 fn emit(&mut self, diag: Self::Diagnostic) {
707 self.sess.span_diagnostic.emit_diagnostic(&diag);
711 impl server::Span for Rustc<'_> {
712 fn debug(&mut self, span: Self::Span) -> String {
714 format!("{:?}", span)
716 format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
719 fn def_site(&mut self) -> Self::Span {
722 fn call_site(&mut self) -> Self::Span {
725 fn mixed_site(&mut self) -> Self::Span {
728 fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
729 self.sess.source_map().lookup_char_pos(span.lo()).file
731 fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
734 fn source(&mut self, span: Self::Span) -> Self::Span {
735 span.source_callsite()
737 fn start(&mut self, span: Self::Span) -> LineColumn {
738 let loc = self.sess.source_map().lookup_char_pos(span.lo());
739 LineColumn { line: loc.line, column: loc.col.to_usize() }
741 fn end(&mut self, span: Self::Span) -> LineColumn {
742 let loc = self.sess.source_map().lookup_char_pos(span.hi());
743 LineColumn { line: loc.line, column: loc.col.to_usize() }
745 fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
746 let self_loc = self.sess.source_map().lookup_char_pos(first.lo());
747 let other_loc = self.sess.source_map().lookup_char_pos(second.lo());
749 if self_loc.file.name != other_loc.file.name {
753 Some(first.to(second))
755 fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
756 span.with_ctxt(at.ctxt())
758 fn source_text(&mut self, span: Self::Span) -> Option<String> {
759 self.sess.source_map().span_to_snippet(span).ok()
761 /// Saves the provided span into the metadata of
762 /// *the crate we are currently compiling*, which must
763 /// be a proc-macro crate. This id can be passed to
764 /// `recover_proc_macro_span` when our current crate
765 /// is *run* as a proc-macro.
767 /// Let's suppose that we have two crates - `my_client`
768 /// and `my_proc_macro`. The `my_proc_macro` crate
769 /// contains a procedural macro `my_macro`, which
770 /// is implemented as: `quote! { "hello" }`
772 /// When we *compile* `my_proc_macro`, we will execute
773 /// the `quote` proc-macro. This will save the span of
774 /// "hello" into the metadata of `my_proc_macro`. As a result,
775 /// the body of `my_proc_macro` (after expansion) will end
776 /// up containg a call that looks like this:
777 /// `proc_macro::Ident::new("hello", proc_macro::Span::recover_proc_macro_span(0))`
779 /// where `0` is the id returned by this function.
780 /// When `my_proc_macro` *executes* (during the compilation of `my_client`),
781 /// the call to `recover_proc_macro_span` will load the corresponding
782 /// span from the metadata of `my_proc_macro` (which we have access to,
783 /// since we've loaded `my_proc_macro` from disk in order to execute it).
784 /// In this way, we have obtained a span pointing into `my_proc_macro`
785 fn save_span(&mut self, mut span: Self::Span) -> usize {
786 // Throw away the `SyntaxContext`, since we currently
787 // skip serializing `SyntaxContext`s for proc-macro crates
788 span = span.with_ctxt(rustc_span::SyntaxContext::root());
789 self.sess.save_proc_macro_span(span)
791 fn recover_proc_macro_span(&mut self, id: usize) -> Self::Span {
792 let resolver = self.resolver;
793 let krate = self.krate;
794 let expn_id = self.expn_id;
795 *self.rebased_spans.entry(id).or_insert_with(|| {
796 let raw_span = resolver.get_proc_macro_quoted_span(krate, id);
797 // Ignore the deserialized `SyntaxContext` entirely.
798 // FIXME: Preserve the macro backtrace from the serialized span
799 // For example, if a proc-macro crate has code like
800 // `macro_one!() -> macro_two!() -> quote!()`, we might
801 // want to 'concatenate' this backtrace with the backtrace from
802 // our current call site.
803 raw_span.with_def_site_ctxt(expn_id)
808 // See issue #74616 for details
809 fn ident_name_compatibility_hack(
812 rustc: &mut Rustc<'_>,
813 ) -> Option<(rustc_span::symbol::Ident, bool)> {
814 if let NtIdent(ident, is_raw) = nt {
815 if let ExpnKind::Macro { name: macro_name, .. } = orig_span.ctxt().outer_expn_data().kind {
816 let source_map = rustc.sess.source_map();
817 let filename = source_map.span_to_filename(orig_span);
818 if let FileName::Real(RealFileName::LocalPath(path)) = filename {
819 let matches_prefix = |prefix, filename| {
820 // Check for a path that ends with 'prefix*/src/<filename>'
821 let mut iter = path.components().rev();
822 iter.next().and_then(|p| p.as_os_str().to_str()) == Some(filename)
823 && iter.next().and_then(|p| p.as_os_str().to_str()) == Some("src")
826 .and_then(|p| p.as_os_str().to_str())
827 .map_or(false, |p| p.starts_with(prefix))
830 let time_macros_impl =
831 macro_name == sym::impl_macros && matches_prefix("time-macros-impl", "lib.rs");
832 let js_sys = macro_name == sym::arrays && matches_prefix("js-sys", "lib.rs");
833 if time_macros_impl || js_sys {
834 let snippet = source_map.span_to_snippet(orig_span);
835 if snippet.as_deref() == Ok("$name") {
836 if time_macros_impl {
837 rustc.sess.buffer_lint_with_diagnostic(
838 &PROC_MACRO_BACK_COMPAT,
841 "using an old version of `time-macros-impl`",
842 BuiltinLintDiagnostics::ProcMacroBackCompat(
843 "the `time-macros-impl` crate will stop compiling in futures version of Rust. \
844 Please update to the latest version of the `time` crate to avoid breakage".to_string())
846 return Some((*ident, *is_raw));
849 if let Some(c) = path
851 .flat_map(|c| c.as_os_str().to_str())
852 .find(|c| c.starts_with("js-sys"))
854 let mut version = c.trim_start_matches("js-sys-").split(".");
855 if version.next() == Some("0")
856 && version.next() == Some("3")
859 .and_then(|c| c.parse::<u32>().ok())
860 .map_or(false, |v| v < 40)
862 rustc.sess.buffer_lint_with_diagnostic(
863 &PROC_MACRO_BACK_COMPAT,
866 "using an old version of `js-sys`",
867 BuiltinLintDiagnostics::ProcMacroBackCompat(
868 "older versions of the `js-sys` crate will stop compiling in future versions of Rust; \
869 please update to `js-sys` v0.3.40 or above".to_string())
871 return Some((*ident, *is_raw));
878 if macro_name == sym::tuple_from_req && matches_prefix("actix-web", "extract.rs") {
879 let snippet = source_map.span_to_snippet(orig_span);
880 if snippet.as_deref() == Ok("$T") {
881 if let FileName::Real(RealFileName::LocalPath(macro_path)) =
882 source_map.span_to_filename(rustc.def_site)
884 if macro_path.to_string_lossy().contains("pin-project-internal-0.") {
885 rustc.sess.buffer_lint_with_diagnostic(
886 &PROC_MACRO_BACK_COMPAT,
889 "using an old version of `actix-web`",
890 BuiltinLintDiagnostics::ProcMacroBackCompat(
891 "the version of `actix-web` you are using might stop compiling in future versions of Rust; \
892 please update to the latest version of the `actix-web` crate to avoid breakage".to_string())
894 return Some((*ident, *is_raw));