]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_expand/src/proc_macro_server.rs
merge rustc history
[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             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 Span = Span;
372     type Symbol = Symbol;
373 }
374
375 impl server::FreeFunctions for Rustc<'_, '_> {
376     fn track_env_var(&mut self, var: &str, value: Option<&str>) {
377         self.sess()
378             .env_depinfo
379             .borrow_mut()
380             .insert((Symbol::intern(var), value.map(Symbol::intern)));
381     }
382
383     fn track_path(&mut self, path: &str) {
384         self.sess().file_depinfo.borrow_mut().insert(Symbol::intern(path));
385     }
386
387     fn literal_from_str(&mut self, s: &str) -> Result<Literal<Self::Span, Self::Symbol>, ()> {
388         let name = FileName::proc_macro_source_code(s);
389         let mut parser = rustc_parse::new_parser_from_source_str(self.sess(), name, s.to_owned());
390
391         let first_span = parser.token.span.data();
392         let minus_present = parser.eat(&token::BinOp(token::Minus));
393
394         let lit_span = parser.token.span.data();
395         let token::Literal(mut lit) = parser.token.kind else {
396             return Err(());
397         };
398
399         // Check no comment or whitespace surrounding the (possibly negative)
400         // literal, or more tokens after it.
401         if (lit_span.hi.0 - first_span.lo.0) as usize != s.len() {
402             return Err(());
403         }
404
405         if minus_present {
406             // If minus is present, check no comment or whitespace in between it
407             // and the literal token.
408             if first_span.hi.0 != lit_span.lo.0 {
409                 return Err(());
410             }
411
412             // Check literal is a kind we allow to be negated in a proc macro token.
413             match lit.kind {
414                 token::LitKind::Bool
415                 | token::LitKind::Byte
416                 | token::LitKind::Char
417                 | token::LitKind::Str
418                 | token::LitKind::StrRaw(_)
419                 | token::LitKind::ByteStr
420                 | token::LitKind::ByteStrRaw(_)
421                 | token::LitKind::Err => return Err(()),
422                 token::LitKind::Integer | token::LitKind::Float => {}
423             }
424
425             // Synthesize a new symbol that includes the minus sign.
426             let symbol = Symbol::intern(&s[..1 + lit.symbol.as_str().len()]);
427             lit = token::Lit::new(lit.kind, symbol, lit.suffix);
428         }
429         let token::Lit { kind, symbol, suffix } = lit;
430         Ok(Literal {
431             kind: FromInternal::from_internal(kind),
432             symbol,
433             suffix,
434             span: self.call_site,
435         })
436     }
437
438     fn emit_diagnostic(&mut self, diagnostic: Diagnostic<Self::Span>) {
439         let mut diag =
440             rustc_errors::Diagnostic::new(diagnostic.level.to_internal(), diagnostic.message);
441         diag.set_span(MultiSpan::from_spans(diagnostic.spans));
442         for child in diagnostic.children {
443             diag.sub(
444                 child.level.to_internal(),
445                 child.message,
446                 MultiSpan::from_spans(child.spans),
447                 None,
448             );
449         }
450         self.sess().span_diagnostic.emit_diagnostic(&mut diag);
451     }
452 }
453
454 impl server::TokenStream for Rustc<'_, '_> {
455     fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
456         stream.is_empty()
457     }
458
459     fn from_str(&mut self, src: &str) -> Self::TokenStream {
460         parse_stream_from_source_str(
461             FileName::proc_macro_source_code(src),
462             src.to_string(),
463             self.sess(),
464             Some(self.call_site),
465         )
466     }
467
468     fn to_string(&mut self, stream: &Self::TokenStream) -> String {
469         pprust::tts_to_string(stream)
470     }
471
472     fn expand_expr(&mut self, stream: &Self::TokenStream) -> Result<Self::TokenStream, ()> {
473         // Parse the expression from our tokenstream.
474         let expr: PResult<'_, _> = try {
475             let mut p = rustc_parse::stream_to_parser(
476                 self.sess(),
477                 stream.clone(),
478                 Some("proc_macro expand expr"),
479             );
480             let expr = p.parse_expr()?;
481             if p.token != token::Eof {
482                 p.unexpected()?;
483             }
484             expr
485         };
486         let expr = expr.map_err(|mut err| {
487             err.emit();
488         })?;
489
490         // Perform eager expansion on the expression.
491         let expr = self
492             .ecx
493             .expander()
494             .fully_expand_fragment(crate::expand::AstFragment::Expr(expr))
495             .make_expr();
496
497         // NOTE: For now, limit `expand_expr` to exclusively expand to literals.
498         // This may be relaxed in the future.
499         // We don't use `TokenStream::from_ast` as the tokenstream currently cannot
500         // be recovered in the general case.
501         match &expr.kind {
502             ast::ExprKind::Lit(l) if l.token_lit.kind == token::Bool => {
503                 Ok(tokenstream::TokenStream::token_alone(
504                     token::Ident(l.token_lit.symbol, false),
505                     l.span,
506                 ))
507             }
508             ast::ExprKind::Lit(l) => {
509                 Ok(tokenstream::TokenStream::token_alone(token::Literal(l.token_lit), l.span))
510             }
511             ast::ExprKind::Unary(ast::UnOp::Neg, e) => match &e.kind {
512                 ast::ExprKind::Lit(l) => match l.token_lit {
513                     token::Lit { kind: token::Integer | token::Float, .. } => {
514                         Ok(Self::TokenStream::from_iter([
515                             // FIXME: The span of the `-` token is lost when
516                             // parsing, so we cannot faithfully recover it here.
517                             tokenstream::TokenTree::token_alone(token::BinOp(token::Minus), e.span),
518                             tokenstream::TokenTree::token_alone(
519                                 token::Literal(l.token_lit),
520                                 l.span,
521                             ),
522                         ]))
523                     }
524                     _ => Err(()),
525                 },
526                 _ => Err(()),
527             },
528             _ => Err(()),
529         }
530     }
531
532     fn from_token_tree(
533         &mut self,
534         tree: TokenTree<Self::TokenStream, Self::Span, Self::Symbol>,
535     ) -> Self::TokenStream {
536         (tree, &mut *self).to_internal()
537     }
538
539     fn concat_trees(
540         &mut self,
541         base: Option<Self::TokenStream>,
542         trees: Vec<TokenTree<Self::TokenStream, Self::Span, Self::Symbol>>,
543     ) -> Self::TokenStream {
544         let mut builder = tokenstream::TokenStreamBuilder::new();
545         if let Some(base) = base {
546             builder.push(base);
547         }
548         for tree in trees {
549             builder.push((tree, &mut *self).to_internal());
550         }
551         builder.build()
552     }
553
554     fn concat_streams(
555         &mut self,
556         base: Option<Self::TokenStream>,
557         streams: Vec<Self::TokenStream>,
558     ) -> Self::TokenStream {
559         let mut builder = tokenstream::TokenStreamBuilder::new();
560         if let Some(base) = base {
561             builder.push(base);
562         }
563         for stream in streams {
564             builder.push(stream);
565         }
566         builder.build()
567     }
568
569     fn into_trees(
570         &mut self,
571         stream: Self::TokenStream,
572     ) -> Vec<TokenTree<Self::TokenStream, Self::Span, Self::Symbol>> {
573         FromInternal::from_internal((stream, self))
574     }
575 }
576
577 impl server::SourceFile for Rustc<'_, '_> {
578     fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
579         Lrc::ptr_eq(file1, file2)
580     }
581
582     fn path(&mut self, file: &Self::SourceFile) -> String {
583         match file.name {
584             FileName::Real(ref name) => name
585                 .local_path()
586                 .expect("attempting to get a file path in an imported file in `proc_macro::SourceFile::path`")
587                 .to_str()
588                 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
589                 .to_string(),
590             _ => file.name.prefer_local().to_string(),
591         }
592     }
593
594     fn is_real(&mut self, file: &Self::SourceFile) -> bool {
595         file.is_real_file()
596     }
597 }
598
599 impl server::Span for Rustc<'_, '_> {
600     fn debug(&mut self, span: Self::Span) -> String {
601         if self.ecx.ecfg.span_debug {
602             format!("{:?}", span)
603         } else {
604             format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
605         }
606     }
607
608     fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
609         self.sess().source_map().lookup_char_pos(span.lo()).file
610     }
611
612     fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
613         span.parent_callsite()
614     }
615
616     fn source(&mut self, span: Self::Span) -> Self::Span {
617         span.source_callsite()
618     }
619
620     fn start(&mut self, span: Self::Span) -> LineColumn {
621         let loc = self.sess().source_map().lookup_char_pos(span.lo());
622         LineColumn { line: loc.line, column: loc.col.to_usize() }
623     }
624
625     fn end(&mut self, span: Self::Span) -> LineColumn {
626         let loc = self.sess().source_map().lookup_char_pos(span.hi());
627         LineColumn { line: loc.line, column: loc.col.to_usize() }
628     }
629
630     fn before(&mut self, span: Self::Span) -> Self::Span {
631         span.shrink_to_lo()
632     }
633
634     fn after(&mut self, span: Self::Span) -> Self::Span {
635         span.shrink_to_hi()
636     }
637
638     fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
639         let self_loc = self.sess().source_map().lookup_char_pos(first.lo());
640         let other_loc = self.sess().source_map().lookup_char_pos(second.lo());
641
642         if self_loc.file.name != other_loc.file.name {
643             return None;
644         }
645
646         Some(first.to(second))
647     }
648
649     fn subspan(
650         &mut self,
651         span: Self::Span,
652         start: Bound<usize>,
653         end: Bound<usize>,
654     ) -> Option<Self::Span> {
655         let length = span.hi().to_usize() - span.lo().to_usize();
656
657         let start = match start {
658             Bound::Included(lo) => lo,
659             Bound::Excluded(lo) => lo.checked_add(1)?,
660             Bound::Unbounded => 0,
661         };
662
663         let end = match end {
664             Bound::Included(hi) => hi.checked_add(1)?,
665             Bound::Excluded(hi) => hi,
666             Bound::Unbounded => length,
667         };
668
669         // Bounds check the values, preventing addition overflow and OOB spans.
670         if start > u32::MAX as usize
671             || end > u32::MAX as usize
672             || (u32::MAX - start as u32) < span.lo().to_u32()
673             || (u32::MAX - end as u32) < span.lo().to_u32()
674             || start >= end
675             || end > length
676         {
677             return None;
678         }
679
680         let new_lo = span.lo() + BytePos::from_usize(start);
681         let new_hi = span.lo() + BytePos::from_usize(end);
682         Some(span.with_lo(new_lo).with_hi(new_hi))
683     }
684
685     fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
686         span.with_ctxt(at.ctxt())
687     }
688
689     fn source_text(&mut self, span: Self::Span) -> Option<String> {
690         self.sess().source_map().span_to_snippet(span).ok()
691     }
692     /// Saves the provided span into the metadata of
693     /// *the crate we are currently compiling*, which must
694     /// be a proc-macro crate. This id can be passed to
695     /// `recover_proc_macro_span` when our current crate
696     /// is *run* as a proc-macro.
697     ///
698     /// Let's suppose that we have two crates - `my_client`
699     /// and `my_proc_macro`. The `my_proc_macro` crate
700     /// contains a procedural macro `my_macro`, which
701     /// is implemented as: `quote! { "hello" }`
702     ///
703     /// When we *compile* `my_proc_macro`, we will execute
704     /// the `quote` proc-macro. This will save the span of
705     /// "hello" into the metadata of `my_proc_macro`. As a result,
706     /// the body of `my_proc_macro` (after expansion) will end
707     /// up containing a call that looks like this:
708     /// `proc_macro::Ident::new("hello", proc_macro::Span::recover_proc_macro_span(0))`
709     ///
710     /// where `0` is the id returned by this function.
711     /// When `my_proc_macro` *executes* (during the compilation of `my_client`),
712     /// the call to `recover_proc_macro_span` will load the corresponding
713     /// span from the metadata of `my_proc_macro` (which we have access to,
714     /// since we've loaded `my_proc_macro` from disk in order to execute it).
715     /// In this way, we have obtained a span pointing into `my_proc_macro`
716     fn save_span(&mut self, span: Self::Span) -> usize {
717         self.sess().save_proc_macro_span(span)
718     }
719
720     fn recover_proc_macro_span(&mut self, id: usize) -> Self::Span {
721         let (resolver, krate, def_site) = (&*self.ecx.resolver, self.krate, self.def_site);
722         *self.rebased_spans.entry(id).or_insert_with(|| {
723             // FIXME: `SyntaxContext` for spans from proc macro crates is lost during encoding,
724             // replace it with a def-site context until we are encoding it properly.
725             resolver.get_proc_macro_quoted_span(krate, id).with_ctxt(def_site.ctxt())
726         })
727     }
728 }
729
730 impl server::Symbol for Rustc<'_, '_> {
731     fn normalize_and_validate_ident(&mut self, string: &str) -> Result<Self::Symbol, ()> {
732         let sym = nfc_normalize(string);
733         if rustc_lexer::is_ident(sym.as_str()) { Ok(sym) } else { Err(()) }
734     }
735 }
736
737 impl server::Server for Rustc<'_, '_> {
738     fn globals(&mut self) -> ExpnGlobals<Self::Span> {
739         ExpnGlobals {
740             def_site: self.def_site,
741             call_site: self.call_site,
742             mixed_site: self.mixed_site,
743         }
744     }
745
746     fn intern_symbol(string: &str) -> Self::Symbol {
747         Symbol::intern(string)
748     }
749
750     fn with_symbol_string(symbol: &Self::Symbol, f: impl FnOnce(&str)) {
751         f(&symbol.as_str())
752     }
753 }