]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_expand/src/proc_macro_server.rs
Auto merge of #93700 - rossmacarthur:ft/iter-next-chunk, r=m-ou-se
[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::tokenstream::{self, DelimSpan, Spacing::*, TokenStream, TreeAndSpacing};
6 use rustc_ast_pretty::pprust;
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_data_structures::sync::Lrc;
9 use rustc_errors::{Diagnostic, MultiSpan, PResult};
10 use rustc_parse::lexer::nfc_normalize;
11 use rustc_parse::parse_stream_from_source_str;
12 use rustc_session::parse::ParseSess;
13 use rustc_span::def_id::CrateNum;
14 use rustc_span::symbol::{self, kw, sym, Symbol};
15 use rustc_span::{BytePos, FileName, Pos, SourceFile, Span};
16
17 use pm::bridge::{server, TokenTree};
18 use pm::{Delimiter, Level, LineColumn, Spacing};
19 use std::ops::Bound;
20 use std::{ascii, panic};
21
22 trait FromInternal<T> {
23     fn from_internal(x: T) -> Self;
24 }
25
26 trait ToInternal<T> {
27     fn to_internal(self) -> T;
28 }
29
30 impl FromInternal<token::Delimiter> for Delimiter {
31     fn from_internal(delim: token::Delimiter) -> Delimiter {
32         match delim {
33             token::Delimiter::Parenthesis => Delimiter::Parenthesis,
34             token::Delimiter::Brace => Delimiter::Brace,
35             token::Delimiter::Bracket => Delimiter::Bracket,
36             token::Delimiter::Invisible => Delimiter::None,
37         }
38     }
39 }
40
41 impl ToInternal<token::Delimiter> for Delimiter {
42     fn to_internal(self) -> token::Delimiter {
43         match self {
44             Delimiter::Parenthesis => token::Delimiter::Parenthesis,
45             Delimiter::Brace => token::Delimiter::Brace,
46             Delimiter::Bracket => token::Delimiter::Bracket,
47             Delimiter::None => token::Delimiter::Invisible,
48         }
49     }
50 }
51
52 impl FromInternal<(TreeAndSpacing, &'_ mut Vec<Self>, &mut Rustc<'_, '_>)>
53     for TokenTree<Group, Punct, Ident, Literal>
54 {
55     fn from_internal(
56         ((tree, spacing), stack, rustc): (TreeAndSpacing, &mut Vec<Self>, &mut Rustc<'_, '_>),
57     ) -> Self {
58         use rustc_ast::token::*;
59
60         let joint = spacing == Joint;
61         let Token { kind, span } = match tree {
62             tokenstream::TokenTree::Delimited(span, delim, tts) => {
63                 let delimiter = pm::Delimiter::from_internal(delim);
64                 return TokenTree::Group(Group { delimiter, stream: tts, span, flatten: false });
65             }
66             tokenstream::TokenTree::Token(token) => token,
67         };
68
69         macro_rules! tt {
70             ($ty:ident { $($field:ident $(: $value:expr)*),+ $(,)? }) => (
71                 TokenTree::$ty(self::$ty {
72                     $($field $(: $value)*,)+
73                     span,
74                 })
75             );
76             ($ty:ident::$method:ident($($value:expr),*)) => (
77                 TokenTree::$ty(self::$ty::$method($($value,)* span))
78             );
79         }
80         macro_rules! op {
81             ($a:expr) => {
82                 tt!(Punct::new($a, joint))
83             };
84             ($a:expr, $b:expr) => {{
85                 stack.push(tt!(Punct::new($b, joint)));
86                 tt!(Punct::new($a, true))
87             }};
88             ($a:expr, $b:expr, $c:expr) => {{
89                 stack.push(tt!(Punct::new($c, joint)));
90                 stack.push(tt!(Punct::new($b, true)));
91                 tt!(Punct::new($a, true))
92             }};
93         }
94
95         match kind {
96             Eq => op!('='),
97             Lt => op!('<'),
98             Le => op!('<', '='),
99             EqEq => op!('=', '='),
100             Ne => op!('!', '='),
101             Ge => op!('>', '='),
102             Gt => op!('>'),
103             AndAnd => op!('&', '&'),
104             OrOr => op!('|', '|'),
105             Not => op!('!'),
106             Tilde => op!('~'),
107             BinOp(Plus) => op!('+'),
108             BinOp(Minus) => op!('-'),
109             BinOp(Star) => op!('*'),
110             BinOp(Slash) => op!('/'),
111             BinOp(Percent) => op!('%'),
112             BinOp(Caret) => op!('^'),
113             BinOp(And) => op!('&'),
114             BinOp(Or) => op!('|'),
115             BinOp(Shl) => op!('<', '<'),
116             BinOp(Shr) => op!('>', '>'),
117             BinOpEq(Plus) => op!('+', '='),
118             BinOpEq(Minus) => op!('-', '='),
119             BinOpEq(Star) => op!('*', '='),
120             BinOpEq(Slash) => op!('/', '='),
121             BinOpEq(Percent) => op!('%', '='),
122             BinOpEq(Caret) => op!('^', '='),
123             BinOpEq(And) => op!('&', '='),
124             BinOpEq(Or) => op!('|', '='),
125             BinOpEq(Shl) => op!('<', '<', '='),
126             BinOpEq(Shr) => op!('>', '>', '='),
127             At => op!('@'),
128             Dot => op!('.'),
129             DotDot => op!('.', '.'),
130             DotDotDot => op!('.', '.', '.'),
131             DotDotEq => op!('.', '.', '='),
132             Comma => op!(','),
133             Semi => op!(';'),
134             Colon => op!(':'),
135             ModSep => op!(':', ':'),
136             RArrow => op!('-', '>'),
137             LArrow => op!('<', '-'),
138             FatArrow => op!('=', '>'),
139             Pound => op!('#'),
140             Dollar => op!('$'),
141             Question => op!('?'),
142             SingleQuote => op!('\''),
143
144             Ident(name, false) if name == kw::DollarCrate => tt!(Ident::dollar_crate()),
145             Ident(name, is_raw) => tt!(Ident::new(rustc.sess(), name, is_raw)),
146             Lifetime(name) => {
147                 let ident = symbol::Ident::new(name, span).without_first_quote();
148                 stack.push(tt!(Ident::new(rustc.sess(), ident.name, false)));
149                 tt!(Punct::new('\'', true))
150             }
151             Literal(lit) => tt!(Literal { lit }),
152             DocComment(_, attr_style, data) => {
153                 let mut escaped = String::new();
154                 for ch in data.as_str().chars() {
155                     escaped.extend(ch.escape_debug());
156                 }
157                 let stream = [
158                     Ident(sym::doc, false),
159                     Eq,
160                     TokenKind::lit(token::Str, Symbol::intern(&escaped), None),
161                 ]
162                 .into_iter()
163                 .map(|kind| tokenstream::TokenTree::token(kind, span))
164                 .collect();
165                 stack.push(TokenTree::Group(Group {
166                     delimiter: pm::Delimiter::Bracket,
167                     stream,
168                     span: DelimSpan::from_single(span),
169                     flatten: false,
170                 }));
171                 if attr_style == ast::AttrStyle::Inner {
172                     stack.push(tt!(Punct::new('!', false)));
173                 }
174                 tt!(Punct::new('#', false))
175             }
176
177             Interpolated(nt) if let NtIdent(ident, is_raw) = *nt => {
178                 TokenTree::Ident(Ident::new(rustc.sess(), ident.name, is_raw, ident.span))
179             }
180             Interpolated(nt) => {
181                 TokenTree::Group(Group {
182                     delimiter: pm::Delimiter::None,
183                     stream: TokenStream::from_nonterminal_ast(&nt),
184                     span: DelimSpan::from_single(span),
185                     flatten: crate::base::nt_pretty_printing_compatibility_hack(&nt, rustc.sess()),
186                 })
187             }
188
189             OpenDelim(..) | CloseDelim(..) => unreachable!(),
190             Eof => unreachable!(),
191         }
192     }
193 }
194
195 impl ToInternal<TokenStream> for TokenTree<Group, Punct, Ident, Literal> {
196     fn to_internal(self) -> TokenStream {
197         use rustc_ast::token::*;
198
199         let (ch, joint, span) = match self {
200             TokenTree::Punct(Punct { ch, joint, span }) => (ch, joint, span),
201             TokenTree::Group(Group { delimiter, stream, span, .. }) => {
202                 return tokenstream::TokenTree::Delimited(span, delimiter.to_internal(), stream)
203                     .into();
204             }
205             TokenTree::Ident(self::Ident { sym, is_raw, span }) => {
206                 return tokenstream::TokenTree::token(Ident(sym, is_raw), span).into();
207             }
208             TokenTree::Literal(self::Literal {
209                 lit: token::Lit { kind: token::Integer, symbol, suffix },
210                 span,
211             }) if symbol.as_str().starts_with('-') => {
212                 let minus = BinOp(BinOpToken::Minus);
213                 let symbol = Symbol::intern(&symbol.as_str()[1..]);
214                 let integer = TokenKind::lit(token::Integer, symbol, suffix);
215                 let a = tokenstream::TokenTree::token(minus, span);
216                 let b = tokenstream::TokenTree::token(integer, span);
217                 return [a, b].into_iter().collect();
218             }
219             TokenTree::Literal(self::Literal {
220                 lit: token::Lit { kind: token::Float, symbol, suffix },
221                 span,
222             }) if symbol.as_str().starts_with('-') => {
223                 let minus = BinOp(BinOpToken::Minus);
224                 let symbol = Symbol::intern(&symbol.as_str()[1..]);
225                 let float = TokenKind::lit(token::Float, symbol, suffix);
226                 let a = tokenstream::TokenTree::token(minus, span);
227                 let b = tokenstream::TokenTree::token(float, span);
228                 return [a, b].into_iter().collect();
229             }
230             TokenTree::Literal(self::Literal { lit, span }) => {
231                 return tokenstream::TokenTree::token(Literal(lit), span).into();
232             }
233         };
234
235         let kind = match ch {
236             '=' => Eq,
237             '<' => Lt,
238             '>' => Gt,
239             '!' => Not,
240             '~' => Tilde,
241             '+' => BinOp(Plus),
242             '-' => BinOp(Minus),
243             '*' => BinOp(Star),
244             '/' => BinOp(Slash),
245             '%' => BinOp(Percent),
246             '^' => BinOp(Caret),
247             '&' => BinOp(And),
248             '|' => BinOp(Or),
249             '@' => At,
250             '.' => Dot,
251             ',' => Comma,
252             ';' => Semi,
253             ':' => Colon,
254             '#' => Pound,
255             '$' => Dollar,
256             '?' => Question,
257             '\'' => SingleQuote,
258             _ => unreachable!(),
259         };
260
261         let tree = tokenstream::TokenTree::token(kind, span);
262         TokenStream::new(vec![(tree, if joint { Joint } else { Alone })])
263     }
264 }
265
266 impl ToInternal<rustc_errors::Level> for Level {
267     fn to_internal(self) -> rustc_errors::Level {
268         match self {
269             Level::Error => rustc_errors::Level::Error { lint: false },
270             Level::Warning => rustc_errors::Level::Warning(None),
271             Level::Note => rustc_errors::Level::Note,
272             Level::Help => rustc_errors::Level::Help,
273             _ => unreachable!("unknown proc_macro::Level variant: {:?}", self),
274         }
275     }
276 }
277
278 pub struct FreeFunctions;
279
280 #[derive(Clone)]
281 pub struct Group {
282     delimiter: Delimiter,
283     stream: TokenStream,
284     span: DelimSpan,
285     /// A hack used to pass AST fragments to attribute and derive macros
286     /// as a single nonterminal token instead of a token stream.
287     /// FIXME: It needs to be removed, but there are some compatibility issues (see #73345).
288     flatten: bool,
289 }
290
291 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
292 pub struct Punct {
293     ch: char,
294     // NB. not using `Spacing` here because it doesn't implement `Hash`.
295     joint: bool,
296     span: Span,
297 }
298
299 impl Punct {
300     fn new(ch: char, joint: bool, span: Span) -> Punct {
301         const LEGAL_CHARS: &[char] = &[
302             '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
303             ':', '#', '$', '?', '\'',
304         ];
305         if !LEGAL_CHARS.contains(&ch) {
306             panic!("unsupported character `{:?}`", ch)
307         }
308         Punct { ch, joint, span }
309     }
310 }
311
312 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
313 pub struct Ident {
314     sym: Symbol,
315     is_raw: bool,
316     span: Span,
317 }
318
319 impl Ident {
320     fn new(sess: &ParseSess, sym: Symbol, is_raw: bool, span: Span) -> Ident {
321         let sym = nfc_normalize(sym.as_str());
322         let string = sym.as_str();
323         if !rustc_lexer::is_ident(string) {
324             panic!("`{:?}` is not a valid identifier", string)
325         }
326         if is_raw && !sym.can_be_raw() {
327             panic!("`{}` cannot be a raw identifier", string);
328         }
329         sess.symbol_gallery.insert(sym, span);
330         Ident { sym, is_raw, span }
331     }
332
333     fn dollar_crate(span: Span) -> Ident {
334         // `$crate` is accepted as an ident only if it comes from the compiler.
335         Ident { sym: kw::DollarCrate, is_raw: false, span }
336     }
337 }
338
339 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
340 #[derive(Clone, Debug)]
341 pub struct Literal {
342     lit: token::Lit,
343     span: Span,
344 }
345
346 pub(crate) struct Rustc<'a, 'b> {
347     ecx: &'a mut ExtCtxt<'b>,
348     def_site: Span,
349     call_site: Span,
350     mixed_site: Span,
351     krate: CrateNum,
352     rebased_spans: FxHashMap<usize, Span>,
353 }
354
355 impl<'a, 'b> Rustc<'a, 'b> {
356     pub fn new(ecx: &'a mut ExtCtxt<'b>) -> Self {
357         let expn_data = ecx.current_expansion.id.expn_data();
358         Rustc {
359             def_site: ecx.with_def_site_ctxt(expn_data.def_site),
360             call_site: ecx.with_call_site_ctxt(expn_data.call_site),
361             mixed_site: ecx.with_mixed_site_ctxt(expn_data.call_site),
362             krate: expn_data.macro_def_id.unwrap().krate,
363             rebased_spans: FxHashMap::default(),
364             ecx,
365         }
366     }
367
368     fn sess(&self) -> &ParseSess {
369         self.ecx.parse_sess()
370     }
371
372     fn lit(&mut self, kind: token::LitKind, symbol: Symbol, suffix: Option<Symbol>) -> Literal {
373         Literal { lit: token::Lit::new(kind, symbol, suffix), span: server::Span::call_site(self) }
374     }
375 }
376
377 impl server::Types for Rustc<'_, '_> {
378     type FreeFunctions = FreeFunctions;
379     type TokenStream = TokenStream;
380     type Group = Group;
381     type Punct = Punct;
382     type Ident = Ident;
383     type Literal = Literal;
384     type SourceFile = Lrc<SourceFile>;
385     type MultiSpan = Vec<Span>;
386     type Diagnostic = Diagnostic;
387     type Span = Span;
388 }
389
390 impl server::FreeFunctions for Rustc<'_, '_> {
391     fn track_env_var(&mut self, var: &str, value: Option<&str>) {
392         self.sess()
393             .env_depinfo
394             .borrow_mut()
395             .insert((Symbol::intern(var), value.map(Symbol::intern)));
396     }
397
398     fn track_path(&mut self, path: &str) {
399         self.sess().file_depinfo.borrow_mut().insert(Symbol::intern(path));
400     }
401 }
402
403 impl server::TokenStream for Rustc<'_, '_> {
404     fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
405         stream.is_empty()
406     }
407
408     fn from_str(&mut self, src: &str) -> Self::TokenStream {
409         parse_stream_from_source_str(
410             FileName::proc_macro_source_code(src),
411             src.to_string(),
412             self.sess(),
413             Some(self.call_site),
414         )
415     }
416
417     fn to_string(&mut self, stream: &Self::TokenStream) -> String {
418         pprust::tts_to_string(stream)
419     }
420
421     fn expand_expr(&mut self, stream: &Self::TokenStream) -> Result<Self::TokenStream, ()> {
422         // Parse the expression from our tokenstream.
423         let expr: PResult<'_, _> = try {
424             let mut p = rustc_parse::stream_to_parser(
425                 self.sess(),
426                 stream.clone(),
427                 Some("proc_macro expand expr"),
428             );
429             let expr = p.parse_expr()?;
430             if p.token != token::Eof {
431                 p.unexpected()?;
432             }
433             expr
434         };
435         let expr = expr.map_err(|mut err| {
436             err.emit();
437         })?;
438
439         // Perform eager expansion on the expression.
440         let expr = self
441             .ecx
442             .expander()
443             .fully_expand_fragment(crate::expand::AstFragment::Expr(expr))
444             .make_expr();
445
446         // NOTE: For now, limit `expand_expr` to exclusively expand to literals.
447         // This may be relaxed in the future.
448         // We don't use `TokenStream::from_ast` as the tokenstream currently cannot
449         // be recovered in the general case.
450         match &expr.kind {
451             ast::ExprKind::Lit(l) => {
452                 Ok(tokenstream::TokenTree::token(token::Literal(l.token), l.span).into())
453             }
454             ast::ExprKind::Unary(ast::UnOp::Neg, e) => match &e.kind {
455                 ast::ExprKind::Lit(l) => match l.token {
456                     token::Lit { kind: token::Integer | token::Float, .. } => {
457                         Ok(Self::TokenStream::from_iter([
458                             // FIXME: The span of the `-` token is lost when
459                             // parsing, so we cannot faithfully recover it here.
460                             tokenstream::TokenTree::token(token::BinOp(token::Minus), e.span),
461                             tokenstream::TokenTree::token(token::Literal(l.token), l.span),
462                         ]))
463                     }
464                     _ => Err(()),
465                 },
466                 _ => Err(()),
467             },
468             _ => Err(()),
469         }
470     }
471
472     fn from_token_tree(
473         &mut self,
474         tree: TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>,
475     ) -> Self::TokenStream {
476         tree.to_internal()
477     }
478
479     fn concat_trees(
480         &mut self,
481         base: Option<Self::TokenStream>,
482         trees: Vec<TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>>,
483     ) -> Self::TokenStream {
484         let mut builder = tokenstream::TokenStreamBuilder::new();
485         if let Some(base) = base {
486             builder.push(base);
487         }
488         for tree in trees {
489             builder.push(tree.to_internal());
490         }
491         builder.build()
492     }
493
494     fn concat_streams(
495         &mut self,
496         base: Option<Self::TokenStream>,
497         streams: Vec<Self::TokenStream>,
498     ) -> Self::TokenStream {
499         let mut builder = tokenstream::TokenStreamBuilder::new();
500         if let Some(base) = base {
501             builder.push(base);
502         }
503         for stream in streams {
504             builder.push(stream);
505         }
506         builder.build()
507     }
508
509     fn into_trees(
510         &mut self,
511         stream: Self::TokenStream,
512     ) -> Vec<TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>> {
513         // FIXME: This is a raw port of the previous approach (which had a
514         // `TokenStreamIter` server-side object with a single `next` method),
515         // and can probably be optimized (for bulk conversion).
516         let mut cursor = stream.into_trees();
517         let mut stack = Vec::new();
518         let mut tts = Vec::new();
519         loop {
520             let next = stack.pop().or_else(|| {
521                 let next = cursor.next_with_spacing()?;
522                 Some(TokenTree::from_internal((next, &mut stack, self)))
523             });
524             match next {
525                 Some(TokenTree::Group(group)) => {
526                     // A hack used to pass AST fragments to attribute and derive
527                     // macros as a single nonterminal token instead of a token
528                     // stream.  Such token needs to be "unwrapped" and not
529                     // represented as a delimited group.
530                     // FIXME: It needs to be removed, but there are some
531                     // compatibility issues (see #73345).
532                     if group.flatten {
533                         tts.append(&mut self.into_trees(group.stream));
534                     } else {
535                         tts.push(TokenTree::Group(group));
536                     }
537                 }
538                 Some(tt) => tts.push(tt),
539                 None => return tts,
540             }
541         }
542     }
543 }
544
545 impl server::Group for Rustc<'_, '_> {
546     fn new(&mut self, delimiter: Delimiter, stream: Option<Self::TokenStream>) -> Self::Group {
547         Group {
548             delimiter,
549             stream: stream.unwrap_or_default(),
550             span: DelimSpan::from_single(server::Span::call_site(self)),
551             flatten: false,
552         }
553     }
554
555     fn delimiter(&mut self, group: &Self::Group) -> Delimiter {
556         group.delimiter
557     }
558
559     fn stream(&mut self, group: &Self::Group) -> Self::TokenStream {
560         group.stream.clone()
561     }
562
563     fn span(&mut self, group: &Self::Group) -> Self::Span {
564         group.span.entire()
565     }
566
567     fn span_open(&mut self, group: &Self::Group) -> Self::Span {
568         group.span.open
569     }
570
571     fn span_close(&mut self, group: &Self::Group) -> Self::Span {
572         group.span.close
573     }
574
575     fn set_span(&mut self, group: &mut Self::Group, span: Self::Span) {
576         group.span = DelimSpan::from_single(span);
577     }
578 }
579
580 impl server::Punct for Rustc<'_, '_> {
581     fn new(&mut self, ch: char, spacing: Spacing) -> Self::Punct {
582         Punct::new(ch, spacing == Spacing::Joint, server::Span::call_site(self))
583     }
584
585     fn as_char(&mut self, punct: Self::Punct) -> char {
586         punct.ch
587     }
588
589     fn spacing(&mut self, punct: Self::Punct) -> Spacing {
590         if punct.joint { Spacing::Joint } else { Spacing::Alone }
591     }
592
593     fn span(&mut self, punct: Self::Punct) -> Self::Span {
594         punct.span
595     }
596
597     fn with_span(&mut self, punct: Self::Punct, span: Self::Span) -> Self::Punct {
598         Punct { span, ..punct }
599     }
600 }
601
602 impl server::Ident for Rustc<'_, '_> {
603     fn new(&mut self, string: &str, span: Self::Span, is_raw: bool) -> Self::Ident {
604         Ident::new(self.sess(), Symbol::intern(string), is_raw, span)
605     }
606
607     fn span(&mut self, ident: Self::Ident) -> Self::Span {
608         ident.span
609     }
610
611     fn with_span(&mut self, ident: Self::Ident, span: Self::Span) -> Self::Ident {
612         Ident { span, ..ident }
613     }
614 }
615
616 impl server::Literal for Rustc<'_, '_> {
617     fn from_str(&mut self, s: &str) -> Result<Self::Literal, ()> {
618         let name = FileName::proc_macro_source_code(s);
619         let mut parser = rustc_parse::new_parser_from_source_str(self.sess(), name, s.to_owned());
620
621         let first_span = parser.token.span.data();
622         let minus_present = parser.eat(&token::BinOp(token::Minus));
623
624         let lit_span = parser.token.span.data();
625         let token::Literal(mut lit) = parser.token.kind else {
626             return Err(());
627         };
628
629         // Check no comment or whitespace surrounding the (possibly negative)
630         // literal, or more tokens after it.
631         if (lit_span.hi.0 - first_span.lo.0) as usize != s.len() {
632             return Err(());
633         }
634
635         if minus_present {
636             // If minus is present, check no comment or whitespace in between it
637             // and the literal token.
638             if first_span.hi.0 != lit_span.lo.0 {
639                 return Err(());
640             }
641
642             // Check literal is a kind we allow to be negated in a proc macro token.
643             match lit.kind {
644                 token::LitKind::Bool
645                 | token::LitKind::Byte
646                 | token::LitKind::Char
647                 | token::LitKind::Str
648                 | token::LitKind::StrRaw(_)
649                 | token::LitKind::ByteStr
650                 | token::LitKind::ByteStrRaw(_)
651                 | token::LitKind::Err => return Err(()),
652                 token::LitKind::Integer | token::LitKind::Float => {}
653             }
654
655             // Synthesize a new symbol that includes the minus sign.
656             let symbol = Symbol::intern(&s[..1 + lit.symbol.as_str().len()]);
657             lit = token::Lit::new(lit.kind, symbol, lit.suffix);
658         }
659
660         Ok(Literal { lit, span: self.call_site })
661     }
662
663     fn to_string(&mut self, literal: &Self::Literal) -> String {
664         literal.lit.to_string()
665     }
666
667     fn debug_kind(&mut self, literal: &Self::Literal) -> String {
668         format!("{:?}", literal.lit.kind)
669     }
670
671     fn symbol(&mut self, literal: &Self::Literal) -> String {
672         literal.lit.symbol.to_string()
673     }
674
675     fn suffix(&mut self, literal: &Self::Literal) -> Option<String> {
676         literal.lit.suffix.as_ref().map(Symbol::to_string)
677     }
678
679     fn integer(&mut self, n: &str) -> Self::Literal {
680         self.lit(token::Integer, Symbol::intern(n), None)
681     }
682
683     fn typed_integer(&mut self, n: &str, kind: &str) -> Self::Literal {
684         self.lit(token::Integer, Symbol::intern(n), Some(Symbol::intern(kind)))
685     }
686
687     fn float(&mut self, n: &str) -> Self::Literal {
688         self.lit(token::Float, Symbol::intern(n), None)
689     }
690
691     fn f32(&mut self, n: &str) -> Self::Literal {
692         self.lit(token::Float, Symbol::intern(n), Some(sym::f32))
693     }
694
695     fn f64(&mut self, n: &str) -> Self::Literal {
696         self.lit(token::Float, Symbol::intern(n), Some(sym::f64))
697     }
698
699     fn string(&mut self, string: &str) -> Self::Literal {
700         let quoted = format!("{:?}", string);
701         assert!(quoted.starts_with('"') && quoted.ends_with('"'));
702         let symbol = &quoted[1..quoted.len() - 1];
703         self.lit(token::Str, Symbol::intern(symbol), None)
704     }
705
706     fn character(&mut self, ch: char) -> Self::Literal {
707         let quoted = format!("{:?}", ch);
708         assert!(quoted.starts_with('\'') && quoted.ends_with('\''));
709         let symbol = &quoted[1..quoted.len() - 1];
710         self.lit(token::Char, Symbol::intern(symbol), None)
711     }
712
713     fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
714         let string = bytes
715             .iter()
716             .cloned()
717             .flat_map(ascii::escape_default)
718             .map(Into::<char>::into)
719             .collect::<String>();
720         self.lit(token::ByteStr, Symbol::intern(&string), None)
721     }
722
723     fn span(&mut self, literal: &Self::Literal) -> Self::Span {
724         literal.span
725     }
726
727     fn set_span(&mut self, literal: &mut Self::Literal, span: Self::Span) {
728         literal.span = span;
729     }
730
731     fn subspan(
732         &mut self,
733         literal: &Self::Literal,
734         start: Bound<usize>,
735         end: Bound<usize>,
736     ) -> Option<Self::Span> {
737         let span = literal.span;
738         let length = span.hi().to_usize() - span.lo().to_usize();
739
740         let start = match start {
741             Bound::Included(lo) => lo,
742             Bound::Excluded(lo) => lo.checked_add(1)?,
743             Bound::Unbounded => 0,
744         };
745
746         let end = match end {
747             Bound::Included(hi) => hi.checked_add(1)?,
748             Bound::Excluded(hi) => hi,
749             Bound::Unbounded => length,
750         };
751
752         // Bounds check the values, preventing addition overflow and OOB spans.
753         if start > u32::MAX as usize
754             || end > u32::MAX as usize
755             || (u32::MAX - start as u32) < span.lo().to_u32()
756             || (u32::MAX - end as u32) < span.lo().to_u32()
757             || start >= end
758             || end > length
759         {
760             return None;
761         }
762
763         let new_lo = span.lo() + BytePos::from_usize(start);
764         let new_hi = span.lo() + BytePos::from_usize(end);
765         Some(span.with_lo(new_lo).with_hi(new_hi))
766     }
767 }
768
769 impl server::SourceFile for Rustc<'_, '_> {
770     fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
771         Lrc::ptr_eq(file1, file2)
772     }
773
774     fn path(&mut self, file: &Self::SourceFile) -> String {
775         match file.name {
776             FileName::Real(ref name) => name
777                 .local_path()
778                 .expect("attempting to get a file path in an imported file in `proc_macro::SourceFile::path`")
779                 .to_str()
780                 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
781                 .to_string(),
782             _ => file.name.prefer_local().to_string(),
783         }
784     }
785
786     fn is_real(&mut self, file: &Self::SourceFile) -> bool {
787         file.is_real_file()
788     }
789 }
790
791 impl server::MultiSpan for Rustc<'_, '_> {
792     fn new(&mut self) -> Self::MultiSpan {
793         vec![]
794     }
795
796     fn push(&mut self, spans: &mut Self::MultiSpan, span: Self::Span) {
797         spans.push(span)
798     }
799 }
800
801 impl server::Diagnostic for Rustc<'_, '_> {
802     fn new(&mut self, level: Level, msg: &str, spans: Self::MultiSpan) -> Self::Diagnostic {
803         let mut diag = Diagnostic::new(level.to_internal(), msg);
804         diag.set_span(MultiSpan::from_spans(spans));
805         diag
806     }
807
808     fn sub(
809         &mut self,
810         diag: &mut Self::Diagnostic,
811         level: Level,
812         msg: &str,
813         spans: Self::MultiSpan,
814     ) {
815         diag.sub(level.to_internal(), msg, MultiSpan::from_spans(spans), None);
816     }
817
818     fn emit(&mut self, mut diag: Self::Diagnostic) {
819         self.sess().span_diagnostic.emit_diagnostic(&mut diag);
820     }
821 }
822
823 impl server::Span for Rustc<'_, '_> {
824     fn debug(&mut self, span: Self::Span) -> String {
825         if self.ecx.ecfg.span_debug {
826             format!("{:?}", span)
827         } else {
828             format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
829         }
830     }
831
832     fn def_site(&mut self) -> Self::Span {
833         self.def_site
834     }
835
836     fn call_site(&mut self) -> Self::Span {
837         self.call_site
838     }
839
840     fn mixed_site(&mut self) -> Self::Span {
841         self.mixed_site
842     }
843
844     fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
845         self.sess().source_map().lookup_char_pos(span.lo()).file
846     }
847
848     fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
849         span.parent_callsite()
850     }
851
852     fn source(&mut self, span: Self::Span) -> Self::Span {
853         span.source_callsite()
854     }
855
856     fn start(&mut self, span: Self::Span) -> LineColumn {
857         let loc = self.sess().source_map().lookup_char_pos(span.lo());
858         LineColumn { line: loc.line, column: loc.col.to_usize() }
859     }
860
861     fn end(&mut self, span: Self::Span) -> LineColumn {
862         let loc = self.sess().source_map().lookup_char_pos(span.hi());
863         LineColumn { line: loc.line, column: loc.col.to_usize() }
864     }
865
866     fn before(&mut self, span: Self::Span) -> Self::Span {
867         span.shrink_to_lo()
868     }
869
870     fn after(&mut self, span: Self::Span) -> Self::Span {
871         span.shrink_to_hi()
872     }
873
874     fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
875         let self_loc = self.sess().source_map().lookup_char_pos(first.lo());
876         let other_loc = self.sess().source_map().lookup_char_pos(second.lo());
877
878         if self_loc.file.name != other_loc.file.name {
879             return None;
880         }
881
882         Some(first.to(second))
883     }
884
885     fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
886         span.with_ctxt(at.ctxt())
887     }
888
889     fn source_text(&mut self, span: Self::Span) -> Option<String> {
890         self.sess().source_map().span_to_snippet(span).ok()
891     }
892     /// Saves the provided span into the metadata of
893     /// *the crate we are currently compiling*, which must
894     /// be a proc-macro crate. This id can be passed to
895     /// `recover_proc_macro_span` when our current crate
896     /// is *run* as a proc-macro.
897     ///
898     /// Let's suppose that we have two crates - `my_client`
899     /// and `my_proc_macro`. The `my_proc_macro` crate
900     /// contains a procedural macro `my_macro`, which
901     /// is implemented as: `quote! { "hello" }`
902     ///
903     /// When we *compile* `my_proc_macro`, we will execute
904     /// the `quote` proc-macro. This will save the span of
905     /// "hello" into the metadata of `my_proc_macro`. As a result,
906     /// the body of `my_proc_macro` (after expansion) will end
907     /// up containing a call that looks like this:
908     /// `proc_macro::Ident::new("hello", proc_macro::Span::recover_proc_macro_span(0))`
909     ///
910     /// where `0` is the id returned by this function.
911     /// When `my_proc_macro` *executes* (during the compilation of `my_client`),
912     /// the call to `recover_proc_macro_span` will load the corresponding
913     /// span from the metadata of `my_proc_macro` (which we have access to,
914     /// since we've loaded `my_proc_macro` from disk in order to execute it).
915     /// In this way, we have obtained a span pointing into `my_proc_macro`
916     fn save_span(&mut self, span: Self::Span) -> usize {
917         self.sess().save_proc_macro_span(span)
918     }
919
920     fn recover_proc_macro_span(&mut self, id: usize) -> Self::Span {
921         let (resolver, krate, def_site) = (&*self.ecx.resolver, self.krate, self.def_site);
922         *self.rebased_spans.entry(id).or_insert_with(|| {
923             // FIXME: `SyntaxContext` for spans from proc macro crates is lost during encoding,
924             // replace it with a def-site context until we are encoding it properly.
925             resolver.get_proc_macro_quoted_span(krate, id).with_ctxt(def_site.ctxt())
926         })
927     }
928 }