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