]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_expand/src/proc_macro_server.rs
Rollup merge of #83277 - spastorino:early_otherwise-opt-unsound, r=oli-obk
[rust.git] / compiler / rustc_expand / src / proc_macro_server.rs
1 use crate::base::ExtCtxt;
2
3 use rustc_ast as ast;
4 use rustc_ast::token;
5 use rustc_ast::token::Nonterminal;
6 use rustc_ast::token::NtIdent;
7 use rustc_ast::tokenstream::{self, CanSynthesizeMissingTokens};
8 use rustc_ast::tokenstream::{DelimSpan, Spacing::*, TokenStream, TreeAndSpacing};
9 use rustc_ast_pretty::pprust;
10 use rustc_data_structures::sync::Lrc;
11 use rustc_errors::Diagnostic;
12 use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT;
13 use rustc_lint_defs::BuiltinLintDiagnostics;
14 use rustc_parse::lexer::nfc_normalize;
15 use rustc_parse::{nt_to_tokenstream, parse_stream_from_source_str};
16 use rustc_session::parse::ParseSess;
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};
20
21 use pm::bridge::{server, TokenTree};
22 use pm::{Delimiter, Level, LineColumn, Spacing};
23 use std::ops::Bound;
24 use std::{ascii, panic};
25
26 trait FromInternal<T> {
27     fn from_internal(x: T) -> Self;
28 }
29
30 trait ToInternal<T> {
31     fn to_internal(self) -> T;
32 }
33
34 impl FromInternal<token::DelimToken> for Delimiter {
35     fn from_internal(delim: token::DelimToken) -> Delimiter {
36         match delim {
37             token::Paren => Delimiter::Parenthesis,
38             token::Brace => Delimiter::Brace,
39             token::Bracket => Delimiter::Bracket,
40             token::NoDelim => Delimiter::None,
41         }
42     }
43 }
44
45 impl ToInternal<token::DelimToken> for Delimiter {
46     fn to_internal(self) -> token::DelimToken {
47         match self {
48             Delimiter::Parenthesis => token::Paren,
49             Delimiter::Brace => token::Brace,
50             Delimiter::Bracket => token::Bracket,
51             Delimiter::None => token::NoDelim,
52         }
53     }
54 }
55
56 impl FromInternal<(TreeAndSpacing, &'_ mut Vec<Self>, &mut Rustc<'_>)>
57     for TokenTree<Group, Punct, Ident, Literal>
58 {
59     fn from_internal(
60         ((tree, spacing), stack, rustc): (TreeAndSpacing, &mut Vec<Self>, &mut Rustc<'_>),
61     ) -> Self {
62         use rustc_ast::token::*;
63
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 });
69             }
70             tokenstream::TokenTree::Token(token) => token,
71         };
72
73         macro_rules! tt {
74             ($ty:ident { $($field:ident $(: $value:expr)*),+ $(,)? }) => (
75                 TokenTree::$ty(self::$ty {
76                     $($field $(: $value)*,)+
77                     span,
78                 })
79             );
80             ($ty:ident::$method:ident($($value:expr),*)) => (
81                 TokenTree::$ty(self::$ty::$method($($value,)* span))
82             );
83         }
84         macro_rules! op {
85             ($a:expr) => {
86                 tt!(Punct::new($a, joint))
87             };
88             ($a:expr, $b:expr) => {{
89                 stack.push(tt!(Punct::new($b, joint)));
90                 tt!(Punct::new($a, true))
91             }};
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))
96             }};
97         }
98
99         match kind {
100             Eq => op!('='),
101             Lt => op!('<'),
102             Le => op!('<', '='),
103             EqEq => op!('=', '='),
104             Ne => op!('!', '='),
105             Ge => op!('>', '='),
106             Gt => op!('>'),
107             AndAnd => op!('&', '&'),
108             OrOr => op!('|', '|'),
109             Not => op!('!'),
110             Tilde => 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!('>', '>', '='),
131             At => op!('@'),
132             Dot => op!('.'),
133             DotDot => op!('.', '.'),
134             DotDotDot => op!('.', '.', '.'),
135             DotDotEq => op!('.', '.', '='),
136             Comma => op!(','),
137             Semi => op!(';'),
138             Colon => op!(':'),
139             ModSep => op!(':', ':'),
140             RArrow => op!('-', '>'),
141             LArrow => op!('<', '-'),
142             FatArrow => op!('=', '>'),
143             Pound => op!('#'),
144             Dollar => op!('$'),
145             Question => op!('?'),
146             SingleQuote => op!('\''),
147
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)),
150             Lifetime(name) => {
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))
154             }
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());
160                 }
161                 let stream = vec![
162                     Ident(sym::doc, false),
163                     Eq,
164                     TokenKind::lit(token::Str, Symbol::intern(&escaped), None),
165                 ]
166                 .into_iter()
167                 .map(|kind| tokenstream::TokenTree::token(kind, span))
168                 .collect();
169                 stack.push(TokenTree::Group(Group {
170                     delimiter: Delimiter::Bracket,
171                     stream,
172                     span: DelimSpan::from_single(span),
173                     flatten: false,
174                 }));
175                 if attr_style == ast::AttrStyle::Inner {
176                     stack.push(tt!(Punct::new('!', false)));
177                 }
178                 tt!(Punct::new('#', false))
179             }
180
181             Interpolated(nt) => {
182                 if let Some((name, is_raw)) = ident_name_compatibility_hack(&nt, span, rustc) {
183                     TokenTree::Ident(Ident::new(rustc.sess, name.name, is_raw, name.span))
184                 } else {
185                     let stream = nt_to_tokenstream(&nt, rustc.sess, CanSynthesizeMissingTokens::No);
186                     TokenTree::Group(Group {
187                         delimiter: Delimiter::None,
188                         stream,
189                         span: DelimSpan::from_single(span),
190                         flatten: crate::base::pretty_printing_compatibility_hack(&nt, rustc.sess),
191                     })
192                 }
193             }
194
195             OpenDelim(..) | CloseDelim(..) => unreachable!(),
196             Eof => unreachable!(),
197         }
198     }
199 }
200
201 impl ToInternal<TokenStream> for TokenTree<Group, Punct, Ident, Literal> {
202     fn to_internal(self) -> TokenStream {
203         use rustc_ast::token::*;
204
205         let (ch, joint, span) = match self {
206             TokenTree::Punct(Punct { ch, joint, span }) => (ch, joint, span),
207             TokenTree::Group(Group { delimiter, stream, span, .. }) => {
208                 return tokenstream::TokenTree::Delimited(span, delimiter.to_internal(), stream)
209                     .into();
210             }
211             TokenTree::Ident(self::Ident { sym, is_raw, span }) => {
212                 return tokenstream::TokenTree::token(Ident(sym, is_raw), span).into();
213             }
214             TokenTree::Literal(self::Literal {
215                 lit: token::Lit { kind: token::Integer, symbol, suffix },
216                 span,
217             }) if symbol.as_str().starts_with('-') => {
218                 let minus = BinOp(BinOpToken::Minus);
219                 let symbol = Symbol::intern(&symbol.as_str()[1..]);
220                 let integer = TokenKind::lit(token::Integer, symbol, suffix);
221                 let a = tokenstream::TokenTree::token(minus, span);
222                 let b = tokenstream::TokenTree::token(integer, span);
223                 return vec![a, b].into_iter().collect();
224             }
225             TokenTree::Literal(self::Literal {
226                 lit: token::Lit { kind: token::Float, symbol, suffix },
227                 span,
228             }) if symbol.as_str().starts_with('-') => {
229                 let minus = BinOp(BinOpToken::Minus);
230                 let symbol = Symbol::intern(&symbol.as_str()[1..]);
231                 let float = TokenKind::lit(token::Float, symbol, suffix);
232                 let a = tokenstream::TokenTree::token(minus, span);
233                 let b = tokenstream::TokenTree::token(float, span);
234                 return vec![a, b].into_iter().collect();
235             }
236             TokenTree::Literal(self::Literal { lit, span }) => {
237                 return tokenstream::TokenTree::token(Literal(lit), span).into();
238             }
239         };
240
241         let kind = match ch {
242             '=' => Eq,
243             '<' => Lt,
244             '>' => Gt,
245             '!' => Not,
246             '~' => Tilde,
247             '+' => BinOp(Plus),
248             '-' => BinOp(Minus),
249             '*' => BinOp(Star),
250             '/' => BinOp(Slash),
251             '%' => BinOp(Percent),
252             '^' => BinOp(Caret),
253             '&' => BinOp(And),
254             '|' => BinOp(Or),
255             '@' => At,
256             '.' => Dot,
257             ',' => Comma,
258             ';' => Semi,
259             ':' => Colon,
260             '#' => Pound,
261             '$' => Dollar,
262             '?' => Question,
263             '\'' => SingleQuote,
264             _ => unreachable!(),
265         };
266
267         let tree = tokenstream::TokenTree::token(kind, span);
268         TokenStream::new(vec![(tree, if joint { Joint } else { Alone })])
269     }
270 }
271
272 impl ToInternal<rustc_errors::Level> for Level {
273     fn to_internal(self) -> rustc_errors::Level {
274         match self {
275             Level::Error => rustc_errors::Level::Error,
276             Level::Warning => rustc_errors::Level::Warning,
277             Level::Note => rustc_errors::Level::Note,
278             Level::Help => rustc_errors::Level::Help,
279             _ => unreachable!("unknown proc_macro::Level variant: {:?}", self),
280         }
281     }
282 }
283
284 pub struct FreeFunctions;
285
286 #[derive(Clone)]
287 pub struct TokenStreamIter {
288     cursor: tokenstream::Cursor,
289     stack: Vec<TokenTree<Group, Punct, Ident, Literal>>,
290 }
291
292 #[derive(Clone)]
293 pub struct Group {
294     delimiter: Delimiter,
295     stream: TokenStream,
296     span: DelimSpan,
297     /// A hack used to pass AST fragments to attribute and derive macros
298     /// as a single nonterminal token instead of a token stream.
299     /// FIXME: It needs to be removed, but there are some compatibility issues (see #73345).
300     flatten: bool,
301 }
302
303 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
304 pub struct Punct {
305     ch: char,
306     // NB. not using `Spacing` here because it doesn't implement `Hash`.
307     joint: bool,
308     span: Span,
309 }
310
311 impl Punct {
312     fn new(ch: char, joint: bool, span: Span) -> Punct {
313         const LEGAL_CHARS: &[char] = &[
314             '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
315             ':', '#', '$', '?', '\'',
316         ];
317         if !LEGAL_CHARS.contains(&ch) {
318             panic!("unsupported character `{:?}`", ch)
319         }
320         Punct { ch, joint, span }
321     }
322 }
323
324 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
325 pub struct Ident {
326     sym: Symbol,
327     is_raw: bool,
328     span: Span,
329 }
330
331 impl Ident {
332     fn new(sess: &ParseSess, sym: Symbol, is_raw: bool, span: Span) -> Ident {
333         let sym = nfc_normalize(&sym.as_str());
334         let string = sym.as_str();
335         if !rustc_lexer::is_ident(&string) {
336             panic!("`{:?}` is not a valid identifier", string)
337         }
338         if is_raw && !sym.can_be_raw() {
339             panic!("`{}` cannot be a raw identifier", string);
340         }
341         sess.symbol_gallery.insert(sym, span);
342         Ident { sym, is_raw, span }
343     }
344     fn dollar_crate(span: Span) -> Ident {
345         // `$crate` is accepted as an ident only if it comes from the compiler.
346         Ident { sym: kw::DollarCrate, is_raw: false, span }
347     }
348 }
349
350 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
351 #[derive(Clone, Debug)]
352 pub struct Literal {
353     lit: token::Lit,
354     span: Span,
355 }
356
357 pub(crate) struct Rustc<'a> {
358     sess: &'a ParseSess,
359     def_site: Span,
360     call_site: Span,
361     mixed_site: Span,
362     span_debug: bool,
363 }
364
365 impl<'a> Rustc<'a> {
366     pub fn new(cx: &'a ExtCtxt<'_>) -> Self {
367         let expn_data = cx.current_expansion.id.expn_data();
368         Rustc {
369             sess: &cx.sess.parse_sess,
370             def_site: cx.with_def_site_ctxt(expn_data.def_site),
371             call_site: cx.with_call_site_ctxt(expn_data.call_site),
372             mixed_site: cx.with_mixed_site_ctxt(expn_data.call_site),
373             span_debug: cx.ecfg.span_debug,
374         }
375     }
376
377     fn lit(&mut self, kind: token::LitKind, symbol: Symbol, suffix: Option<Symbol>) -> Literal {
378         Literal { lit: token::Lit::new(kind, symbol, suffix), span: server::Span::call_site(self) }
379     }
380 }
381
382 impl server::Types for Rustc<'_> {
383     type FreeFunctions = FreeFunctions;
384     type TokenStream = TokenStream;
385     type TokenStreamBuilder = tokenstream::TokenStreamBuilder;
386     type TokenStreamIter = TokenStreamIter;
387     type Group = Group;
388     type Punct = Punct;
389     type Ident = Ident;
390     type Literal = Literal;
391     type SourceFile = Lrc<SourceFile>;
392     type MultiSpan = Vec<Span>;
393     type Diagnostic = Diagnostic;
394     type Span = Span;
395 }
396
397 impl server::FreeFunctions for Rustc<'_> {
398     fn track_env_var(&mut self, var: &str, value: Option<&str>) {
399         self.sess.env_depinfo.borrow_mut().insert((Symbol::intern(var), value.map(Symbol::intern)));
400     }
401 }
402
403 impl server::TokenStream for Rustc<'_> {
404     fn new(&mut self) -> Self::TokenStream {
405         TokenStream::default()
406     }
407     fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
408         stream.is_empty()
409     }
410     fn from_str(&mut self, src: &str) -> Self::TokenStream {
411         parse_stream_from_source_str(
412             FileName::proc_macro_source_code(src),
413             src.to_string(),
414             self.sess,
415             Some(self.call_site),
416         )
417     }
418     fn to_string(&mut self, stream: &Self::TokenStream) -> String {
419         pprust::tts_to_string(stream)
420     }
421     fn from_token_tree(
422         &mut self,
423         tree: TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>,
424     ) -> Self::TokenStream {
425         tree.to_internal()
426     }
427     fn into_iter(&mut self, stream: Self::TokenStream) -> Self::TokenStreamIter {
428         TokenStreamIter { cursor: stream.trees(), stack: vec![] }
429     }
430 }
431
432 impl server::TokenStreamBuilder for Rustc<'_> {
433     fn new(&mut self) -> Self::TokenStreamBuilder {
434         tokenstream::TokenStreamBuilder::new()
435     }
436     fn push(&mut self, builder: &mut Self::TokenStreamBuilder, stream: Self::TokenStream) {
437         builder.push(stream);
438     }
439     fn build(&mut self, builder: Self::TokenStreamBuilder) -> Self::TokenStream {
440         builder.build()
441     }
442 }
443
444 impl server::TokenStreamIter for Rustc<'_> {
445     fn next(
446         &mut self,
447         iter: &mut Self::TokenStreamIter,
448     ) -> Option<TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>> {
449         loop {
450             let tree = iter.stack.pop().or_else(|| {
451                 let next = iter.cursor.next_with_spacing()?;
452                 Some(TokenTree::from_internal((next, &mut iter.stack, self)))
453             })?;
454             // A hack used to pass AST fragments to attribute and derive macros
455             // as a single nonterminal token instead of a token stream.
456             // Such token needs to be "unwrapped" and not represented as a delimited group.
457             // FIXME: It needs to be removed, but there are some compatibility issues (see #73345).
458             if let TokenTree::Group(ref group) = tree {
459                 if group.flatten {
460                     iter.cursor.append(group.stream.clone());
461                     continue;
462                 }
463             }
464             return Some(tree);
465         }
466     }
467 }
468
469 impl server::Group for Rustc<'_> {
470     fn new(&mut self, delimiter: Delimiter, stream: Self::TokenStream) -> Self::Group {
471         Group {
472             delimiter,
473             stream,
474             span: DelimSpan::from_single(server::Span::call_site(self)),
475             flatten: false,
476         }
477     }
478     fn delimiter(&mut self, group: &Self::Group) -> Delimiter {
479         group.delimiter
480     }
481     fn stream(&mut self, group: &Self::Group) -> Self::TokenStream {
482         group.stream.clone()
483     }
484     fn span(&mut self, group: &Self::Group) -> Self::Span {
485         group.span.entire()
486     }
487     fn span_open(&mut self, group: &Self::Group) -> Self::Span {
488         group.span.open
489     }
490     fn span_close(&mut self, group: &Self::Group) -> Self::Span {
491         group.span.close
492     }
493     fn set_span(&mut self, group: &mut Self::Group, span: Self::Span) {
494         group.span = DelimSpan::from_single(span);
495     }
496 }
497
498 impl server::Punct for Rustc<'_> {
499     fn new(&mut self, ch: char, spacing: Spacing) -> Self::Punct {
500         Punct::new(ch, spacing == Spacing::Joint, server::Span::call_site(self))
501     }
502     fn as_char(&mut self, punct: Self::Punct) -> char {
503         punct.ch
504     }
505     fn spacing(&mut self, punct: Self::Punct) -> Spacing {
506         if punct.joint { Spacing::Joint } else { Spacing::Alone }
507     }
508     fn span(&mut self, punct: Self::Punct) -> Self::Span {
509         punct.span
510     }
511     fn with_span(&mut self, punct: Self::Punct, span: Self::Span) -> Self::Punct {
512         Punct { span, ..punct }
513     }
514 }
515
516 impl server::Ident for Rustc<'_> {
517     fn new(&mut self, string: &str, span: Self::Span, is_raw: bool) -> Self::Ident {
518         Ident::new(self.sess, Symbol::intern(string), is_raw, span)
519     }
520     fn span(&mut self, ident: Self::Ident) -> Self::Span {
521         ident.span
522     }
523     fn with_span(&mut self, ident: Self::Ident, span: Self::Span) -> Self::Ident {
524         Ident { span, ..ident }
525     }
526 }
527
528 impl server::Literal for Rustc<'_> {
529     fn debug_kind(&mut self, literal: &Self::Literal) -> String {
530         format!("{:?}", literal.lit.kind)
531     }
532     fn symbol(&mut self, literal: &Self::Literal) -> String {
533         literal.lit.symbol.to_string()
534     }
535     fn suffix(&mut self, literal: &Self::Literal) -> Option<String> {
536         literal.lit.suffix.as_ref().map(Symbol::to_string)
537     }
538     fn integer(&mut self, n: &str) -> Self::Literal {
539         self.lit(token::Integer, Symbol::intern(n), None)
540     }
541     fn typed_integer(&mut self, n: &str, kind: &str) -> Self::Literal {
542         self.lit(token::Integer, Symbol::intern(n), Some(Symbol::intern(kind)))
543     }
544     fn float(&mut self, n: &str) -> Self::Literal {
545         self.lit(token::Float, Symbol::intern(n), None)
546     }
547     fn f32(&mut self, n: &str) -> Self::Literal {
548         self.lit(token::Float, Symbol::intern(n), Some(sym::f32))
549     }
550     fn f64(&mut self, n: &str) -> Self::Literal {
551         self.lit(token::Float, Symbol::intern(n), Some(sym::f64))
552     }
553     fn string(&mut self, string: &str) -> Self::Literal {
554         let mut escaped = String::new();
555         for ch in string.chars() {
556             escaped.extend(ch.escape_debug());
557         }
558         self.lit(token::Str, Symbol::intern(&escaped), None)
559     }
560     fn character(&mut self, ch: char) -> Self::Literal {
561         let mut escaped = String::new();
562         escaped.extend(ch.escape_unicode());
563         self.lit(token::Char, Symbol::intern(&escaped), None)
564     }
565     fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
566         let string = bytes
567             .iter()
568             .cloned()
569             .flat_map(ascii::escape_default)
570             .map(Into::<char>::into)
571             .collect::<String>();
572         self.lit(token::ByteStr, Symbol::intern(&string), None)
573     }
574     fn span(&mut self, literal: &Self::Literal) -> Self::Span {
575         literal.span
576     }
577     fn set_span(&mut self, literal: &mut Self::Literal, span: Self::Span) {
578         literal.span = span;
579     }
580     fn subspan(
581         &mut self,
582         literal: &Self::Literal,
583         start: Bound<usize>,
584         end: Bound<usize>,
585     ) -> Option<Self::Span> {
586         let span = literal.span;
587         let length = span.hi().to_usize() - span.lo().to_usize();
588
589         let start = match start {
590             Bound::Included(lo) => lo,
591             Bound::Excluded(lo) => lo.checked_add(1)?,
592             Bound::Unbounded => 0,
593         };
594
595         let end = match end {
596             Bound::Included(hi) => hi.checked_add(1)?,
597             Bound::Excluded(hi) => hi,
598             Bound::Unbounded => length,
599         };
600
601         // Bounds check the values, preventing addition overflow and OOB spans.
602         if start > u32::MAX as usize
603             || end > u32::MAX as usize
604             || (u32::MAX - start as u32) < span.lo().to_u32()
605             || (u32::MAX - end as u32) < span.lo().to_u32()
606             || start >= end
607             || end > length
608         {
609             return None;
610         }
611
612         let new_lo = span.lo() + BytePos::from_usize(start);
613         let new_hi = span.lo() + BytePos::from_usize(end);
614         Some(span.with_lo(new_lo).with_hi(new_hi))
615     }
616 }
617
618 impl server::SourceFile for Rustc<'_> {
619     fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
620         Lrc::ptr_eq(file1, file2)
621     }
622     fn path(&mut self, file: &Self::SourceFile) -> String {
623         match file.name {
624             FileName::Real(ref name) => name
625                 .local_path()
626                 .to_str()
627                 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
628                 .to_string(),
629             _ => file.name.to_string(),
630         }
631     }
632     fn is_real(&mut self, file: &Self::SourceFile) -> bool {
633         file.is_real_file()
634     }
635 }
636
637 impl server::MultiSpan for Rustc<'_> {
638     fn new(&mut self) -> Self::MultiSpan {
639         vec![]
640     }
641     fn push(&mut self, spans: &mut Self::MultiSpan, span: Self::Span) {
642         spans.push(span)
643     }
644 }
645
646 impl server::Diagnostic for Rustc<'_> {
647     fn new(&mut self, level: Level, msg: &str, spans: Self::MultiSpan) -> Self::Diagnostic {
648         let mut diag = Diagnostic::new(level.to_internal(), msg);
649         diag.set_span(MultiSpan::from_spans(spans));
650         diag
651     }
652     fn sub(
653         &mut self,
654         diag: &mut Self::Diagnostic,
655         level: Level,
656         msg: &str,
657         spans: Self::MultiSpan,
658     ) {
659         diag.sub(level.to_internal(), msg, MultiSpan::from_spans(spans), None);
660     }
661     fn emit(&mut self, diag: Self::Diagnostic) {
662         self.sess.span_diagnostic.emit_diagnostic(&diag);
663     }
664 }
665
666 impl server::Span for Rustc<'_> {
667     fn debug(&mut self, span: Self::Span) -> String {
668         if self.span_debug {
669             format!("{:?}", span)
670         } else {
671             format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
672         }
673     }
674     fn def_site(&mut self) -> Self::Span {
675         self.def_site
676     }
677     fn call_site(&mut self) -> Self::Span {
678         self.call_site
679     }
680     fn mixed_site(&mut self) -> Self::Span {
681         self.mixed_site
682     }
683     fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
684         self.sess.source_map().lookup_char_pos(span.lo()).file
685     }
686     fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
687         span.parent()
688     }
689     fn source(&mut self, span: Self::Span) -> Self::Span {
690         span.source_callsite()
691     }
692     fn start(&mut self, span: Self::Span) -> LineColumn {
693         let loc = self.sess.source_map().lookup_char_pos(span.lo());
694         LineColumn { line: loc.line, column: loc.col.to_usize() }
695     }
696     fn end(&mut self, span: Self::Span) -> LineColumn {
697         let loc = self.sess.source_map().lookup_char_pos(span.hi());
698         LineColumn { line: loc.line, column: loc.col.to_usize() }
699     }
700     fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
701         let self_loc = self.sess.source_map().lookup_char_pos(first.lo());
702         let other_loc = self.sess.source_map().lookup_char_pos(second.lo());
703
704         if self_loc.file.name != other_loc.file.name {
705             return None;
706         }
707
708         Some(first.to(second))
709     }
710     fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
711         span.with_ctxt(at.ctxt())
712     }
713     fn source_text(&mut self, span: Self::Span) -> Option<String> {
714         self.sess.source_map().span_to_snippet(span).ok()
715     }
716 }
717
718 // See issue #74616 for details
719 fn ident_name_compatibility_hack(
720     nt: &Nonterminal,
721     orig_span: Span,
722     rustc: &mut Rustc<'_>,
723 ) -> Option<(rustc_span::symbol::Ident, bool)> {
724     if let NtIdent(ident, is_raw) = nt {
725         if let ExpnKind::Macro(_, macro_name) = orig_span.ctxt().outer_expn_data().kind {
726             let source_map = rustc.sess.source_map();
727             let filename = source_map.span_to_filename(orig_span);
728             if let FileName::Real(RealFileName::Named(path)) = filename {
729                 let matches_prefix = |prefix, filename| {
730                     // Check for a path that ends with 'prefix*/src/<filename>'
731                     let mut iter = path.components().rev();
732                     iter.next().and_then(|p| p.as_os_str().to_str()) == Some(filename)
733                         && iter.next().and_then(|p| p.as_os_str().to_str()) == Some("src")
734                         && iter
735                             .next()
736                             .and_then(|p| p.as_os_str().to_str())
737                             .map_or(false, |p| p.starts_with(prefix))
738                 };
739
740                 let time_macros_impl =
741                     macro_name == sym::impl_macros && matches_prefix("time-macros-impl", "lib.rs");
742                 if time_macros_impl
743                     || (macro_name == sym::arrays && matches_prefix("js-sys", "lib.rs"))
744                 {
745                     let snippet = source_map.span_to_snippet(orig_span);
746                     if snippet.as_deref() == Ok("$name") {
747                         if time_macros_impl {
748                             rustc.sess.buffer_lint_with_diagnostic(
749                                 &PROC_MACRO_BACK_COMPAT,
750                                 orig_span,
751                                 ast::CRATE_NODE_ID,
752                                 "using an old version of `time-macros-impl`",
753                                 BuiltinLintDiagnostics::ProcMacroBackCompat(
754                                 "the `time-macros-impl` crate will stop compiling in futures version of Rust. \
755                                 Please update to the latest version of the `time` crate to avoid breakage".to_string())
756                             );
757                         }
758                         return Some((*ident, *is_raw));
759                     }
760                 }
761
762                 if macro_name == sym::tuple_from_req && matches_prefix("actix-web", "extract.rs") {
763                     let snippet = source_map.span_to_snippet(orig_span);
764                     if snippet.as_deref() == Ok("$T") {
765                         if let FileName::Real(RealFileName::Named(macro_path)) =
766                             source_map.span_to_filename(rustc.def_site)
767                         {
768                             if macro_path.to_string_lossy().contains("pin-project-internal-0.") {
769                                 rustc.sess.buffer_lint_with_diagnostic(
770                                     &PROC_MACRO_BACK_COMPAT,
771                                     orig_span,
772                                     ast::CRATE_NODE_ID,
773                                     "using an old version of `actix-web`",
774                                     BuiltinLintDiagnostics::ProcMacroBackCompat(
775                                     "the version of `actix-web` you are using might stop compiling in future versions of Rust; \
776                                     please update to the latest version of the `actix-web` crate to avoid breakage".to_string())
777                                 );
778                                 return Some((*ident, *is_raw));
779                             }
780                         }
781                     }
782                 }
783             }
784         }
785     }
786     None
787 }