]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_expand/src/proc_macro_server.rs
proc_macro: reduce the number of messages required to create, extend, and iterate...
[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,
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     fn dollar_crate(span: Span) -> Ident {
333         // `$crate` is accepted as an ident only if it comes from the compiler.
334         Ident { sym: kw::DollarCrate, is_raw: false, span }
335     }
336 }
337
338 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
339 #[derive(Clone, Debug)]
340 pub struct Literal {
341     lit: token::Lit,
342     span: Span,
343 }
344
345 pub(crate) struct Rustc<'a, 'b> {
346     ecx: &'a mut ExtCtxt<'b>,
347     def_site: Span,
348     call_site: Span,
349     mixed_site: Span,
350     krate: CrateNum,
351     rebased_spans: FxHashMap<usize, Span>,
352 }
353
354 impl<'a, 'b> Rustc<'a, 'b> {
355     pub fn new(ecx: &'a mut ExtCtxt<'b>) -> Self {
356         let expn_data = ecx.current_expansion.id.expn_data();
357         Rustc {
358             def_site: ecx.with_def_site_ctxt(expn_data.def_site),
359             call_site: ecx.with_call_site_ctxt(expn_data.call_site),
360             mixed_site: ecx.with_mixed_site_ctxt(expn_data.call_site),
361             krate: expn_data.macro_def_id.unwrap().krate,
362             rebased_spans: FxHashMap::default(),
363             ecx,
364         }
365     }
366
367     fn sess(&self) -> &ParseSess {
368         self.ecx.parse_sess()
369     }
370
371     fn lit(&mut self, kind: token::LitKind, symbol: Symbol, suffix: Option<Symbol>) -> Literal {
372         Literal { lit: token::Lit::new(kind, symbol, suffix), span: server::Span::call_site(self) }
373     }
374 }
375
376 impl server::Types for Rustc<'_, '_> {
377     type FreeFunctions = FreeFunctions;
378     type TokenStream = TokenStream;
379     type Group = Group;
380     type Punct = Punct;
381     type Ident = Ident;
382     type Literal = Literal;
383     type SourceFile = Lrc<SourceFile>;
384     type MultiSpan = Vec<Span>;
385     type Diagnostic = Diagnostic;
386     type Span = Span;
387 }
388
389 impl server::FreeFunctions for Rustc<'_, '_> {
390     fn track_env_var(&mut self, var: &str, value: Option<&str>) {
391         self.sess()
392             .env_depinfo
393             .borrow_mut()
394             .insert((Symbol::intern(var), value.map(Symbol::intern)));
395     }
396
397     fn track_path(&mut self, path: &str) {
398         self.sess().file_depinfo.borrow_mut().insert(Symbol::intern(path));
399     }
400 }
401
402 impl server::TokenStream for Rustc<'_, '_> {
403     fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
404         stream.is_empty()
405     }
406     fn from_str(&mut self, src: &str) -> Self::TokenStream {
407         parse_stream_from_source_str(
408             FileName::proc_macro_source_code(src),
409             src.to_string(),
410             self.sess(),
411             Some(self.call_site),
412         )
413     }
414     fn to_string(&mut self, stream: &Self::TokenStream) -> String {
415         pprust::tts_to_string(stream)
416     }
417     fn expand_expr(&mut self, stream: &Self::TokenStream) -> Result<Self::TokenStream, ()> {
418         // Parse the expression from our tokenstream.
419         let expr: PResult<'_, _> = try {
420             let mut p = rustc_parse::stream_to_parser(
421                 self.sess(),
422                 stream.clone(),
423                 Some("proc_macro expand expr"),
424             );
425             let expr = p.parse_expr()?;
426             if p.token != token::Eof {
427                 p.unexpected()?;
428             }
429             expr
430         };
431         let expr = expr.map_err(|mut err| {
432             err.emit();
433         })?;
434
435         // Perform eager expansion on the expression.
436         let expr = self
437             .ecx
438             .expander()
439             .fully_expand_fragment(crate::expand::AstFragment::Expr(expr))
440             .make_expr();
441
442         // NOTE: For now, limit `expand_expr` to exclusively expand to literals.
443         // This may be relaxed in the future.
444         // We don't use `TokenStream::from_ast` as the tokenstream currently cannot
445         // be recovered in the general case.
446         match &expr.kind {
447             ast::ExprKind::Lit(l) => {
448                 Ok(tokenstream::TokenTree::token(token::Literal(l.token), l.span).into())
449             }
450             ast::ExprKind::Unary(ast::UnOp::Neg, e) => match &e.kind {
451                 ast::ExprKind::Lit(l) => match l.token {
452                     token::Lit { kind: token::Integer | token::Float, .. } => {
453                         Ok(Self::TokenStream::from_iter([
454                             // FIXME: The span of the `-` token is lost when
455                             // parsing, so we cannot faithfully recover it here.
456                             tokenstream::TokenTree::token(token::BinOp(token::Minus), e.span),
457                             tokenstream::TokenTree::token(token::Literal(l.token), l.span),
458                         ]))
459                     }
460                     _ => Err(()),
461                 },
462                 _ => Err(()),
463             },
464             _ => Err(()),
465         }
466     }
467     fn from_token_tree(
468         &mut self,
469         tree: TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>,
470     ) -> Self::TokenStream {
471         tree.to_internal()
472     }
473     fn concat_trees(
474         &mut self,
475         base: Option<Self::TokenStream>,
476         trees: Vec<TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>>,
477     ) -> Self::TokenStream {
478         let mut builder = tokenstream::TokenStreamBuilder::new();
479         if let Some(base) = base {
480             builder.push(base);
481         }
482         for tree in trees {
483             builder.push(tree.to_internal());
484         }
485         builder.build()
486     }
487     fn concat_streams(
488         &mut self,
489         base: Option<Self::TokenStream>,
490         streams: Vec<Self::TokenStream>,
491     ) -> Self::TokenStream {
492         let mut builder = tokenstream::TokenStreamBuilder::new();
493         if let Some(base) = base {
494             builder.push(base);
495         }
496         for stream in streams {
497             builder.push(stream);
498         }
499         builder.build()
500     }
501     fn into_iter(
502         &mut self,
503         stream: Self::TokenStream,
504     ) -> Vec<TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>> {
505         // XXX: This is a raw port of the previous approach, and can probably be
506         // optimized.
507         let mut cursor = stream.into_trees();
508         let mut stack = Vec::new();
509         let mut tts = Vec::new();
510         loop {
511             let next = stack.pop().or_else(|| {
512                 let next = cursor.next_with_spacing()?;
513                 Some(TokenTree::from_internal((next, &mut stack, self)))
514             });
515             match next {
516                 Some(TokenTree::Group(group)) => {
517                     // A hack used to pass AST fragments to attribute and derive
518                     // macros as a single nonterminal token instead of a token
519                     // stream.  Such token needs to be "unwrapped" and not
520                     // represented as a delimited group.
521                     // FIXME: It needs to be removed, but there are some
522                     // compatibility issues (see #73345).
523                     if group.flatten {
524                         cursor.append(group.stream);
525                         continue;
526                     }
527                     tts.push(TokenTree::Group(group));
528                 }
529                 Some(tt) => tts.push(tt),
530                 None => return tts,
531             }
532         }
533     }
534 }
535
536 impl server::Group for Rustc<'_, '_> {
537     fn new(&mut self, delimiter: Delimiter, stream: Option<Self::TokenStream>) -> Self::Group {
538         Group {
539             delimiter,
540             stream: stream.unwrap_or_default(),
541             span: DelimSpan::from_single(server::Span::call_site(self)),
542             flatten: false,
543         }
544     }
545     fn delimiter(&mut self, group: &Self::Group) -> Delimiter {
546         group.delimiter
547     }
548     fn stream(&mut self, group: &Self::Group) -> Self::TokenStream {
549         group.stream.clone()
550     }
551     fn span(&mut self, group: &Self::Group) -> Self::Span {
552         group.span.entire()
553     }
554     fn span_open(&mut self, group: &Self::Group) -> Self::Span {
555         group.span.open
556     }
557     fn span_close(&mut self, group: &Self::Group) -> Self::Span {
558         group.span.close
559     }
560     fn set_span(&mut self, group: &mut Self::Group, span: Self::Span) {
561         group.span = DelimSpan::from_single(span);
562     }
563 }
564
565 impl server::Punct for Rustc<'_, '_> {
566     fn new(&mut self, ch: char, spacing: Spacing) -> Self::Punct {
567         Punct::new(ch, spacing == Spacing::Joint, server::Span::call_site(self))
568     }
569     fn as_char(&mut self, punct: Self::Punct) -> char {
570         punct.ch
571     }
572     fn spacing(&mut self, punct: Self::Punct) -> Spacing {
573         if punct.joint { Spacing::Joint } else { Spacing::Alone }
574     }
575     fn span(&mut self, punct: Self::Punct) -> Self::Span {
576         punct.span
577     }
578     fn with_span(&mut self, punct: Self::Punct, span: Self::Span) -> Self::Punct {
579         Punct { span, ..punct }
580     }
581 }
582
583 impl server::Ident for Rustc<'_, '_> {
584     fn new(&mut self, string: &str, span: Self::Span, is_raw: bool) -> Self::Ident {
585         Ident::new(self.sess(), Symbol::intern(string), is_raw, span)
586     }
587     fn span(&mut self, ident: Self::Ident) -> Self::Span {
588         ident.span
589     }
590     fn with_span(&mut self, ident: Self::Ident, span: Self::Span) -> Self::Ident {
591         Ident { span, ..ident }
592     }
593 }
594
595 impl server::Literal for Rustc<'_, '_> {
596     fn from_str(&mut self, s: &str) -> Result<Self::Literal, ()> {
597         let name = FileName::proc_macro_source_code(s);
598         let mut parser = rustc_parse::new_parser_from_source_str(self.sess(), name, s.to_owned());
599
600         let first_span = parser.token.span.data();
601         let minus_present = parser.eat(&token::BinOp(token::Minus));
602
603         let lit_span = parser.token.span.data();
604         let token::Literal(mut lit) = parser.token.kind else {
605             return Err(());
606         };
607
608         // Check no comment or whitespace surrounding the (possibly negative)
609         // literal, or more tokens after it.
610         if (lit_span.hi.0 - first_span.lo.0) as usize != s.len() {
611             return Err(());
612         }
613
614         if minus_present {
615             // If minus is present, check no comment or whitespace in between it
616             // and the literal token.
617             if first_span.hi.0 != lit_span.lo.0 {
618                 return Err(());
619             }
620
621             // Check literal is a kind we allow to be negated in a proc macro token.
622             match lit.kind {
623                 token::LitKind::Bool
624                 | token::LitKind::Byte
625                 | token::LitKind::Char
626                 | token::LitKind::Str
627                 | token::LitKind::StrRaw(_)
628                 | token::LitKind::ByteStr
629                 | token::LitKind::ByteStrRaw(_)
630                 | token::LitKind::Err => return Err(()),
631                 token::LitKind::Integer | token::LitKind::Float => {}
632             }
633
634             // Synthesize a new symbol that includes the minus sign.
635             let symbol = Symbol::intern(&s[..1 + lit.symbol.as_str().len()]);
636             lit = token::Lit::new(lit.kind, symbol, lit.suffix);
637         }
638
639         Ok(Literal { lit, span: self.call_site })
640     }
641     fn to_string(&mut self, literal: &Self::Literal) -> String {
642         literal.lit.to_string()
643     }
644     fn debug_kind(&mut self, literal: &Self::Literal) -> String {
645         format!("{:?}", literal.lit.kind)
646     }
647     fn symbol(&mut self, literal: &Self::Literal) -> String {
648         literal.lit.symbol.to_string()
649     }
650     fn suffix(&mut self, literal: &Self::Literal) -> Option<String> {
651         literal.lit.suffix.as_ref().map(Symbol::to_string)
652     }
653     fn integer(&mut self, n: &str) -> Self::Literal {
654         self.lit(token::Integer, Symbol::intern(n), None)
655     }
656     fn typed_integer(&mut self, n: &str, kind: &str) -> Self::Literal {
657         self.lit(token::Integer, Symbol::intern(n), Some(Symbol::intern(kind)))
658     }
659     fn float(&mut self, n: &str) -> Self::Literal {
660         self.lit(token::Float, Symbol::intern(n), None)
661     }
662     fn f32(&mut self, n: &str) -> Self::Literal {
663         self.lit(token::Float, Symbol::intern(n), Some(sym::f32))
664     }
665     fn f64(&mut self, n: &str) -> Self::Literal {
666         self.lit(token::Float, Symbol::intern(n), Some(sym::f64))
667     }
668     fn string(&mut self, string: &str) -> Self::Literal {
669         let quoted = format!("{:?}", string);
670         assert!(quoted.starts_with('"') && quoted.ends_with('"'));
671         let symbol = &quoted[1..quoted.len() - 1];
672         self.lit(token::Str, Symbol::intern(symbol), None)
673     }
674     fn character(&mut self, ch: char) -> Self::Literal {
675         let quoted = format!("{:?}", ch);
676         assert!(quoted.starts_with('\'') && quoted.ends_with('\''));
677         let symbol = &quoted[1..quoted.len() - 1];
678         self.lit(token::Char, Symbol::intern(symbol), None)
679     }
680     fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
681         let string = bytes
682             .iter()
683             .cloned()
684             .flat_map(ascii::escape_default)
685             .map(Into::<char>::into)
686             .collect::<String>();
687         self.lit(token::ByteStr, Symbol::intern(&string), None)
688     }
689     fn span(&mut self, literal: &Self::Literal) -> Self::Span {
690         literal.span
691     }
692     fn set_span(&mut self, literal: &mut Self::Literal, span: Self::Span) {
693         literal.span = span;
694     }
695     fn subspan(
696         &mut self,
697         literal: &Self::Literal,
698         start: Bound<usize>,
699         end: Bound<usize>,
700     ) -> Option<Self::Span> {
701         let span = literal.span;
702         let length = span.hi().to_usize() - span.lo().to_usize();
703
704         let start = match start {
705             Bound::Included(lo) => lo,
706             Bound::Excluded(lo) => lo.checked_add(1)?,
707             Bound::Unbounded => 0,
708         };
709
710         let end = match end {
711             Bound::Included(hi) => hi.checked_add(1)?,
712             Bound::Excluded(hi) => hi,
713             Bound::Unbounded => length,
714         };
715
716         // Bounds check the values, preventing addition overflow and OOB spans.
717         if start > u32::MAX as usize
718             || end > u32::MAX as usize
719             || (u32::MAX - start as u32) < span.lo().to_u32()
720             || (u32::MAX - end as u32) < span.lo().to_u32()
721             || start >= end
722             || end > length
723         {
724             return None;
725         }
726
727         let new_lo = span.lo() + BytePos::from_usize(start);
728         let new_hi = span.lo() + BytePos::from_usize(end);
729         Some(span.with_lo(new_lo).with_hi(new_hi))
730     }
731 }
732
733 impl server::SourceFile for Rustc<'_, '_> {
734     fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
735         Lrc::ptr_eq(file1, file2)
736     }
737     fn path(&mut self, file: &Self::SourceFile) -> String {
738         match file.name {
739             FileName::Real(ref name) => name
740                 .local_path()
741                 .expect("attempting to get a file path in an imported file in `proc_macro::SourceFile::path`")
742                 .to_str()
743                 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
744                 .to_string(),
745             _ => file.name.prefer_local().to_string(),
746         }
747     }
748     fn is_real(&mut self, file: &Self::SourceFile) -> bool {
749         file.is_real_file()
750     }
751 }
752
753 impl server::MultiSpan for Rustc<'_, '_> {
754     fn new(&mut self) -> Self::MultiSpan {
755         vec![]
756     }
757     fn push(&mut self, spans: &mut Self::MultiSpan, span: Self::Span) {
758         spans.push(span)
759     }
760 }
761
762 impl server::Diagnostic for Rustc<'_, '_> {
763     fn new(&mut self, level: Level, msg: &str, spans: Self::MultiSpan) -> Self::Diagnostic {
764         let mut diag = Diagnostic::new(level.to_internal(), msg);
765         diag.set_span(MultiSpan::from_spans(spans));
766         diag
767     }
768     fn sub(
769         &mut self,
770         diag: &mut Self::Diagnostic,
771         level: Level,
772         msg: &str,
773         spans: Self::MultiSpan,
774     ) {
775         diag.sub(level.to_internal(), msg, MultiSpan::from_spans(spans), None);
776     }
777     fn emit(&mut self, mut diag: Self::Diagnostic) {
778         self.sess().span_diagnostic.emit_diagnostic(&mut diag);
779     }
780 }
781
782 impl server::Span for Rustc<'_, '_> {
783     fn debug(&mut self, span: Self::Span) -> String {
784         if self.ecx.ecfg.span_debug {
785             format!("{:?}", span)
786         } else {
787             format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
788         }
789     }
790     fn def_site(&mut self) -> Self::Span {
791         self.def_site
792     }
793     fn call_site(&mut self) -> Self::Span {
794         self.call_site
795     }
796     fn mixed_site(&mut self) -> Self::Span {
797         self.mixed_site
798     }
799     fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
800         self.sess().source_map().lookup_char_pos(span.lo()).file
801     }
802     fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
803         span.parent_callsite()
804     }
805     fn source(&mut self, span: Self::Span) -> Self::Span {
806         span.source_callsite()
807     }
808     fn start(&mut self, span: Self::Span) -> LineColumn {
809         let loc = self.sess().source_map().lookup_char_pos(span.lo());
810         LineColumn { line: loc.line, column: loc.col.to_usize() }
811     }
812     fn end(&mut self, span: Self::Span) -> LineColumn {
813         let loc = self.sess().source_map().lookup_char_pos(span.hi());
814         LineColumn { line: loc.line, column: loc.col.to_usize() }
815     }
816     fn before(&mut self, span: Self::Span) -> Self::Span {
817         span.shrink_to_lo()
818     }
819     fn after(&mut self, span: Self::Span) -> Self::Span {
820         span.shrink_to_hi()
821     }
822     fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
823         let self_loc = self.sess().source_map().lookup_char_pos(first.lo());
824         let other_loc = self.sess().source_map().lookup_char_pos(second.lo());
825
826         if self_loc.file.name != other_loc.file.name {
827             return None;
828         }
829
830         Some(first.to(second))
831     }
832     fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
833         span.with_ctxt(at.ctxt())
834     }
835     fn source_text(&mut self, span: Self::Span) -> Option<String> {
836         self.sess().source_map().span_to_snippet(span).ok()
837     }
838     /// Saves the provided span into the metadata of
839     /// *the crate we are currently compiling*, which must
840     /// be a proc-macro crate. This id can be passed to
841     /// `recover_proc_macro_span` when our current crate
842     /// is *run* as a proc-macro.
843     ///
844     /// Let's suppose that we have two crates - `my_client`
845     /// and `my_proc_macro`. The `my_proc_macro` crate
846     /// contains a procedural macro `my_macro`, which
847     /// is implemented as: `quote! { "hello" }`
848     ///
849     /// When we *compile* `my_proc_macro`, we will execute
850     /// the `quote` proc-macro. This will save the span of
851     /// "hello" into the metadata of `my_proc_macro`. As a result,
852     /// the body of `my_proc_macro` (after expansion) will end
853     /// up containing a call that looks like this:
854     /// `proc_macro::Ident::new("hello", proc_macro::Span::recover_proc_macro_span(0))`
855     ///
856     /// where `0` is the id returned by this function.
857     /// When `my_proc_macro` *executes* (during the compilation of `my_client`),
858     /// the call to `recover_proc_macro_span` will load the corresponding
859     /// span from the metadata of `my_proc_macro` (which we have access to,
860     /// since we've loaded `my_proc_macro` from disk in order to execute it).
861     /// In this way, we have obtained a span pointing into `my_proc_macro`
862     fn save_span(&mut self, span: Self::Span) -> usize {
863         self.sess().save_proc_macro_span(span)
864     }
865     fn recover_proc_macro_span(&mut self, id: usize) -> Self::Span {
866         let (resolver, krate, def_site) = (&*self.ecx.resolver, self.krate, self.def_site);
867         *self.rebased_spans.entry(id).or_insert_with(|| {
868             // FIXME: `SyntaxContext` for spans from proc macro crates is lost during encoding,
869             // replace it with a def-site context until we are encoding it properly.
870             resolver.get_proc_macro_quoted_span(krate, id).with_ctxt(def_site.ctxt())
871         })
872     }
873 }