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