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