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