]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/proc_macro_server.rs
Rollup merge of #63055 - Mark-Simulacrum:save-analysis-clean-2, r=Xanewok
[rust.git] / src / libsyntax / ext / proc_macro_server.rs
1 use crate::ast;
2 use crate::ext::base::ExtCtxt;
3 use crate::parse::{self, token, ParseSess};
4 use crate::parse::lexer::comments;
5 use crate::tokenstream::{self, DelimSpan, IsJoint::*, TokenStream, TreeAndJoint};
6
7 use errors::{Diagnostic, DiagnosticBuilder};
8 use rustc_data_structures::sync::Lrc;
9 use syntax_pos::{BytePos, FileName, MultiSpan, Pos, SourceFile, Span};
10 use syntax_pos::hygiene::{SyntaxContext, Transparency};
11 use syntax_pos::symbol::{kw, sym, Symbol};
12
13 use proc_macro::{Delimiter, Level, LineColumn, Spacing};
14 use proc_macro::bridge::{server, TokenTree};
15 use std::{ascii, panic};
16 use std::ops::Bound;
17
18 trait FromInternal<T> {
19     fn from_internal(x: T) -> Self;
20 }
21
22 trait ToInternal<T> {
23     fn to_internal(self) -> T;
24 }
25
26 impl FromInternal<token::DelimToken> for Delimiter {
27     fn from_internal(delim: token::DelimToken) -> Delimiter {
28         match delim {
29             token::Paren => Delimiter::Parenthesis,
30             token::Brace => Delimiter::Brace,
31             token::Bracket => Delimiter::Bracket,
32             token::NoDelim => Delimiter::None,
33         }
34     }
35 }
36
37 impl ToInternal<token::DelimToken> for Delimiter {
38     fn to_internal(self) -> token::DelimToken {
39         match self {
40             Delimiter::Parenthesis => token::Paren,
41             Delimiter::Brace => token::Brace,
42             Delimiter::Bracket => token::Bracket,
43             Delimiter::None => token::NoDelim,
44         }
45     }
46 }
47
48 impl FromInternal<(TreeAndJoint, &'_ ParseSess, &'_ mut Vec<Self>)>
49     for TokenTree<Group, Punct, Ident, Literal>
50 {
51     fn from_internal(((tree, is_joint), sess, stack): (TreeAndJoint, &ParseSess, &mut Vec<Self>))
52                     -> Self {
53         use crate::parse::token::*;
54
55         let joint = is_joint == Joint;
56         let Token { kind, span } = match tree {
57             tokenstream::TokenTree::Delimited(span, delim, tts) => {
58                 let delimiter = Delimiter::from_internal(delim);
59                 return TokenTree::Group(Group {
60                     delimiter,
61                     stream: tts.into(),
62                     span,
63                 });
64             }
65             tokenstream::TokenTree::Token(token) => token,
66         };
67
68         macro_rules! tt {
69             ($ty:ident { $($field:ident $(: $value:expr)*),+ $(,)? }) => (
70                 TokenTree::$ty(self::$ty {
71                     $($field $(: $value)*,)+
72                     span,
73                 })
74             );
75             ($ty:ident::$method:ident($($value:expr),*)) => (
76                 TokenTree::$ty(self::$ty::$method($($value,)* span))
77             );
78         }
79         macro_rules! op {
80             ($a:expr) => {
81                 tt!(Punct::new($a, joint))
82             };
83             ($a:expr, $b:expr) => {{
84                 stack.push(tt!(Punct::new($b, joint)));
85                 tt!(Punct::new($a, true))
86             }};
87             ($a:expr, $b:expr, $c:expr) => {{
88                 stack.push(tt!(Punct::new($c, joint)));
89                 stack.push(tt!(Punct::new($b, true)));
90                 tt!(Punct::new($a, true))
91             }};
92         }
93
94         match kind {
95             Eq => op!('='),
96             Lt => op!('<'),
97             Le => op!('<', '='),
98             EqEq => op!('=', '='),
99             Ne => op!('!', '='),
100             Ge => op!('>', '='),
101             Gt => op!('>'),
102             AndAnd => op!('&', '&'),
103             OrOr => op!('|', '|'),
104             Not => op!('!'),
105             Tilde => op!('~'),
106             BinOp(Plus) => op!('+'),
107             BinOp(Minus) => op!('-'),
108             BinOp(Star) => op!('*'),
109             BinOp(Slash) => op!('/'),
110             BinOp(Percent) => op!('%'),
111             BinOp(Caret) => op!('^'),
112             BinOp(And) => op!('&'),
113             BinOp(Or) => op!('|'),
114             BinOp(Shl) => op!('<', '<'),
115             BinOp(Shr) => op!('>', '>'),
116             BinOpEq(Plus) => op!('+', '='),
117             BinOpEq(Minus) => op!('-', '='),
118             BinOpEq(Star) => op!('*', '='),
119             BinOpEq(Slash) => op!('/', '='),
120             BinOpEq(Percent) => op!('%', '='),
121             BinOpEq(Caret) => op!('^', '='),
122             BinOpEq(And) => op!('&', '='),
123             BinOpEq(Or) => op!('|', '='),
124             BinOpEq(Shl) => op!('<', '<', '='),
125             BinOpEq(Shr) => op!('>', '>', '='),
126             At => op!('@'),
127             Dot => op!('.'),
128             DotDot => op!('.', '.'),
129             DotDotDot => op!('.', '.', '.'),
130             DotDotEq => op!('.', '.', '='),
131             Comma => op!(','),
132             Semi => op!(';'),
133             Colon => op!(':'),
134             ModSep => op!(':', ':'),
135             RArrow => op!('-', '>'),
136             LArrow => op!('<', '-'),
137             FatArrow => op!('=', '>'),
138             Pound => op!('#'),
139             Dollar => op!('$'),
140             Question => op!('?'),
141             SingleQuote => op!('\''),
142
143             Ident(name, false) if name == kw::DollarCrate => tt!(Ident::dollar_crate()),
144             Ident(name, is_raw) => tt!(Ident::new(name, is_raw)),
145             Lifetime(name) => {
146                 let ident = ast::Ident::new(name, span).without_first_quote();
147                 stack.push(tt!(Ident::new(ident.name, false)));
148                 tt!(Punct::new('\'', true))
149             }
150             Literal(lit) => tt!(Literal { lit }),
151             DocComment(c) => {
152                 let style = comments::doc_comment_style(&c.as_str());
153                 let stripped = comments::strip_doc_comment_decoration(&c.as_str());
154                 let mut escaped = String::new();
155                 for ch in stripped.chars() {
156                     escaped.extend(ch.escape_debug());
157                 }
158                 let stream = vec![
159                     Ident(sym::doc, false),
160                     Eq,
161                     TokenKind::lit(token::Str, Symbol::intern(&escaped), None),
162                 ]
163                 .into_iter()
164                 .map(|kind| tokenstream::TokenTree::token(kind, span))
165                 .collect();
166                 stack.push(TokenTree::Group(Group {
167                     delimiter: Delimiter::Bracket,
168                     stream,
169                     span: DelimSpan::from_single(span),
170                 }));
171                 if style == ast::AttrStyle::Inner {
172                     stack.push(tt!(Punct::new('!', false)));
173                 }
174                 tt!(Punct::new('#', false))
175             }
176
177             Interpolated(nt) => {
178                 let stream = nt.to_tokenstream(sess, span);
179                 TokenTree::Group(Group {
180                     delimiter: Delimiter::None,
181                     stream,
182                     span: DelimSpan::from_single(span),
183                 })
184             }
185
186             OpenDelim(..) | CloseDelim(..) => unreachable!(),
187             Whitespace | Comment | Shebang(..) | Eof => unreachable!(),
188         }
189     }
190 }
191
192 impl ToInternal<TokenStream> for TokenTree<Group, Punct, Ident, Literal> {
193     fn to_internal(self) -> TokenStream {
194         use crate::parse::token::*;
195
196         let (ch, joint, span) = match self {
197             TokenTree::Punct(Punct { ch, joint, span }) => (ch, joint, span),
198             TokenTree::Group(Group {
199                 delimiter,
200                 stream,
201                 span,
202             }) => {
203                 return tokenstream::TokenTree::Delimited(
204                     span,
205                     delimiter.to_internal(),
206                     stream.into(),
207                 )
208                 .into();
209             }
210             TokenTree::Ident(self::Ident { sym, is_raw, span }) => {
211                 return tokenstream::TokenTree::token(Ident(sym, is_raw), span).into();
212             }
213             TokenTree::Literal(self::Literal {
214                 lit: token::Lit { kind: token::Integer, symbol, suffix },
215                 span,
216             }) if symbol.as_str().starts_with("-") => {
217                 let minus = BinOp(BinOpToken::Minus);
218                 let symbol = Symbol::intern(&symbol.as_str()[1..]);
219                 let integer = TokenKind::lit(token::Integer, symbol, suffix);
220                 let a = tokenstream::TokenTree::token(minus, span);
221                 let b = tokenstream::TokenTree::token(integer, span);
222                 return vec![a, b].into_iter().collect();
223             }
224             TokenTree::Literal(self::Literal {
225                 lit: token::Lit { kind: token::Float, symbol, suffix },
226                 span,
227             }) if symbol.as_str().starts_with("-") => {
228                 let minus = BinOp(BinOpToken::Minus);
229                 let symbol = Symbol::intern(&symbol.as_str()[1..]);
230                 let float = TokenKind::lit(token::Float, symbol, suffix);
231                 let a = tokenstream::TokenTree::token(minus, span);
232                 let b = tokenstream::TokenTree::token(float, span);
233                 return vec![a, b].into_iter().collect();
234             }
235             TokenTree::Literal(self::Literal { lit, span }) => {
236                 return tokenstream::TokenTree::token(Literal(lit), span).into()
237             }
238         };
239
240         let kind = match ch {
241             '=' => Eq,
242             '<' => Lt,
243             '>' => Gt,
244             '!' => Not,
245             '~' => Tilde,
246             '+' => BinOp(Plus),
247             '-' => BinOp(Minus),
248             '*' => BinOp(Star),
249             '/' => BinOp(Slash),
250             '%' => BinOp(Percent),
251             '^' => BinOp(Caret),
252             '&' => BinOp(And),
253             '|' => BinOp(Or),
254             '@' => At,
255             '.' => Dot,
256             ',' => Comma,
257             ';' => Semi,
258             ':' => Colon,
259             '#' => Pound,
260             '$' => Dollar,
261             '?' => Question,
262             '\'' => SingleQuote,
263             _ => unreachable!(),
264         };
265
266         let tree = tokenstream::TokenTree::token(kind, span);
267         TokenStream::new(vec![(tree, if joint { Joint } else { NonJoint })])
268     }
269 }
270
271 impl ToInternal<errors::Level> for Level {
272     fn to_internal(self) -> errors::Level {
273         match self {
274             Level::Error => errors::Level::Error,
275             Level::Warning => errors::Level::Warning,
276             Level::Note => errors::Level::Note,
277             Level::Help => errors::Level::Help,
278             _ => unreachable!("unknown proc_macro::Level variant: {:?}", self),
279         }
280     }
281 }
282
283 #[derive(Clone)]
284 pub struct TokenStreamIter {
285     cursor: tokenstream::Cursor,
286     stack: Vec<TokenTree<Group, Punct, Ident, Literal>>,
287 }
288
289 #[derive(Clone)]
290 pub struct Group {
291     delimiter: Delimiter,
292     stream: TokenStream,
293     span: DelimSpan,
294 }
295
296 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
297 pub struct Punct {
298     ch: char,
299     // NB. not using `Spacing` here because it doesn't implement `Hash`.
300     joint: bool,
301     span: Span,
302 }
303
304 impl Punct {
305     fn new(ch: char, joint: bool, span: Span) -> Punct {
306         const LEGAL_CHARS: &[char] = &['=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^',
307                                        '&', '|', '@', '.', ',', ';', ':', '#', '$', '?', '\''];
308         if !LEGAL_CHARS.contains(&ch) {
309             panic!("unsupported character `{:?}`", ch)
310         }
311         Punct { ch, joint, span }
312     }
313 }
314
315 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
316 pub struct Ident {
317     sym: Symbol,
318     is_raw: bool,
319     span: Span,
320 }
321
322 impl Ident {
323     fn is_valid(string: &str) -> bool {
324         let mut chars = string.chars();
325         if let Some(start) = chars.next() {
326             (start == '_' || start.is_xid_start())
327                 && chars.all(|cont| cont == '_' || cont.is_xid_continue())
328         } else {
329             false
330         }
331     }
332     fn new(sym: Symbol, is_raw: bool, span: Span) -> Ident {
333         let string = sym.as_str();
334         if !Self::is_valid(&string) {
335             panic!("`{:?}` is not a valid identifier", string)
336         }
337         // Get rid of gensyms to conservatively check rawness on the string contents only.
338         if is_raw && !sym.as_interned_str().as_symbol().can_be_raw() {
339             panic!("`{}` cannot be a raw identifier", string);
340         }
341         Ident { sym, is_raw, span }
342     }
343     fn dollar_crate(span: Span) -> Ident {
344         // `$crate` is accepted as an ident only if it comes from the compiler.
345         Ident { sym: kw::DollarCrate, is_raw: false, span }
346     }
347 }
348
349 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
350 #[derive(Clone, Debug)]
351 pub struct Literal {
352     lit: token::Lit,
353     span: Span,
354 }
355
356 pub(crate) struct Rustc<'a> {
357     sess: &'a ParseSess,
358     def_site: Span,
359     call_site: Span,
360 }
361
362 impl<'a> Rustc<'a> {
363     pub fn new(cx: &'a ExtCtxt<'_>) -> Self {
364         // No way to determine def location for a proc macro right now, so use call location.
365         let location = cx.current_expansion.id.expn_info().unwrap().call_site;
366         let to_span = |transparency| {
367             location.with_ctxt(
368                 SyntaxContext::empty()
369                     .apply_mark_with_transparency(cx.current_expansion.id, transparency),
370             )
371         };
372         Rustc {
373             sess: cx.parse_sess,
374             def_site: to_span(Transparency::Opaque),
375             call_site: to_span(Transparency::Transparent),
376         }
377     }
378
379     fn lit(&mut self, kind: token::LitKind, symbol: Symbol, suffix: Option<Symbol>) -> Literal {
380         Literal {
381             lit: token::Lit::new(kind, symbol, suffix),
382             span: server::Span::call_site(self),
383         }
384     }
385 }
386
387 impl server::Types for Rustc<'_> {
388     type TokenStream = TokenStream;
389     type TokenStreamBuilder = tokenstream::TokenStreamBuilder;
390     type TokenStreamIter = TokenStreamIter;
391     type Group = Group;
392     type Punct = Punct;
393     type Ident = Ident;
394     type Literal = Literal;
395     type SourceFile = Lrc<SourceFile>;
396     type MultiSpan = Vec<Span>;
397     type Diagnostic = Diagnostic;
398     type Span = Span;
399 }
400
401 impl server::TokenStream for Rustc<'_> {
402     fn new(&mut self) -> Self::TokenStream {
403         TokenStream::empty()
404     }
405     fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
406         stream.is_empty()
407     }
408     fn from_str(&mut self, src: &str) -> Self::TokenStream {
409         parse::parse_stream_from_source_str(
410             FileName::proc_macro_source_code(src),
411             src.to_string(),
412             self.sess,
413             Some(self.call_site),
414         )
415     }
416     fn to_string(&mut self, stream: &Self::TokenStream) -> String {
417         stream.to_string()
418     }
419     fn from_token_tree(
420         &mut self,
421         tree: TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>,
422     ) -> Self::TokenStream {
423         tree.to_internal()
424     }
425     fn into_iter(&mut self, stream: Self::TokenStream) -> Self::TokenStreamIter {
426         TokenStreamIter {
427             cursor: stream.trees(),
428             stack: vec![],
429         }
430     }
431 }
432
433 impl server::TokenStreamBuilder for Rustc<'_> {
434     fn new(&mut self) -> Self::TokenStreamBuilder {
435         tokenstream::TokenStreamBuilder::new()
436     }
437     fn push(&mut self, builder: &mut Self::TokenStreamBuilder, stream: Self::TokenStream) {
438         builder.push(stream);
439     }
440     fn build(&mut self, builder: Self::TokenStreamBuilder) -> Self::TokenStream {
441         builder.build()
442     }
443 }
444
445 impl server::TokenStreamIter for Rustc<'_> {
446     fn next(
447         &mut self,
448         iter: &mut Self::TokenStreamIter,
449     ) -> Option<TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>> {
450         loop {
451             let tree = iter.stack.pop().or_else(|| {
452                 let next = iter.cursor.next_with_joint()?;
453                 Some(TokenTree::from_internal((next, self.sess, &mut iter.stack)))
454             })?;
455             // HACK: The condition "dummy span + group with empty delimiter" represents an AST
456             // fragment approximately converted into a token stream. This may happen, for
457             // example, with inputs to proc macro attributes, including derives. Such "groups"
458             // need to flattened during iteration over stream's token trees.
459             // Eventually this needs to be removed in favor of keeping original token trees
460             // and not doing the roundtrip through AST.
461             if let TokenTree::Group(ref group) = tree {
462                 if group.delimiter == Delimiter::None && group.span.entire().is_dummy() {
463                     iter.cursor.append(group.stream.clone());
464                     continue;
465                 }
466             }
467             return Some(tree);
468         }
469     }
470 }
471
472 impl server::Group for Rustc<'_> {
473     fn new(&mut self, delimiter: Delimiter, stream: Self::TokenStream) -> Self::Group {
474         Group {
475             delimiter,
476             stream,
477             span: DelimSpan::from_single(server::Span::call_site(self)),
478         }
479     }
480     fn delimiter(&mut self, group: &Self::Group) -> Delimiter {
481         group.delimiter
482     }
483     fn stream(&mut self, group: &Self::Group) -> Self::TokenStream {
484         group.stream.clone()
485     }
486     fn span(&mut self, group: &Self::Group) -> Self::Span {
487         group.span.entire()
488     }
489     fn span_open(&mut self, group: &Self::Group) -> Self::Span {
490         group.span.open
491     }
492     fn span_close(&mut self, group: &Self::Group) -> Self::Span {
493         group.span.close
494     }
495     fn set_span(&mut self, group: &mut Self::Group, span: Self::Span) {
496         group.span = DelimSpan::from_single(span);
497     }
498 }
499
500 impl server::Punct for Rustc<'_> {
501     fn new(&mut self, ch: char, spacing: Spacing) -> Self::Punct {
502         Punct::new(ch, spacing == Spacing::Joint, server::Span::call_site(self))
503     }
504     fn as_char(&mut self, punct: Self::Punct) -> char {
505         punct.ch
506     }
507     fn spacing(&mut self, punct: Self::Punct) -> Spacing {
508         if punct.joint {
509             Spacing::Joint
510         } else {
511             Spacing::Alone
512         }
513     }
514     fn span(&mut self, punct: Self::Punct) -> Self::Span {
515         punct.span
516     }
517     fn with_span(&mut self, punct: Self::Punct, span: Self::Span) -> Self::Punct {
518         Punct { span, ..punct }
519     }
520 }
521
522 impl server::Ident for Rustc<'_> {
523     fn new(&mut self, string: &str, span: Self::Span, is_raw: bool) -> Self::Ident {
524         Ident::new(Symbol::intern(string), is_raw, span)
525     }
526     fn span(&mut self, ident: Self::Ident) -> Self::Span {
527         ident.span
528     }
529     fn with_span(&mut self, ident: Self::Ident, span: Self::Span) -> Self::Ident {
530         Ident { span, ..ident }
531     }
532 }
533
534 impl server::Literal for Rustc<'_> {
535     // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
536     fn debug(&mut self, literal: &Self::Literal) -> String {
537         format!("{:?}", literal)
538     }
539     fn integer(&mut self, n: &str) -> Self::Literal {
540         self.lit(token::Integer, Symbol::intern(n), None)
541     }
542     fn typed_integer(&mut self, n: &str, kind: &str) -> Self::Literal {
543         self.lit(token::Integer, Symbol::intern(n), Some(Symbol::intern(kind)))
544     }
545     fn float(&mut self, n: &str) -> Self::Literal {
546         self.lit(token::Float, Symbol::intern(n), None)
547     }
548     fn f32(&mut self, n: &str) -> Self::Literal {
549         self.lit(token::Float, Symbol::intern(n), Some(sym::f32))
550     }
551     fn f64(&mut self, n: &str) -> Self::Literal {
552         self.lit(token::Float, Symbol::intern(n), Some(sym::f64))
553     }
554     fn string(&mut self, string: &str) -> Self::Literal {
555         let mut escaped = String::new();
556         for ch in string.chars() {
557             escaped.extend(ch.escape_debug());
558         }
559         self.lit(token::Str, Symbol::intern(&escaped), None)
560     }
561     fn character(&mut self, ch: char) -> Self::Literal {
562         let mut escaped = String::new();
563         escaped.extend(ch.escape_unicode());
564         self.lit(token::Char, Symbol::intern(&escaped), None)
565     }
566     fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
567         let string = bytes
568             .iter()
569             .cloned()
570             .flat_map(ascii::escape_default)
571             .map(Into::<char>::into)
572             .collect::<String>();
573         self.lit(token::ByteStr, Symbol::intern(&string), None)
574     }
575     fn span(&mut self, literal: &Self::Literal) -> Self::Span {
576         literal.span
577     }
578     fn set_span(&mut self, literal: &mut Self::Literal, span: Self::Span) {
579         literal.span = span;
580     }
581     fn subspan(
582         &mut self,
583         literal: &Self::Literal,
584         start: Bound<usize>,
585         end: Bound<usize>,
586     ) -> Option<Self::Span> {
587         let span = literal.span;
588         let length = span.hi().to_usize() - span.lo().to_usize();
589
590         let start = match start {
591             Bound::Included(lo) => lo,
592             Bound::Excluded(lo) => lo + 1,
593             Bound::Unbounded => 0,
594         };
595
596         let end = match end {
597             Bound::Included(hi) => hi + 1,
598             Bound::Excluded(hi) => hi,
599             Bound::Unbounded => length,
600         };
601
602         // Bounds check the values, preventing addition overflow and OOB spans.
603         if start > u32::max_value() as usize
604             || end > u32::max_value() as usize
605             || (u32::max_value() - start as u32) < span.lo().to_u32()
606             || (u32::max_value() - end as u32) < span.lo().to_u32()
607             || start >= end
608             || end > length
609         {
610             return None;
611         }
612
613         let new_lo = span.lo() + BytePos::from_usize(start);
614         let new_hi = span.lo() + BytePos::from_usize(end);
615         Some(span.with_lo(new_lo).with_hi(new_hi))
616     }
617 }
618
619 impl server::SourceFile for Rustc<'_> {
620     fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
621         Lrc::ptr_eq(file1, file2)
622     }
623     fn path(&mut self, file: &Self::SourceFile) -> String {
624         match file.name {
625             FileName::Real(ref path) => path
626                 .to_str()
627                 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
628                 .to_string(),
629             _ => file.name.to_string(),
630         }
631     }
632     fn is_real(&mut self, file: &Self::SourceFile) -> bool {
633         file.is_real_file()
634     }
635 }
636
637 impl server::MultiSpan for Rustc<'_> {
638     fn new(&mut self) -> Self::MultiSpan {
639         vec![]
640     }
641     fn push(&mut self, spans: &mut Self::MultiSpan, span: Self::Span) {
642         spans.push(span)
643     }
644 }
645
646 impl server::Diagnostic for Rustc<'_> {
647     fn new(&mut self, level: Level, msg: &str, spans: Self::MultiSpan) -> Self::Diagnostic {
648         let mut diag = Diagnostic::new(level.to_internal(), msg);
649         diag.set_span(MultiSpan::from_spans(spans));
650         diag
651     }
652     fn sub(
653         &mut self,
654         diag: &mut Self::Diagnostic,
655         level: Level,
656         msg: &str,
657         spans: Self::MultiSpan,
658     ) {
659         diag.sub(level.to_internal(), msg, MultiSpan::from_spans(spans), None);
660     }
661     fn emit(&mut self, diag: Self::Diagnostic) {
662         DiagnosticBuilder::new_diagnostic(&self.sess.span_diagnostic, diag).emit()
663     }
664 }
665
666 impl server::Span for Rustc<'_> {
667     fn debug(&mut self, span: Self::Span) -> String {
668         format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
669     }
670     fn def_site(&mut self) -> Self::Span {
671         self.def_site
672     }
673     fn call_site(&mut self) -> Self::Span {
674         self.call_site
675     }
676     fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
677         self.sess.source_map().lookup_char_pos(span.lo()).file
678     }
679     fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
680         span.ctxt().outer_expn_info().map(|i| i.call_site)
681     }
682     fn source(&mut self, span: Self::Span) -> Self::Span {
683         span.source_callsite()
684     }
685     fn start(&mut self, span: Self::Span) -> LineColumn {
686         let loc = self.sess.source_map().lookup_char_pos(span.lo());
687         LineColumn {
688             line: loc.line,
689             column: loc.col.to_usize(),
690         }
691     }
692     fn end(&mut self, span: Self::Span) -> LineColumn {
693         let loc = self.sess.source_map().lookup_char_pos(span.hi());
694         LineColumn {
695             line: loc.line,
696             column: loc.col.to_usize(),
697         }
698     }
699     fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
700         let self_loc = self.sess.source_map().lookup_char_pos(first.lo());
701         let other_loc = self.sess.source_map().lookup_char_pos(second.lo());
702
703         if self_loc.file.name != other_loc.file.name {
704             return None;
705         }
706
707         Some(first.to(second))
708     }
709     fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
710         span.with_ctxt(at.ctxt())
711     }
712     fn source_text(&mut self,  span: Self::Span) -> Option<String> {
713         self.sess.source_map().span_to_snippet(span).ok()
714     }
715 }