]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_expand/src/proc_macro_server.rs
Rollup merge of #93213 - c410-f3r:let-chains-feature, r=matthewjasper
[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::{self, Nonterminal, NtIdent};
5 use rustc_ast::tokenstream::{self, CanSynthesizeMissingTokens};
6 use rustc_ast::tokenstream::{DelimSpan, Spacing::*, TokenStream, TreeAndSpacing};
7 use rustc_ast_pretty::pprust;
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc_data_structures::sync::Lrc;
10 use rustc_errors::{Diagnostic, PResult};
11 use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT;
12 use rustc_lint_defs::BuiltinLintDiagnostics;
13 use rustc_parse::lexer::nfc_normalize;
14 use rustc_parse::{nt_to_tokenstream, parse_stream_from_source_str};
15 use rustc_session::parse::ParseSess;
16 use rustc_span::def_id::CrateNum;
17 use rustc_span::hygiene::ExpnKind;
18 use rustc_span::symbol::{self, kw, sym, Symbol};
19 use rustc_span::{BytePos, FileName, MultiSpan, Pos, RealFileName, SourceFile, Span};
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 = [
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             {
184                 TokenTree::Ident(Ident::new(rustc.sess(), name.name, is_raw, name.span))
185             }
186             Interpolated(nt) => {
187                 let stream = nt_to_tokenstream(&nt, rustc.sess(), CanSynthesizeMissingTokens::No);
188                 TokenTree::Group(Group {
189                     delimiter: Delimiter::None,
190                     stream,
191                     span: DelimSpan::from_single(span),
192                     flatten: crate::base::pretty_printing_compatibility_hack(&nt, rustc.sess()),
193                 })
194             }
195
196             OpenDelim(..) | CloseDelim(..) => unreachable!(),
197             Eof => unreachable!(),
198         }
199     }
200 }
201
202 impl ToInternal<TokenStream> for TokenTree<Group, Punct, Ident, Literal> {
203     fn to_internal(self) -> TokenStream {
204         use rustc_ast::token::*;
205
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)
210                     .into();
211             }
212             TokenTree::Ident(self::Ident { sym, is_raw, span }) => {
213                 return tokenstream::TokenTree::token(Ident(sym, is_raw), span).into();
214             }
215             TokenTree::Literal(self::Literal {
216                 lit: token::Lit { kind: token::Integer, symbol, suffix },
217                 span,
218             }) if symbol.as_str().starts_with('-') => {
219                 let minus = BinOp(BinOpToken::Minus);
220                 let symbol = Symbol::intern(&symbol.as_str()[1..]);
221                 let integer = TokenKind::lit(token::Integer, symbol, suffix);
222                 let a = tokenstream::TokenTree::token(minus, span);
223                 let b = tokenstream::TokenTree::token(integer, span);
224                 return [a, b].into_iter().collect();
225             }
226             TokenTree::Literal(self::Literal {
227                 lit: token::Lit { kind: token::Float, symbol, suffix },
228                 span,
229             }) if symbol.as_str().starts_with('-') => {
230                 let minus = BinOp(BinOpToken::Minus);
231                 let symbol = Symbol::intern(&symbol.as_str()[1..]);
232                 let float = TokenKind::lit(token::Float, symbol, suffix);
233                 let a = tokenstream::TokenTree::token(minus, span);
234                 let b = tokenstream::TokenTree::token(float, span);
235                 return [a, b].into_iter().collect();
236             }
237             TokenTree::Literal(self::Literal { lit, span }) => {
238                 return tokenstream::TokenTree::token(Literal(lit), span).into();
239             }
240         };
241
242         let kind = match ch {
243             '=' => Eq,
244             '<' => Lt,
245             '>' => Gt,
246             '!' => Not,
247             '~' => Tilde,
248             '+' => BinOp(Plus),
249             '-' => BinOp(Minus),
250             '*' => BinOp(Star),
251             '/' => BinOp(Slash),
252             '%' => BinOp(Percent),
253             '^' => BinOp(Caret),
254             '&' => BinOp(And),
255             '|' => BinOp(Or),
256             '@' => At,
257             '.' => Dot,
258             ',' => Comma,
259             ';' => Semi,
260             ':' => Colon,
261             '#' => Pound,
262             '$' => Dollar,
263             '?' => Question,
264             '\'' => SingleQuote,
265             _ => unreachable!(),
266         };
267
268         let tree = tokenstream::TokenTree::token(kind, span);
269         TokenStream::new(vec![(tree, if joint { Joint } else { Alone })])
270     }
271 }
272
273 impl ToInternal<rustc_errors::Level> for Level {
274     fn to_internal(self) -> rustc_errors::Level {
275         match self {
276             Level::Error => rustc_errors::Level::Error { lint: false },
277             Level::Warning => rustc_errors::Level::Warning,
278             Level::Note => rustc_errors::Level::Note,
279             Level::Help => rustc_errors::Level::Help,
280             _ => unreachable!("unknown proc_macro::Level variant: {:?}", self),
281         }
282     }
283 }
284
285 pub struct FreeFunctions;
286
287 #[derive(Clone)]
288 pub struct TokenStreamIter {
289     cursor: tokenstream::Cursor,
290     stack: Vec<TokenTree<Group, Punct, Ident, Literal>>,
291 }
292
293 #[derive(Clone)]
294 pub struct Group {
295     delimiter: Delimiter,
296     stream: TokenStream,
297     span: DelimSpan,
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).
301     flatten: bool,
302 }
303
304 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
305 pub struct Punct {
306     ch: char,
307     // NB. not using `Spacing` here because it doesn't implement `Hash`.
308     joint: bool,
309     span: Span,
310 }
311
312 impl Punct {
313     fn new(ch: char, joint: bool, span: Span) -> Punct {
314         const LEGAL_CHARS: &[char] = &[
315             '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
316             ':', '#', '$', '?', '\'',
317         ];
318         if !LEGAL_CHARS.contains(&ch) {
319             panic!("unsupported character `{:?}`", ch)
320         }
321         Punct { ch, joint, span }
322     }
323 }
324
325 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
326 pub struct Ident {
327     sym: Symbol,
328     is_raw: bool,
329     span: Span,
330 }
331
332 impl Ident {
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)
338         }
339         if is_raw && !sym.can_be_raw() {
340             panic!("`{}` cannot be a raw identifier", string);
341         }
342         sess.symbol_gallery.insert(sym, span);
343         Ident { sym, is_raw, span }
344     }
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 }
348     }
349 }
350
351 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
352 #[derive(Clone, Debug)]
353 pub struct Literal {
354     lit: token::Lit,
355     span: Span,
356 }
357
358 pub(crate) struct Rustc<'a, 'b> {
359     ecx: &'a mut ExtCtxt<'b>,
360     def_site: Span,
361     call_site: Span,
362     mixed_site: Span,
363     krate: CrateNum,
364     rebased_spans: FxHashMap<usize, Span>,
365 }
366
367 impl<'a, 'b> Rustc<'a, 'b> {
368     pub fn new(ecx: &'a mut ExtCtxt<'b>) -> Self {
369         let expn_data = ecx.current_expansion.id.expn_data();
370         Rustc {
371             def_site: ecx.with_def_site_ctxt(expn_data.def_site),
372             call_site: ecx.with_call_site_ctxt(expn_data.call_site),
373             mixed_site: ecx.with_mixed_site_ctxt(expn_data.call_site),
374             krate: expn_data.macro_def_id.unwrap().krate,
375             rebased_spans: FxHashMap::default(),
376             ecx,
377         }
378     }
379
380     fn sess(&self) -> &ParseSess {
381         self.ecx.parse_sess()
382     }
383
384     fn lit(&mut self, kind: token::LitKind, symbol: Symbol, suffix: Option<Symbol>) -> Literal {
385         Literal { lit: token::Lit::new(kind, symbol, suffix), span: server::Span::call_site(self) }
386     }
387 }
388
389 impl server::Types for Rustc<'_, '_> {
390     type FreeFunctions = FreeFunctions;
391     type TokenStream = TokenStream;
392     type TokenStreamBuilder = tokenstream::TokenStreamBuilder;
393     type TokenStreamIter = TokenStreamIter;
394     type Group = Group;
395     type Punct = Punct;
396     type Ident = Ident;
397     type Literal = Literal;
398     type SourceFile = Lrc<SourceFile>;
399     type MultiSpan = Vec<Span>;
400     type Diagnostic = Diagnostic;
401     type Span = Span;
402 }
403
404 impl server::FreeFunctions for Rustc<'_, '_> {
405     fn track_env_var(&mut self, var: &str, value: Option<&str>) {
406         self.sess()
407             .env_depinfo
408             .borrow_mut()
409             .insert((Symbol::intern(var), value.map(Symbol::intern)));
410     }
411
412     fn track_path(&mut self, path: &str) {
413         self.sess().file_depinfo.borrow_mut().insert(Symbol::intern(path));
414     }
415 }
416
417 impl server::TokenStream for Rustc<'_, '_> {
418     fn new(&mut self) -> Self::TokenStream {
419         TokenStream::default()
420     }
421     fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
422         stream.is_empty()
423     }
424     fn from_str(&mut self, src: &str) -> Self::TokenStream {
425         parse_stream_from_source_str(
426             FileName::proc_macro_source_code(src),
427             src.to_string(),
428             self.sess(),
429             Some(self.call_site),
430         )
431     }
432     fn to_string(&mut self, stream: &Self::TokenStream) -> String {
433         pprust::tts_to_string(stream)
434     }
435     fn expand_expr(&mut self, stream: &Self::TokenStream) -> Result<Self::TokenStream, ()> {
436         // Parse the expression from our tokenstream.
437         let expr: PResult<'_, _> = try {
438             let mut p = rustc_parse::stream_to_parser(
439                 self.sess(),
440                 stream.clone(),
441                 Some("proc_macro expand expr"),
442             );
443             let expr = p.parse_expr()?;
444             if p.token != token::Eof {
445                 p.unexpected()?;
446             }
447             expr
448         };
449         let expr = expr.map_err(|mut err| err.emit())?;
450
451         // Perform eager expansion on the expression.
452         let expr = self
453             .ecx
454             .expander()
455             .fully_expand_fragment(crate::expand::AstFragment::Expr(expr))
456             .make_expr();
457
458         // NOTE: For now, limit `expand_expr` to exclusively expand to literals.
459         // This may be relaxed in the future.
460         // We don't use `nt_to_tokenstream` as the tokenstream currently cannot
461         // be recovered in the general case.
462         match &expr.kind {
463             ast::ExprKind::Lit(l) => {
464                 Ok(tokenstream::TokenTree::token(token::Literal(l.token), l.span).into())
465             }
466             ast::ExprKind::Unary(ast::UnOp::Neg, e) => match &e.kind {
467                 ast::ExprKind::Lit(l) => match l.token {
468                     token::Lit { kind: token::Integer | token::Float, .. } => {
469                         Ok(Self::TokenStream::from_iter([
470                             // FIXME: The span of the `-` token is lost when
471                             // parsing, so we cannot faithfully recover it here.
472                             tokenstream::TokenTree::token(token::BinOp(token::Minus), e.span),
473                             tokenstream::TokenTree::token(token::Literal(l.token), l.span),
474                         ]))
475                     }
476                     _ => Err(()),
477                 },
478                 _ => Err(()),
479             },
480             _ => Err(()),
481         }
482     }
483     fn from_token_tree(
484         &mut self,
485         tree: TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>,
486     ) -> Self::TokenStream {
487         tree.to_internal()
488     }
489     fn into_iter(&mut self, stream: Self::TokenStream) -> Self::TokenStreamIter {
490         TokenStreamIter { cursor: stream.trees(), stack: vec![] }
491     }
492 }
493
494 impl server::TokenStreamBuilder for Rustc<'_, '_> {
495     fn new(&mut self) -> Self::TokenStreamBuilder {
496         tokenstream::TokenStreamBuilder::new()
497     }
498     fn push(&mut self, builder: &mut Self::TokenStreamBuilder, stream: Self::TokenStream) {
499         builder.push(stream);
500     }
501     fn build(&mut self, builder: Self::TokenStreamBuilder) -> Self::TokenStream {
502         builder.build()
503     }
504 }
505
506 impl server::TokenStreamIter for Rustc<'_, '_> {
507     fn next(
508         &mut self,
509         iter: &mut Self::TokenStreamIter,
510     ) -> Option<TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>> {
511         loop {
512             let tree = iter.stack.pop().or_else(|| {
513                 let next = iter.cursor.next_with_spacing()?;
514                 Some(TokenTree::from_internal((next, &mut iter.stack, self)))
515             })?;
516             // A hack used to pass AST fragments to attribute and derive macros
517             // as a single nonterminal token instead of a token stream.
518             // Such token needs to be "unwrapped" and not represented as a delimited group.
519             // FIXME: It needs to be removed, but there are some compatibility issues (see #73345).
520             if let TokenTree::Group(ref group) = tree {
521                 if group.flatten {
522                     iter.cursor.append(group.stream.clone());
523                     continue;
524                 }
525             }
526             return Some(tree);
527         }
528     }
529 }
530
531 impl server::Group for Rustc<'_, '_> {
532     fn new(&mut self, delimiter: Delimiter, stream: Self::TokenStream) -> Self::Group {
533         Group {
534             delimiter,
535             stream,
536             span: DelimSpan::from_single(server::Span::call_site(self)),
537             flatten: false,
538         }
539     }
540     fn delimiter(&mut self, group: &Self::Group) -> Delimiter {
541         group.delimiter
542     }
543     fn stream(&mut self, group: &Self::Group) -> Self::TokenStream {
544         group.stream.clone()
545     }
546     fn span(&mut self, group: &Self::Group) -> Self::Span {
547         group.span.entire()
548     }
549     fn span_open(&mut self, group: &Self::Group) -> Self::Span {
550         group.span.open
551     }
552     fn span_close(&mut self, group: &Self::Group) -> Self::Span {
553         group.span.close
554     }
555     fn set_span(&mut self, group: &mut Self::Group, span: Self::Span) {
556         group.span = DelimSpan::from_single(span);
557     }
558 }
559
560 impl server::Punct for Rustc<'_, '_> {
561     fn new(&mut self, ch: char, spacing: Spacing) -> Self::Punct {
562         Punct::new(ch, spacing == Spacing::Joint, server::Span::call_site(self))
563     }
564     fn as_char(&mut self, punct: Self::Punct) -> char {
565         punct.ch
566     }
567     fn spacing(&mut self, punct: Self::Punct) -> Spacing {
568         if punct.joint { Spacing::Joint } else { Spacing::Alone }
569     }
570     fn span(&mut self, punct: Self::Punct) -> Self::Span {
571         punct.span
572     }
573     fn with_span(&mut self, punct: Self::Punct, span: Self::Span) -> Self::Punct {
574         Punct { span, ..punct }
575     }
576 }
577
578 impl server::Ident for Rustc<'_, '_> {
579     fn new(&mut self, string: &str, span: Self::Span, is_raw: bool) -> Self::Ident {
580         Ident::new(self.sess(), Symbol::intern(string), is_raw, span)
581     }
582     fn span(&mut self, ident: Self::Ident) -> Self::Span {
583         ident.span
584     }
585     fn with_span(&mut self, ident: Self::Ident, span: Self::Span) -> Self::Ident {
586         Ident { span, ..ident }
587     }
588 }
589
590 impl server::Literal for Rustc<'_, '_> {
591     fn from_str(&mut self, s: &str) -> Result<Self::Literal, ()> {
592         let name = FileName::proc_macro_source_code(s);
593         let mut parser = rustc_parse::new_parser_from_source_str(self.sess(), name, s.to_owned());
594
595         let first_span = parser.token.span.data();
596         let minus_present = parser.eat(&token::BinOp(token::Minus));
597
598         let lit_span = parser.token.span.data();
599         let mut lit = match parser.token.kind {
600             token::Literal(lit) => lit,
601             _ => return Err(()),
602         };
603
604         // Check no comment or whitespace surrounding the (possibly negative)
605         // literal, or more tokens after it.
606         if (lit_span.hi.0 - first_span.lo.0) as usize != s.len() {
607             return Err(());
608         }
609
610         if minus_present {
611             // If minus is present, check no comment or whitespace in between it
612             // and the literal token.
613             if first_span.hi.0 != lit_span.lo.0 {
614                 return Err(());
615             }
616
617             // Check literal is a kind we allow to be negated in a proc macro token.
618             match lit.kind {
619                 token::LitKind::Bool
620                 | token::LitKind::Byte
621                 | token::LitKind::Char
622                 | token::LitKind::Str
623                 | token::LitKind::StrRaw(_)
624                 | token::LitKind::ByteStr
625                 | token::LitKind::ByteStrRaw(_)
626                 | token::LitKind::Err => return Err(()),
627                 token::LitKind::Integer | token::LitKind::Float => {}
628             }
629
630             // Synthesize a new symbol that includes the minus sign.
631             let symbol = Symbol::intern(&s[..1 + lit.symbol.as_str().len()]);
632             lit = token::Lit::new(lit.kind, symbol, lit.suffix);
633         }
634
635         Ok(Literal { lit, span: self.call_site })
636     }
637     fn to_string(&mut self, literal: &Self::Literal) -> String {
638         literal.lit.to_string()
639     }
640     fn debug_kind(&mut self, literal: &Self::Literal) -> String {
641         format!("{:?}", literal.lit.kind)
642     }
643     fn symbol(&mut self, literal: &Self::Literal) -> String {
644         literal.lit.symbol.to_string()
645     }
646     fn suffix(&mut self, literal: &Self::Literal) -> Option<String> {
647         literal.lit.suffix.as_ref().map(Symbol::to_string)
648     }
649     fn integer(&mut self, n: &str) -> Self::Literal {
650         self.lit(token::Integer, Symbol::intern(n), None)
651     }
652     fn typed_integer(&mut self, n: &str, kind: &str) -> Self::Literal {
653         self.lit(token::Integer, Symbol::intern(n), Some(Symbol::intern(kind)))
654     }
655     fn float(&mut self, n: &str) -> Self::Literal {
656         self.lit(token::Float, Symbol::intern(n), None)
657     }
658     fn f32(&mut self, n: &str) -> Self::Literal {
659         self.lit(token::Float, Symbol::intern(n), Some(sym::f32))
660     }
661     fn f64(&mut self, n: &str) -> Self::Literal {
662         self.lit(token::Float, Symbol::intern(n), Some(sym::f64))
663     }
664     fn string(&mut self, string: &str) -> Self::Literal {
665         let mut escaped = String::new();
666         for ch in string.chars() {
667             escaped.extend(ch.escape_debug());
668         }
669         self.lit(token::Str, Symbol::intern(&escaped), None)
670     }
671     fn character(&mut self, ch: char) -> Self::Literal {
672         let mut escaped = String::new();
673         escaped.extend(ch.escape_unicode());
674         self.lit(token::Char, Symbol::intern(&escaped), None)
675     }
676     fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
677         let string = bytes
678             .iter()
679             .cloned()
680             .flat_map(ascii::escape_default)
681             .map(Into::<char>::into)
682             .collect::<String>();
683         self.lit(token::ByteStr, Symbol::intern(&string), None)
684     }
685     fn span(&mut self, literal: &Self::Literal) -> Self::Span {
686         literal.span
687     }
688     fn set_span(&mut self, literal: &mut Self::Literal, span: Self::Span) {
689         literal.span = span;
690     }
691     fn subspan(
692         &mut self,
693         literal: &Self::Literal,
694         start: Bound<usize>,
695         end: Bound<usize>,
696     ) -> Option<Self::Span> {
697         let span = literal.span;
698         let length = span.hi().to_usize() - span.lo().to_usize();
699
700         let start = match start {
701             Bound::Included(lo) => lo,
702             Bound::Excluded(lo) => lo.checked_add(1)?,
703             Bound::Unbounded => 0,
704         };
705
706         let end = match end {
707             Bound::Included(hi) => hi.checked_add(1)?,
708             Bound::Excluded(hi) => hi,
709             Bound::Unbounded => length,
710         };
711
712         // Bounds check the values, preventing addition overflow and OOB spans.
713         if start > u32::MAX as usize
714             || end > u32::MAX as usize
715             || (u32::MAX - start as u32) < span.lo().to_u32()
716             || (u32::MAX - end as u32) < span.lo().to_u32()
717             || start >= end
718             || end > length
719         {
720             return None;
721         }
722
723         let new_lo = span.lo() + BytePos::from_usize(start);
724         let new_hi = span.lo() + BytePos::from_usize(end);
725         Some(span.with_lo(new_lo).with_hi(new_hi))
726     }
727 }
728
729 impl server::SourceFile for Rustc<'_, '_> {
730     fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
731         Lrc::ptr_eq(file1, file2)
732     }
733     fn path(&mut self, file: &Self::SourceFile) -> String {
734         match file.name {
735             FileName::Real(ref name) => name
736                 .local_path()
737                 .expect("attempting to get a file path in an imported file in `proc_macro::SourceFile::path`")
738                 .to_str()
739                 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
740                 .to_string(),
741             _ => file.name.prefer_local().to_string(),
742         }
743     }
744     fn is_real(&mut self, file: &Self::SourceFile) -> bool {
745         file.is_real_file()
746     }
747 }
748
749 impl server::MultiSpan for Rustc<'_, '_> {
750     fn new(&mut self) -> Self::MultiSpan {
751         vec![]
752     }
753     fn push(&mut self, spans: &mut Self::MultiSpan, span: Self::Span) {
754         spans.push(span)
755     }
756 }
757
758 impl server::Diagnostic for Rustc<'_, '_> {
759     fn new(&mut self, level: Level, msg: &str, spans: Self::MultiSpan) -> Self::Diagnostic {
760         let mut diag = Diagnostic::new(level.to_internal(), msg);
761         diag.set_span(MultiSpan::from_spans(spans));
762         diag
763     }
764     fn sub(
765         &mut self,
766         diag: &mut Self::Diagnostic,
767         level: Level,
768         msg: &str,
769         spans: Self::MultiSpan,
770     ) {
771         diag.sub(level.to_internal(), msg, MultiSpan::from_spans(spans), None);
772     }
773     fn emit(&mut self, diag: Self::Diagnostic) {
774         self.sess().span_diagnostic.emit_diagnostic(&diag);
775     }
776 }
777
778 impl server::Span for Rustc<'_, '_> {
779     fn debug(&mut self, span: Self::Span) -> String {
780         if self.ecx.ecfg.span_debug {
781             format!("{:?}", span)
782         } else {
783             format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
784         }
785     }
786     fn def_site(&mut self) -> Self::Span {
787         self.def_site
788     }
789     fn call_site(&mut self) -> Self::Span {
790         self.call_site
791     }
792     fn mixed_site(&mut self) -> Self::Span {
793         self.mixed_site
794     }
795     fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
796         self.sess().source_map().lookup_char_pos(span.lo()).file
797     }
798     fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
799         span.parent_callsite()
800     }
801     fn source(&mut self, span: Self::Span) -> Self::Span {
802         span.source_callsite()
803     }
804     fn start(&mut self, span: Self::Span) -> LineColumn {
805         let loc = self.sess().source_map().lookup_char_pos(span.lo());
806         LineColumn { line: loc.line, column: loc.col.to_usize() }
807     }
808     fn end(&mut self, span: Self::Span) -> LineColumn {
809         let loc = self.sess().source_map().lookup_char_pos(span.hi());
810         LineColumn { line: loc.line, column: loc.col.to_usize() }
811     }
812     fn before(&mut self, span: Self::Span) -> Self::Span {
813         span.shrink_to_lo()
814     }
815     fn after(&mut self, span: Self::Span) -> Self::Span {
816         span.shrink_to_hi()
817     }
818     fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
819         let self_loc = self.sess().source_map().lookup_char_pos(first.lo());
820         let other_loc = self.sess().source_map().lookup_char_pos(second.lo());
821
822         if self_loc.file.name != other_loc.file.name {
823             return None;
824         }
825
826         Some(first.to(second))
827     }
828     fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
829         span.with_ctxt(at.ctxt())
830     }
831     fn source_text(&mut self, span: Self::Span) -> Option<String> {
832         self.sess().source_map().span_to_snippet(span).ok()
833     }
834     /// Saves the provided span into the metadata of
835     /// *the crate we are currently compiling*, which must
836     /// be a proc-macro crate. This id can be passed to
837     /// `recover_proc_macro_span` when our current crate
838     /// is *run* as a proc-macro.
839     ///
840     /// Let's suppose that we have two crates - `my_client`
841     /// and `my_proc_macro`. The `my_proc_macro` crate
842     /// contains a procedural macro `my_macro`, which
843     /// is implemented as: `quote! { "hello" }`
844     ///
845     /// When we *compile* `my_proc_macro`, we will execute
846     /// the `quote` proc-macro. This will save the span of
847     /// "hello" into the metadata of `my_proc_macro`. As a result,
848     /// the body of `my_proc_macro` (after expansion) will end
849     /// up containg a call that looks like this:
850     /// `proc_macro::Ident::new("hello", proc_macro::Span::recover_proc_macro_span(0))`
851     ///
852     /// where `0` is the id returned by this function.
853     /// When `my_proc_macro` *executes* (during the compilation of `my_client`),
854     /// the call to `recover_proc_macro_span` will load the corresponding
855     /// span from the metadata of `my_proc_macro` (which we have access to,
856     /// since we've loaded `my_proc_macro` from disk in order to execute it).
857     /// In this way, we have obtained a span pointing into `my_proc_macro`
858     fn save_span(&mut self, span: Self::Span) -> usize {
859         self.sess().save_proc_macro_span(span)
860     }
861     fn recover_proc_macro_span(&mut self, id: usize) -> Self::Span {
862         let (resolver, krate, def_site) = (&*self.ecx.resolver, self.krate, self.def_site);
863         *self.rebased_spans.entry(id).or_insert_with(|| {
864             // FIXME: `SyntaxContext` for spans from proc macro crates is lost during encoding,
865             // replace it with a def-site context until we are encoding it properly.
866             resolver.get_proc_macro_quoted_span(krate, id).with_ctxt(def_site.ctxt())
867         })
868     }
869 }
870
871 // See issue #74616 for details
872 fn ident_name_compatibility_hack(
873     nt: &Nonterminal,
874     orig_span: Span,
875     rustc: &mut Rustc<'_, '_>,
876 ) -> Option<(rustc_span::symbol::Ident, bool)> {
877     if let NtIdent(ident, is_raw) = nt {
878         if let ExpnKind::Macro(_, macro_name) = orig_span.ctxt().outer_expn_data().kind {
879             let source_map = rustc.sess().source_map();
880             let filename = source_map.span_to_filename(orig_span);
881             if let FileName::Real(RealFileName::LocalPath(path)) = filename {
882                 let matches_prefix = |prefix, filename| {
883                     // Check for a path that ends with 'prefix*/src/<filename>'
884                     let mut iter = path.components().rev();
885                     iter.next().and_then(|p| p.as_os_str().to_str()) == Some(filename)
886                         && iter.next().and_then(|p| p.as_os_str().to_str()) == Some("src")
887                         && iter
888                             .next()
889                             .and_then(|p| p.as_os_str().to_str())
890                             .map_or(false, |p| p.starts_with(prefix))
891                 };
892
893                 let time_macros_impl =
894                     macro_name == sym::impl_macros && matches_prefix("time-macros-impl", "lib.rs");
895                 let js_sys = macro_name == sym::arrays && matches_prefix("js-sys", "lib.rs");
896                 if time_macros_impl || js_sys {
897                     let snippet = source_map.span_to_snippet(orig_span);
898                     if snippet.as_deref() == Ok("$name") {
899                         if time_macros_impl {
900                             rustc.sess().buffer_lint_with_diagnostic(
901                                 &PROC_MACRO_BACK_COMPAT,
902                                 orig_span,
903                                 ast::CRATE_NODE_ID,
904                                 "using an old version of `time-macros-impl`",
905                                 BuiltinLintDiagnostics::ProcMacroBackCompat(
906                                 "the `time-macros-impl` crate will stop compiling in futures version of Rust. \
907                                 Please update to the latest version of the `time` crate to avoid breakage".to_string())
908                             );
909                             return Some((*ident, *is_raw));
910                         }
911                         if js_sys {
912                             if let Some(c) = path
913                                 .components()
914                                 .flat_map(|c| c.as_os_str().to_str())
915                                 .find(|c| c.starts_with("js-sys"))
916                             {
917                                 let mut version = c.trim_start_matches("js-sys-").split('.');
918                                 if version.next() == Some("0")
919                                     && version.next() == Some("3")
920                                     && version
921                                         .next()
922                                         .and_then(|c| c.parse::<u32>().ok())
923                                         .map_or(false, |v| v < 40)
924                                 {
925                                     rustc.sess().buffer_lint_with_diagnostic(
926                                         &PROC_MACRO_BACK_COMPAT,
927                                         orig_span,
928                                         ast::CRATE_NODE_ID,
929                                         "using an old version of `js-sys`",
930                                         BuiltinLintDiagnostics::ProcMacroBackCompat(
931                                         "older versions of the `js-sys` crate will stop compiling in future versions of Rust; \
932                                         please update to `js-sys` v0.3.40 or above".to_string())
933                                     );
934                                     return Some((*ident, *is_raw));
935                                 }
936                             }
937                         }
938                     }
939                 }
940
941                 if macro_name == sym::tuple_from_req && matches_prefix("actix-web", "extract.rs") {
942                     let snippet = source_map.span_to_snippet(orig_span);
943                     if snippet.as_deref() == Ok("$T") {
944                         if let FileName::Real(RealFileName::LocalPath(macro_path)) =
945                             source_map.span_to_filename(rustc.def_site)
946                         {
947                             if macro_path.to_string_lossy().contains("pin-project-internal-0.") {
948                                 rustc.sess().buffer_lint_with_diagnostic(
949                                     &PROC_MACRO_BACK_COMPAT,
950                                     orig_span,
951                                     ast::CRATE_NODE_ID,
952                                     "using an old version of `actix-web`",
953                                     BuiltinLintDiagnostics::ProcMacroBackCompat(
954                                     "the version of `actix-web` you are using might stop compiling in future versions of Rust; \
955                                     please update to the latest version of the `actix-web` crate to avoid breakage".to_string())
956                                 );
957                                 return Some((*ident, *is_raw));
958                             }
959                         }
960                     }
961                 }
962             }
963         }
964     }
965     None
966 }