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