]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_expand/src/proc_macro_server.rs
Rollup merge of #98881 - cjgillot:q-def-kind, r=fee1-dead
[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) => {
430                 Ok(tokenstream::TokenTree::token(token::Literal(l.token), l.span).into())
431             }
432             ast::ExprKind::Unary(ast::UnOp::Neg, e) => match &e.kind {
433                 ast::ExprKind::Lit(l) => match l.token {
434                     token::Lit { kind: token::Integer | token::Float, .. } => {
435                         Ok(Self::TokenStream::from_iter([
436                             // FIXME: The span of the `-` token is lost when
437                             // parsing, so we cannot faithfully recover it here.
438                             tokenstream::TokenTree::token(token::BinOp(token::Minus), e.span),
439                             tokenstream::TokenTree::token(token::Literal(l.token), l.span),
440                         ]))
441                     }
442                     _ => Err(()),
443                 },
444                 _ => Err(()),
445             },
446             _ => Err(()),
447         }
448     }
449
450     fn from_token_tree(
451         &mut self,
452         tree: TokenTree<Self::TokenStream, Self::Span, Self::Ident, Self::Literal>,
453     ) -> Self::TokenStream {
454         tree.to_internal()
455     }
456
457     fn concat_trees(
458         &mut self,
459         base: Option<Self::TokenStream>,
460         trees: Vec<TokenTree<Self::TokenStream, Self::Span, Self::Ident, Self::Literal>>,
461     ) -> Self::TokenStream {
462         let mut builder = tokenstream::TokenStreamBuilder::new();
463         if let Some(base) = base {
464             builder.push(base);
465         }
466         for tree in trees {
467             builder.push(tree.to_internal());
468         }
469         builder.build()
470     }
471
472     fn concat_streams(
473         &mut self,
474         base: Option<Self::TokenStream>,
475         streams: Vec<Self::TokenStream>,
476     ) -> Self::TokenStream {
477         let mut builder = tokenstream::TokenStreamBuilder::new();
478         if let Some(base) = base {
479             builder.push(base);
480         }
481         for stream in streams {
482             builder.push(stream);
483         }
484         builder.build()
485     }
486
487     fn into_trees(
488         &mut self,
489         stream: Self::TokenStream,
490     ) -> Vec<TokenTree<Self::TokenStream, Self::Span, Self::Ident, Self::Literal>> {
491         FromInternal::from_internal((stream, self))
492     }
493 }
494
495 impl server::Ident for Rustc<'_, '_> {
496     fn new(&mut self, string: &str, span: Self::Span, is_raw: bool) -> Self::Ident {
497         Ident::new(self.sess(), Symbol::intern(string), is_raw, span)
498     }
499
500     fn span(&mut self, ident: Self::Ident) -> Self::Span {
501         ident.span
502     }
503
504     fn with_span(&mut self, ident: Self::Ident, span: Self::Span) -> Self::Ident {
505         Ident { span, ..ident }
506     }
507 }
508
509 impl server::Literal for Rustc<'_, '_> {
510     fn from_str(&mut self, s: &str) -> Result<Self::Literal, ()> {
511         let name = FileName::proc_macro_source_code(s);
512         let mut parser = rustc_parse::new_parser_from_source_str(self.sess(), name, s.to_owned());
513
514         let first_span = parser.token.span.data();
515         let minus_present = parser.eat(&token::BinOp(token::Minus));
516
517         let lit_span = parser.token.span.data();
518         let token::Literal(mut lit) = parser.token.kind else {
519             return Err(());
520         };
521
522         // Check no comment or whitespace surrounding the (possibly negative)
523         // literal, or more tokens after it.
524         if (lit_span.hi.0 - first_span.lo.0) as usize != s.len() {
525             return Err(());
526         }
527
528         if minus_present {
529             // If minus is present, check no comment or whitespace in between it
530             // and the literal token.
531             if first_span.hi.0 != lit_span.lo.0 {
532                 return Err(());
533             }
534
535             // Check literal is a kind we allow to be negated in a proc macro token.
536             match lit.kind {
537                 token::LitKind::Bool
538                 | token::LitKind::Byte
539                 | token::LitKind::Char
540                 | token::LitKind::Str
541                 | token::LitKind::StrRaw(_)
542                 | token::LitKind::ByteStr
543                 | token::LitKind::ByteStrRaw(_)
544                 | token::LitKind::Err => return Err(()),
545                 token::LitKind::Integer | token::LitKind::Float => {}
546             }
547
548             // Synthesize a new symbol that includes the minus sign.
549             let symbol = Symbol::intern(&s[..1 + lit.symbol.as_str().len()]);
550             lit = token::Lit::new(lit.kind, symbol, lit.suffix);
551         }
552
553         Ok(Literal { lit, span: self.call_site })
554     }
555
556     fn to_string(&mut self, literal: &Self::Literal) -> String {
557         literal.lit.to_string()
558     }
559
560     fn debug_kind(&mut self, literal: &Self::Literal) -> String {
561         format!("{:?}", literal.lit.kind)
562     }
563
564     fn symbol(&mut self, literal: &Self::Literal) -> String {
565         literal.lit.symbol.to_string()
566     }
567
568     fn suffix(&mut self, literal: &Self::Literal) -> Option<String> {
569         literal.lit.suffix.as_ref().map(Symbol::to_string)
570     }
571
572     fn integer(&mut self, n: &str) -> Self::Literal {
573         self.lit(token::Integer, Symbol::intern(n), None)
574     }
575
576     fn typed_integer(&mut self, n: &str, kind: &str) -> Self::Literal {
577         self.lit(token::Integer, Symbol::intern(n), Some(Symbol::intern(kind)))
578     }
579
580     fn float(&mut self, n: &str) -> Self::Literal {
581         self.lit(token::Float, Symbol::intern(n), None)
582     }
583
584     fn f32(&mut self, n: &str) -> Self::Literal {
585         self.lit(token::Float, Symbol::intern(n), Some(sym::f32))
586     }
587
588     fn f64(&mut self, n: &str) -> Self::Literal {
589         self.lit(token::Float, Symbol::intern(n), Some(sym::f64))
590     }
591
592     fn string(&mut self, string: &str) -> Self::Literal {
593         let quoted = format!("{:?}", string);
594         assert!(quoted.starts_with('"') && quoted.ends_with('"'));
595         let symbol = &quoted[1..quoted.len() - 1];
596         self.lit(token::Str, Symbol::intern(symbol), None)
597     }
598
599     fn character(&mut self, ch: char) -> Self::Literal {
600         let quoted = format!("{:?}", ch);
601         assert!(quoted.starts_with('\'') && quoted.ends_with('\''));
602         let symbol = &quoted[1..quoted.len() - 1];
603         self.lit(token::Char, Symbol::intern(symbol), None)
604     }
605
606     fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
607         let string = bytes
608             .iter()
609             .cloned()
610             .flat_map(ascii::escape_default)
611             .map(Into::<char>::into)
612             .collect::<String>();
613         self.lit(token::ByteStr, Symbol::intern(&string), None)
614     }
615
616     fn span(&mut self, literal: &Self::Literal) -> Self::Span {
617         literal.span
618     }
619
620     fn set_span(&mut self, literal: &mut Self::Literal, span: Self::Span) {
621         literal.span = span;
622     }
623
624     fn subspan(
625         &mut self,
626         literal: &Self::Literal,
627         start: Bound<usize>,
628         end: Bound<usize>,
629     ) -> Option<Self::Span> {
630         let span = literal.span;
631         let length = span.hi().to_usize() - span.lo().to_usize();
632
633         let start = match start {
634             Bound::Included(lo) => lo,
635             Bound::Excluded(lo) => lo.checked_add(1)?,
636             Bound::Unbounded => 0,
637         };
638
639         let end = match end {
640             Bound::Included(hi) => hi.checked_add(1)?,
641             Bound::Excluded(hi) => hi,
642             Bound::Unbounded => length,
643         };
644
645         // Bounds check the values, preventing addition overflow and OOB spans.
646         if start > u32::MAX as usize
647             || end > u32::MAX as usize
648             || (u32::MAX - start as u32) < span.lo().to_u32()
649             || (u32::MAX - end as u32) < span.lo().to_u32()
650             || start >= end
651             || end > length
652         {
653             return None;
654         }
655
656         let new_lo = span.lo() + BytePos::from_usize(start);
657         let new_hi = span.lo() + BytePos::from_usize(end);
658         Some(span.with_lo(new_lo).with_hi(new_hi))
659     }
660 }
661
662 impl server::SourceFile for Rustc<'_, '_> {
663     fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
664         Lrc::ptr_eq(file1, file2)
665     }
666
667     fn path(&mut self, file: &Self::SourceFile) -> String {
668         match file.name {
669             FileName::Real(ref name) => name
670                 .local_path()
671                 .expect("attempting to get a file path in an imported file in `proc_macro::SourceFile::path`")
672                 .to_str()
673                 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
674                 .to_string(),
675             _ => file.name.prefer_local().to_string(),
676         }
677     }
678
679     fn is_real(&mut self, file: &Self::SourceFile) -> bool {
680         file.is_real_file()
681     }
682 }
683
684 impl server::MultiSpan for Rustc<'_, '_> {
685     fn new(&mut self) -> Self::MultiSpan {
686         vec![]
687     }
688
689     fn push(&mut self, spans: &mut Self::MultiSpan, span: Self::Span) {
690         spans.push(span)
691     }
692 }
693
694 impl server::Diagnostic for Rustc<'_, '_> {
695     fn new(&mut self, level: Level, msg: &str, spans: Self::MultiSpan) -> Self::Diagnostic {
696         let mut diag = Diagnostic::new(level.to_internal(), msg);
697         diag.set_span(MultiSpan::from_spans(spans));
698         diag
699     }
700
701     fn sub(
702         &mut self,
703         diag: &mut Self::Diagnostic,
704         level: Level,
705         msg: &str,
706         spans: Self::MultiSpan,
707     ) {
708         diag.sub(level.to_internal(), msg, MultiSpan::from_spans(spans), None);
709     }
710
711     fn emit(&mut self, mut diag: Self::Diagnostic) {
712         self.sess().span_diagnostic.emit_diagnostic(&mut diag);
713     }
714 }
715
716 impl server::Span for Rustc<'_, '_> {
717     fn debug(&mut self, span: Self::Span) -> String {
718         if self.ecx.ecfg.span_debug {
719             format!("{:?}", span)
720         } else {
721             format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
722         }
723     }
724
725     fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
726         self.sess().source_map().lookup_char_pos(span.lo()).file
727     }
728
729     fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
730         span.parent_callsite()
731     }
732
733     fn source(&mut self, span: Self::Span) -> Self::Span {
734         span.source_callsite()
735     }
736
737     fn start(&mut self, span: Self::Span) -> LineColumn {
738         let loc = self.sess().source_map().lookup_char_pos(span.lo());
739         LineColumn { line: loc.line, column: loc.col.to_usize() }
740     }
741
742     fn end(&mut self, span: Self::Span) -> LineColumn {
743         let loc = self.sess().source_map().lookup_char_pos(span.hi());
744         LineColumn { line: loc.line, column: loc.col.to_usize() }
745     }
746
747     fn before(&mut self, span: Self::Span) -> Self::Span {
748         span.shrink_to_lo()
749     }
750
751     fn after(&mut self, span: Self::Span) -> Self::Span {
752         span.shrink_to_hi()
753     }
754
755     fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
756         let self_loc = self.sess().source_map().lookup_char_pos(first.lo());
757         let other_loc = self.sess().source_map().lookup_char_pos(second.lo());
758
759         if self_loc.file.name != other_loc.file.name {
760             return None;
761         }
762
763         Some(first.to(second))
764     }
765
766     fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
767         span.with_ctxt(at.ctxt())
768     }
769
770     fn source_text(&mut self, span: Self::Span) -> Option<String> {
771         self.sess().source_map().span_to_snippet(span).ok()
772     }
773     /// Saves the provided span into the metadata of
774     /// *the crate we are currently compiling*, which must
775     /// be a proc-macro crate. This id can be passed to
776     /// `recover_proc_macro_span` when our current crate
777     /// is *run* as a proc-macro.
778     ///
779     /// Let's suppose that we have two crates - `my_client`
780     /// and `my_proc_macro`. The `my_proc_macro` crate
781     /// contains a procedural macro `my_macro`, which
782     /// is implemented as: `quote! { "hello" }`
783     ///
784     /// When we *compile* `my_proc_macro`, we will execute
785     /// the `quote` proc-macro. This will save the span of
786     /// "hello" into the metadata of `my_proc_macro`. As a result,
787     /// the body of `my_proc_macro` (after expansion) will end
788     /// up containing a call that looks like this:
789     /// `proc_macro::Ident::new("hello", proc_macro::Span::recover_proc_macro_span(0))`
790     ///
791     /// where `0` is the id returned by this function.
792     /// When `my_proc_macro` *executes* (during the compilation of `my_client`),
793     /// the call to `recover_proc_macro_span` will load the corresponding
794     /// span from the metadata of `my_proc_macro` (which we have access to,
795     /// since we've loaded `my_proc_macro` from disk in order to execute it).
796     /// In this way, we have obtained a span pointing into `my_proc_macro`
797     fn save_span(&mut self, span: Self::Span) -> usize {
798         self.sess().save_proc_macro_span(span)
799     }
800
801     fn recover_proc_macro_span(&mut self, id: usize) -> Self::Span {
802         let (resolver, krate, def_site) = (&*self.ecx.resolver, self.krate, self.def_site);
803         *self.rebased_spans.entry(id).or_insert_with(|| {
804             // FIXME: `SyntaxContext` for spans from proc macro crates is lost during encoding,
805             // replace it with a def-site context until we are encoding it properly.
806             resolver.get_proc_macro_quoted_span(krate, id).with_ctxt(def_site.ctxt())
807         })
808     }
809 }
810
811 impl server::Server for Rustc<'_, '_> {
812     fn globals(&mut self) -> ExpnGlobals<Self::Span> {
813         ExpnGlobals {
814             def_site: self.def_site,
815             call_site: self.call_site,
816             mixed_site: self.mixed_site,
817         }
818     }
819 }