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