]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_expand/src/proc_macro_server.rs
Auto merge of #87532 - tlyu:bootstrap-rev-list, r=jyn514
[rust.git] / compiler / rustc_expand / src / proc_macro_server.rs
1 use crate::base::{ExtCtxt, ResolverExpand};
2
3 use rustc_ast as ast;
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;
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};
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     resolver: &'a dyn ResolverExpand,
359     sess: &'a ParseSess,
360     def_site: Span,
361     call_site: Span,
362     mixed_site: Span,
363     span_debug: bool,
364     krate: CrateNum,
365     rebased_spans: FxHashMap<usize, Span>,
366 }
367
368 impl<'a> Rustc<'a> {
369     pub fn new(cx: &'a ExtCtxt<'_>) -> Self {
370         let expn_data = cx.current_expansion.id.expn_data();
371         Rustc {
372             resolver: cx.resolver,
373             sess: cx.parse_sess(),
374             def_site: cx.with_def_site_ctxt(expn_data.def_site),
375             call_site: cx.with_call_site_ctxt(expn_data.call_site),
376             mixed_site: cx.with_mixed_site_ctxt(expn_data.call_site),
377             span_debug: cx.ecfg.span_debug,
378             krate: expn_data.macro_def_id.unwrap().krate,
379             rebased_spans: FxHashMap::default(),
380         }
381     }
382
383     fn lit(&mut self, kind: token::LitKind, symbol: Symbol, suffix: Option<Symbol>) -> Literal {
384         Literal { lit: token::Lit::new(kind, symbol, suffix), span: server::Span::call_site(self) }
385     }
386 }
387
388 impl server::Types for Rustc<'_> {
389     type FreeFunctions = FreeFunctions;
390     type TokenStream = TokenStream;
391     type TokenStreamBuilder = tokenstream::TokenStreamBuilder;
392     type TokenStreamIter = TokenStreamIter;
393     type Group = Group;
394     type Punct = Punct;
395     type Ident = Ident;
396     type Literal = Literal;
397     type SourceFile = Lrc<SourceFile>;
398     type MultiSpan = Vec<Span>;
399     type Diagnostic = Diagnostic;
400     type Span = Span;
401 }
402
403 impl server::FreeFunctions for Rustc<'_> {
404     fn track_env_var(&mut self, var: &str, value: Option<&str>) {
405         self.sess.env_depinfo.borrow_mut().insert((Symbol::intern(var), value.map(Symbol::intern)));
406     }
407
408     fn track_path(&mut self, path: &str) {
409         self.sess.file_depinfo.borrow_mut().insert(Symbol::intern(path));
410     }
411 }
412
413 impl server::TokenStream for Rustc<'_> {
414     fn new(&mut self) -> Self::TokenStream {
415         TokenStream::default()
416     }
417     fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
418         stream.is_empty()
419     }
420     fn from_str(&mut self, src: &str) -> Self::TokenStream {
421         parse_stream_from_source_str(
422             FileName::proc_macro_source_code(src),
423             src.to_string(),
424             self.sess,
425             Some(self.call_site),
426         )
427     }
428     fn to_string(&mut self, stream: &Self::TokenStream) -> String {
429         pprust::tts_to_string(stream)
430     }
431     fn from_token_tree(
432         &mut self,
433         tree: TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>,
434     ) -> Self::TokenStream {
435         tree.to_internal()
436     }
437     fn into_iter(&mut self, stream: Self::TokenStream) -> Self::TokenStreamIter {
438         TokenStreamIter { cursor: stream.trees(), stack: vec![] }
439     }
440 }
441
442 impl server::TokenStreamBuilder for Rustc<'_> {
443     fn new(&mut self) -> Self::TokenStreamBuilder {
444         tokenstream::TokenStreamBuilder::new()
445     }
446     fn push(&mut self, builder: &mut Self::TokenStreamBuilder, stream: Self::TokenStream) {
447         builder.push(stream);
448     }
449     fn build(&mut self, builder: Self::TokenStreamBuilder) -> Self::TokenStream {
450         builder.build()
451     }
452 }
453
454 impl server::TokenStreamIter for Rustc<'_> {
455     fn next(
456         &mut self,
457         iter: &mut Self::TokenStreamIter,
458     ) -> Option<TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>> {
459         loop {
460             let tree = iter.stack.pop().or_else(|| {
461                 let next = iter.cursor.next_with_spacing()?;
462                 Some(TokenTree::from_internal((next, &mut iter.stack, self)))
463             })?;
464             // A hack used to pass AST fragments to attribute and derive macros
465             // as a single nonterminal token instead of a token stream.
466             // Such token needs to be "unwrapped" and not represented as a delimited group.
467             // FIXME: It needs to be removed, but there are some compatibility issues (see #73345).
468             if let TokenTree::Group(ref group) = tree {
469                 if group.flatten {
470                     iter.cursor.append(group.stream.clone());
471                     continue;
472                 }
473             }
474             return Some(tree);
475         }
476     }
477 }
478
479 impl server::Group for Rustc<'_> {
480     fn new(&mut self, delimiter: Delimiter, stream: Self::TokenStream) -> Self::Group {
481         Group {
482             delimiter,
483             stream,
484             span: DelimSpan::from_single(server::Span::call_site(self)),
485             flatten: false,
486         }
487     }
488     fn delimiter(&mut self, group: &Self::Group) -> Delimiter {
489         group.delimiter
490     }
491     fn stream(&mut self, group: &Self::Group) -> Self::TokenStream {
492         group.stream.clone()
493     }
494     fn span(&mut self, group: &Self::Group) -> Self::Span {
495         group.span.entire()
496     }
497     fn span_open(&mut self, group: &Self::Group) -> Self::Span {
498         group.span.open
499     }
500     fn span_close(&mut self, group: &Self::Group) -> Self::Span {
501         group.span.close
502     }
503     fn set_span(&mut self, group: &mut Self::Group, span: Self::Span) {
504         group.span = DelimSpan::from_single(span);
505     }
506 }
507
508 impl server::Punct for Rustc<'_> {
509     fn new(&mut self, ch: char, spacing: Spacing) -> Self::Punct {
510         Punct::new(ch, spacing == Spacing::Joint, server::Span::call_site(self))
511     }
512     fn as_char(&mut self, punct: Self::Punct) -> char {
513         punct.ch
514     }
515     fn spacing(&mut self, punct: Self::Punct) -> Spacing {
516         if punct.joint { Spacing::Joint } else { Spacing::Alone }
517     }
518     fn span(&mut self, punct: Self::Punct) -> Self::Span {
519         punct.span
520     }
521     fn with_span(&mut self, punct: Self::Punct, span: Self::Span) -> Self::Punct {
522         Punct { span, ..punct }
523     }
524 }
525
526 impl server::Ident for Rustc<'_> {
527     fn new(&mut self, string: &str, span: Self::Span, is_raw: bool) -> Self::Ident {
528         Ident::new(self.sess, Symbol::intern(string), is_raw, span)
529     }
530     fn span(&mut self, ident: Self::Ident) -> Self::Span {
531         ident.span
532     }
533     fn with_span(&mut self, ident: Self::Ident, span: Self::Span) -> Self::Ident {
534         Ident { span, ..ident }
535     }
536 }
537
538 impl server::Literal for Rustc<'_> {
539     fn from_str(&mut self, s: &str) -> Result<Self::Literal, ()> {
540         let name = FileName::proc_macro_source_code(s);
541         let mut parser = rustc_parse::new_parser_from_source_str(self.sess, name, s.to_owned());
542
543         let first_span = parser.token.span.data();
544         let minus_present = parser.eat(&token::BinOp(token::Minus));
545
546         let lit_span = parser.token.span.data();
547         let mut lit = match parser.token.kind {
548             token::Literal(lit) => lit,
549             _ => return Err(()),
550         };
551
552         // Check no comment or whitespace surrounding the (possibly negative)
553         // literal, or more tokens after it.
554         if (lit_span.hi.0 - first_span.lo.0) as usize != s.len() {
555             return Err(());
556         }
557
558         if minus_present {
559             // If minus is present, check no comment or whitespace in between it
560             // and the literal token.
561             if first_span.hi.0 != lit_span.lo.0 {
562                 return Err(());
563             }
564
565             // Check literal is a kind we allow to be negated in a proc macro token.
566             match lit.kind {
567                 token::LitKind::Bool
568                 | token::LitKind::Byte
569                 | token::LitKind::Char
570                 | token::LitKind::Str
571                 | token::LitKind::StrRaw(_)
572                 | token::LitKind::ByteStr
573                 | token::LitKind::ByteStrRaw(_)
574                 | token::LitKind::Err => return Err(()),
575                 token::LitKind::Integer | token::LitKind::Float => {}
576             }
577
578             // Synthesize a new symbol that includes the minus sign.
579             let symbol = Symbol::intern(&s[..1 + lit.symbol.len()]);
580             lit = token::Lit::new(lit.kind, symbol, lit.suffix);
581         }
582
583         Ok(Literal { lit, span: self.call_site })
584     }
585     fn to_string(&mut self, literal: &Self::Literal) -> String {
586         literal.lit.to_string()
587     }
588     fn debug_kind(&mut self, literal: &Self::Literal) -> String {
589         format!("{:?}", literal.lit.kind)
590     }
591     fn symbol(&mut self, literal: &Self::Literal) -> String {
592         literal.lit.symbol.to_string()
593     }
594     fn suffix(&mut self, literal: &Self::Literal) -> Option<String> {
595         literal.lit.suffix.as_ref().map(Symbol::to_string)
596     }
597     fn integer(&mut self, n: &str) -> Self::Literal {
598         self.lit(token::Integer, Symbol::intern(n), None)
599     }
600     fn typed_integer(&mut self, n: &str, kind: &str) -> Self::Literal {
601         self.lit(token::Integer, Symbol::intern(n), Some(Symbol::intern(kind)))
602     }
603     fn float(&mut self, n: &str) -> Self::Literal {
604         self.lit(token::Float, Symbol::intern(n), None)
605     }
606     fn f32(&mut self, n: &str) -> Self::Literal {
607         self.lit(token::Float, Symbol::intern(n), Some(sym::f32))
608     }
609     fn f64(&mut self, n: &str) -> Self::Literal {
610         self.lit(token::Float, Symbol::intern(n), Some(sym::f64))
611     }
612     fn string(&mut self, string: &str) -> Self::Literal {
613         let mut escaped = String::new();
614         for ch in string.chars() {
615             escaped.extend(ch.escape_debug());
616         }
617         self.lit(token::Str, Symbol::intern(&escaped), None)
618     }
619     fn character(&mut self, ch: char) -> Self::Literal {
620         let mut escaped = String::new();
621         escaped.extend(ch.escape_unicode());
622         self.lit(token::Char, Symbol::intern(&escaped), None)
623     }
624     fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
625         let string = bytes
626             .iter()
627             .cloned()
628             .flat_map(ascii::escape_default)
629             .map(Into::<char>::into)
630             .collect::<String>();
631         self.lit(token::ByteStr, Symbol::intern(&string), None)
632     }
633     fn span(&mut self, literal: &Self::Literal) -> Self::Span {
634         literal.span
635     }
636     fn set_span(&mut self, literal: &mut Self::Literal, span: Self::Span) {
637         literal.span = span;
638     }
639     fn subspan(
640         &mut self,
641         literal: &Self::Literal,
642         start: Bound<usize>,
643         end: Bound<usize>,
644     ) -> Option<Self::Span> {
645         let span = literal.span;
646         let length = span.hi().to_usize() - span.lo().to_usize();
647
648         let start = match start {
649             Bound::Included(lo) => lo,
650             Bound::Excluded(lo) => lo.checked_add(1)?,
651             Bound::Unbounded => 0,
652         };
653
654         let end = match end {
655             Bound::Included(hi) => hi.checked_add(1)?,
656             Bound::Excluded(hi) => hi,
657             Bound::Unbounded => length,
658         };
659
660         // Bounds check the values, preventing addition overflow and OOB spans.
661         if start > u32::MAX as usize
662             || end > u32::MAX as usize
663             || (u32::MAX - start as u32) < span.lo().to_u32()
664             || (u32::MAX - end as u32) < span.lo().to_u32()
665             || start >= end
666             || end > length
667         {
668             return None;
669         }
670
671         let new_lo = span.lo() + BytePos::from_usize(start);
672         let new_hi = span.lo() + BytePos::from_usize(end);
673         Some(span.with_lo(new_lo).with_hi(new_hi))
674     }
675 }
676
677 impl server::SourceFile for Rustc<'_> {
678     fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
679         Lrc::ptr_eq(file1, file2)
680     }
681     fn path(&mut self, file: &Self::SourceFile) -> String {
682         match file.name {
683             FileName::Real(ref name) => name
684                 .local_path()
685                 .expect("attempting to get a file path in an imported file in `proc_macro::SourceFile::path`")
686                 .to_str()
687                 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
688                 .to_string(),
689             _ => file.name.prefer_local().to_string(),
690         }
691     }
692     fn is_real(&mut self, file: &Self::SourceFile) -> bool {
693         file.is_real_file()
694     }
695 }
696
697 impl server::MultiSpan for Rustc<'_> {
698     fn new(&mut self) -> Self::MultiSpan {
699         vec![]
700     }
701     fn push(&mut self, spans: &mut Self::MultiSpan, span: Self::Span) {
702         spans.push(span)
703     }
704 }
705
706 impl server::Diagnostic for Rustc<'_> {
707     fn new(&mut self, level: Level, msg: &str, spans: Self::MultiSpan) -> Self::Diagnostic {
708         let mut diag = Diagnostic::new(level.to_internal(), msg);
709         diag.set_span(MultiSpan::from_spans(spans));
710         diag
711     }
712     fn sub(
713         &mut self,
714         diag: &mut Self::Diagnostic,
715         level: Level,
716         msg: &str,
717         spans: Self::MultiSpan,
718     ) {
719         diag.sub(level.to_internal(), msg, MultiSpan::from_spans(spans), None);
720     }
721     fn emit(&mut self, diag: Self::Diagnostic) {
722         self.sess.span_diagnostic.emit_diagnostic(&diag);
723     }
724 }
725
726 impl server::Span for Rustc<'_> {
727     fn debug(&mut self, span: Self::Span) -> String {
728         if self.span_debug {
729             format!("{:?}", span)
730         } else {
731             format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
732         }
733     }
734     fn def_site(&mut self) -> Self::Span {
735         self.def_site
736     }
737     fn call_site(&mut self) -> Self::Span {
738         self.call_site
739     }
740     fn mixed_site(&mut self) -> Self::Span {
741         self.mixed_site
742     }
743     fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
744         self.sess.source_map().lookup_char_pos(span.lo()).file
745     }
746     fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
747         span.parent()
748     }
749     fn source(&mut self, span: Self::Span) -> Self::Span {
750         span.source_callsite()
751     }
752     fn start(&mut self, span: Self::Span) -> LineColumn {
753         let loc = self.sess.source_map().lookup_char_pos(span.lo());
754         LineColumn { line: loc.line, column: loc.col.to_usize() }
755     }
756     fn end(&mut self, span: Self::Span) -> LineColumn {
757         let loc = self.sess.source_map().lookup_char_pos(span.hi());
758         LineColumn { line: loc.line, column: loc.col.to_usize() }
759     }
760     fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
761         let self_loc = self.sess.source_map().lookup_char_pos(first.lo());
762         let other_loc = self.sess.source_map().lookup_char_pos(second.lo());
763
764         if self_loc.file.name != other_loc.file.name {
765             return None;
766         }
767
768         Some(first.to(second))
769     }
770     fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
771         span.with_ctxt(at.ctxt())
772     }
773     fn source_text(&mut self, span: Self::Span) -> Option<String> {
774         self.sess.source_map().span_to_snippet(span).ok()
775     }
776     /// Saves the provided span into the metadata of
777     /// *the crate we are currently compiling*, which must
778     /// be a proc-macro crate. This id can be passed to
779     /// `recover_proc_macro_span` when our current crate
780     /// is *run* as a proc-macro.
781     ///
782     /// Let's suppose that we have two crates - `my_client`
783     /// and `my_proc_macro`. The `my_proc_macro` crate
784     /// contains a procedural macro `my_macro`, which
785     /// is implemented as: `quote! { "hello" }`
786     ///
787     /// When we *compile* `my_proc_macro`, we will execute
788     /// the `quote` proc-macro. This will save the span of
789     /// "hello" into the metadata of `my_proc_macro`. As a result,
790     /// the body of `my_proc_macro` (after expansion) will end
791     /// up containg a call that looks like this:
792     /// `proc_macro::Ident::new("hello", proc_macro::Span::recover_proc_macro_span(0))`
793     ///
794     /// where `0` is the id returned by this function.
795     /// When `my_proc_macro` *executes* (during the compilation of `my_client`),
796     /// the call to `recover_proc_macro_span` will load the corresponding
797     /// span from the metadata of `my_proc_macro` (which we have access to,
798     /// since we've loaded `my_proc_macro` from disk in order to execute it).
799     /// In this way, we have obtained a span pointing into `my_proc_macro`
800     fn save_span(&mut self, span: Self::Span) -> usize {
801         self.sess.save_proc_macro_span(span)
802     }
803     fn recover_proc_macro_span(&mut self, id: usize) -> Self::Span {
804         let (resolver, krate, def_site) = (self.resolver, self.krate, self.def_site);
805         *self.rebased_spans.entry(id).or_insert_with(|| {
806             // FIXME: `SyntaxContext` for spans from proc macro crates is lost during encoding,
807             // replace it with a def-site context until we are encoding it properly.
808             resolver.get_proc_macro_quoted_span(krate, id).with_ctxt(def_site.ctxt())
809         })
810     }
811 }
812
813 // See issue #74616 for details
814 fn ident_name_compatibility_hack(
815     nt: &Nonterminal,
816     orig_span: Span,
817     rustc: &mut Rustc<'_>,
818 ) -> Option<(rustc_span::symbol::Ident, bool)> {
819     if let NtIdent(ident, is_raw) = nt {
820         if let ExpnKind::Macro(_, macro_name) = orig_span.ctxt().outer_expn_data().kind {
821             let source_map = rustc.sess.source_map();
822             let filename = source_map.span_to_filename(orig_span);
823             if let FileName::Real(RealFileName::LocalPath(path)) = filename {
824                 let matches_prefix = |prefix, filename| {
825                     // Check for a path that ends with 'prefix*/src/<filename>'
826                     let mut iter = path.components().rev();
827                     iter.next().and_then(|p| p.as_os_str().to_str()) == Some(filename)
828                         && iter.next().and_then(|p| p.as_os_str().to_str()) == Some("src")
829                         && iter
830                             .next()
831                             .and_then(|p| p.as_os_str().to_str())
832                             .map_or(false, |p| p.starts_with(prefix))
833                 };
834
835                 let time_macros_impl =
836                     macro_name == sym::impl_macros && matches_prefix("time-macros-impl", "lib.rs");
837                 let js_sys = macro_name == sym::arrays && matches_prefix("js-sys", "lib.rs");
838                 if time_macros_impl || js_sys {
839                     let snippet = source_map.span_to_snippet(orig_span);
840                     if snippet.as_deref() == Ok("$name") {
841                         if time_macros_impl {
842                             rustc.sess.buffer_lint_with_diagnostic(
843                                 &PROC_MACRO_BACK_COMPAT,
844                                 orig_span,
845                                 ast::CRATE_NODE_ID,
846                                 "using an old version of `time-macros-impl`",
847                                 BuiltinLintDiagnostics::ProcMacroBackCompat(
848                                 "the `time-macros-impl` crate will stop compiling in futures version of Rust. \
849                                 Please update to the latest version of the `time` crate to avoid breakage".to_string())
850                             );
851                             return Some((*ident, *is_raw));
852                         }
853                         if js_sys {
854                             if let Some(c) = path
855                                 .components()
856                                 .flat_map(|c| c.as_os_str().to_str())
857                                 .find(|c| c.starts_with("js-sys"))
858                             {
859                                 let mut version = c.trim_start_matches("js-sys-").split('.');
860                                 if version.next() == Some("0")
861                                     && version.next() == Some("3")
862                                     && version
863                                         .next()
864                                         .and_then(|c| c.parse::<u32>().ok())
865                                         .map_or(false, |v| v < 40)
866                                 {
867                                     rustc.sess.buffer_lint_with_diagnostic(
868                                         &PROC_MACRO_BACK_COMPAT,
869                                         orig_span,
870                                         ast::CRATE_NODE_ID,
871                                         "using an old version of `js-sys`",
872                                         BuiltinLintDiagnostics::ProcMacroBackCompat(
873                                         "older versions of the `js-sys` crate will stop compiling in future versions of Rust; \
874                                         please update to `js-sys` v0.3.40 or above".to_string())
875                                     );
876                                     return Some((*ident, *is_raw));
877                                 }
878                             }
879                         }
880                     }
881                 }
882
883                 if macro_name == sym::tuple_from_req && matches_prefix("actix-web", "extract.rs") {
884                     let snippet = source_map.span_to_snippet(orig_span);
885                     if snippet.as_deref() == Ok("$T") {
886                         if let FileName::Real(RealFileName::LocalPath(macro_path)) =
887                             source_map.span_to_filename(rustc.def_site)
888                         {
889                             if macro_path.to_string_lossy().contains("pin-project-internal-0.") {
890                                 rustc.sess.buffer_lint_with_diagnostic(
891                                     &PROC_MACRO_BACK_COMPAT,
892                                     orig_span,
893                                     ast::CRATE_NODE_ID,
894                                     "using an old version of `actix-web`",
895                                     BuiltinLintDiagnostics::ProcMacroBackCompat(
896                                     "the version of `actix-web` you are using might stop compiling in future versions of Rust; \
897                                     please update to the latest version of the `actix-web` crate to avoid breakage".to_string())
898                                 );
899                                 return Some((*ident, *is_raw));
900                             }
901                         }
902                     }
903                 }
904             }
905         }
906     }
907     None
908 }