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