]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/proc_macro_server.rs
Make `TokenStream` less recursive.
[rust.git] / src / libsyntax_ext / proc_macro_server.rs
1 use errors::{self, Diagnostic, DiagnosticBuilder};
2 use std::panic;
3
4 use proc_macro::bridge::{server, TokenTree};
5 use proc_macro::{Delimiter, Level, LineColumn, Spacing};
6
7 use rustc_data_structures::sync::Lrc;
8 use std::ascii;
9 use std::ops::Bound;
10 use syntax::ast;
11 use syntax::ext::base::ExtCtxt;
12 use syntax::parse::lexer::comments;
13 use syntax::parse::{self, token, ParseSess};
14 use syntax::tokenstream::{self, DelimSpan, IsJoint::*, TokenStream, TreeAndJoint};
15 use syntax_pos::hygiene::{SyntaxContext, Transparency};
16 use syntax_pos::symbol::{keywords, Symbol};
17 use syntax_pos::{BytePos, FileName, MultiSpan, Pos, SourceFile, Span};
18
19 trait FromInternal<T> {
20     fn from_internal(x: T) -> Self;
21 }
22
23 trait ToInternal<T> {
24     fn to_internal(self) -> T;
25 }
26
27 impl FromInternal<token::DelimToken> for Delimiter {
28     fn from_internal(delim: token::DelimToken) -> Delimiter {
29         match delim {
30             token::Paren => Delimiter::Parenthesis,
31             token::Brace => Delimiter::Brace,
32             token::Bracket => Delimiter::Bracket,
33             token::NoDelim => Delimiter::None,
34         }
35     }
36 }
37
38 impl ToInternal<token::DelimToken> for Delimiter {
39     fn to_internal(self) -> token::DelimToken {
40         match self {
41             Delimiter::Parenthesis => token::Paren,
42             Delimiter::Brace => token::Brace,
43             Delimiter::Bracket => token::Bracket,
44             Delimiter::None => token::NoDelim,
45         }
46     }
47 }
48
49 impl FromInternal<(TreeAndJoint, &'_ ParseSess, &'_ mut Vec<Self>)>
50     for TokenTree<Group, Punct, Ident, Literal>
51 {
52     fn from_internal(((tree, is_joint), sess, stack): (TreeAndJoint, &ParseSess, &mut Vec<Self>))
53                     -> Self {
54         use syntax::parse::token::*;
55
56         let joint = is_joint == Joint;
57         let (span, token) = match tree {
58             tokenstream::TokenTree::Delimited(span, delim, tts) => {
59                 let delimiter = Delimiter::from_internal(delim);
60                 return TokenTree::Group(Group {
61                     delimiter,
62                     stream: tts.into(),
63                     span,
64                 });
65             }
66             tokenstream::TokenTree::Token(span, token) => (span, token),
67         };
68
69         macro_rules! tt {
70             ($ty:ident { $($field:ident $(: $value:expr)*),+ $(,)* }) => (
71                 TokenTree::$ty(self::$ty {
72                     $($field $(: $value)*,)*
73                     span,
74                 })
75             );
76             ($ty:ident::$method:ident($($value:expr),*)) => (
77                 TokenTree::$ty(self::$ty::$method($($value,)* span))
78             );
79         }
80         macro_rules! op {
81             ($a:expr) => {
82                 tt!(Punct::new($a, joint))
83             };
84             ($a:expr, $b:expr) => {{
85                 stack.push(tt!(Punct::new($b, joint)));
86                 tt!(Punct::new($a, true))
87             }};
88             ($a:expr, $b:expr, $c:expr) => {{
89                 stack.push(tt!(Punct::new($c, joint)));
90                 stack.push(tt!(Punct::new($b, true)));
91                 tt!(Punct::new($a, true))
92             }};
93         }
94
95         match token {
96             Eq => op!('='),
97             Lt => op!('<'),
98             Le => op!('<', '='),
99             EqEq => op!('=', '='),
100             Ne => op!('!', '='),
101             Ge => op!('>', '='),
102             Gt => op!('>'),
103             AndAnd => op!('&', '&'),
104             OrOr => op!('|', '|'),
105             Not => op!('!'),
106             Tilde => op!('~'),
107             BinOp(Plus) => op!('+'),
108             BinOp(Minus) => op!('-'),
109             BinOp(Star) => op!('*'),
110             BinOp(Slash) => op!('/'),
111             BinOp(Percent) => op!('%'),
112             BinOp(Caret) => op!('^'),
113             BinOp(And) => op!('&'),
114             BinOp(Or) => op!('|'),
115             BinOp(Shl) => op!('<', '<'),
116             BinOp(Shr) => op!('>', '>'),
117             BinOpEq(Plus) => op!('+', '='),
118             BinOpEq(Minus) => op!('-', '='),
119             BinOpEq(Star) => op!('*', '='),
120             BinOpEq(Slash) => op!('/', '='),
121             BinOpEq(Percent) => op!('%', '='),
122             BinOpEq(Caret) => op!('^', '='),
123             BinOpEq(And) => op!('&', '='),
124             BinOpEq(Or) => op!('|', '='),
125             BinOpEq(Shl) => op!('<', '<', '='),
126             BinOpEq(Shr) => op!('>', '>', '='),
127             At => op!('@'),
128             Dot => op!('.'),
129             DotDot => op!('.', '.'),
130             DotDotDot => op!('.', '.', '.'),
131             DotDotEq => op!('.', '.', '='),
132             Comma => op!(','),
133             Semi => op!(';'),
134             Colon => op!(':'),
135             ModSep => op!(':', ':'),
136             RArrow => op!('-', '>'),
137             LArrow => op!('<', '-'),
138             FatArrow => op!('=', '>'),
139             Pound => op!('#'),
140             Dollar => op!('$'),
141             Question => op!('?'),
142             SingleQuote => op!('\''),
143
144             Ident(ident, false) if ident.name == keywords::DollarCrate.name() =>
145                 tt!(Ident::dollar_crate()),
146             Ident(ident, is_raw) => tt!(Ident::new(ident.name, is_raw)),
147             Lifetime(ident) => {
148                 let ident = ident.without_first_quote();
149                 stack.push(tt!(Ident::new(ident.name, false)));
150                 tt!(Punct::new('\'', true))
151             }
152             Literal(lit, suffix) => tt!(Literal { lit, suffix }),
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(ast::Ident::new(Symbol::intern("doc"), span), false),
162                     Eq,
163                     Literal(Lit::Str_(Symbol::intern(&escaped)), None),
164                 ]
165                 .into_iter()
166                 .map(|token| tokenstream::TokenTree::Token(span, token))
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(_) => {
180                 let stream = token.interpolated_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                 let token = Ident(ast::Ident::new(sym, span), is_raw);
214                 return tokenstream::TokenTree::Token(span, token).into();
215             }
216             TokenTree::Literal(self::Literal {
217                 lit: Lit::Integer(ref a),
218                 suffix,
219                 span,
220             }) if a.as_str().starts_with("-") => {
221                 let minus = BinOp(BinOpToken::Minus);
222                 let integer = Symbol::intern(&a.as_str()[1..]);
223                 let integer = Literal(Lit::Integer(integer), 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: Lit::Float(ref a),
230                 suffix,
231                 span,
232             }) if a.as_str().starts_with("-") => {
233                 let minus = BinOp(BinOpToken::Minus);
234                 let float = Symbol::intern(&a.as_str()[1..]);
235                 let float = Literal(Lit::Float(float), suffix);
236                 let a = tokenstream::TokenTree::Token(span, minus);
237                 let b = tokenstream::TokenTree::Token(span, float);
238                 return vec![a, b].into_iter().collect();
239             }
240             TokenTree::Literal(self::Literal { lit, suffix, span }) => {
241                 return tokenstream::TokenTree::Token(span, Literal(lit, suffix)).into()
242             }
243         };
244
245         let token = match ch {
246             '=' => Eq,
247             '<' => Lt,
248             '>' => Gt,
249             '!' => Not,
250             '~' => Tilde,
251             '+' => BinOp(Plus),
252             '-' => BinOp(Minus),
253             '*' => BinOp(Star),
254             '/' => BinOp(Slash),
255             '%' => BinOp(Percent),
256             '^' => BinOp(Caret),
257             '&' => BinOp(And),
258             '|' => BinOp(Or),
259             '@' => At,
260             '.' => Dot,
261             ',' => Comma,
262             ';' => Semi,
263             ':' => Colon,
264             '#' => Pound,
265             '$' => Dollar,
266             '?' => Question,
267             '\'' => SingleQuote,
268             _ => unreachable!(),
269         };
270
271         let tree = tokenstream::TokenTree::Token(span, token);
272         TokenStream::Tree(tree, if joint { Joint } else { NonJoint })
273     }
274 }
275
276 impl ToInternal<errors::Level> for Level {
277     fn to_internal(self) -> errors::Level {
278         match self {
279             Level::Error => errors::Level::Error,
280             Level::Warning => errors::Level::Warning,
281             Level::Note => errors::Level::Note,
282             Level::Help => errors::Level::Help,
283             _ => unreachable!("unknown proc_macro::Level variant: {:?}", self),
284         }
285     }
286 }
287
288 #[derive(Clone)]
289 pub struct TokenStreamIter {
290     cursor: tokenstream::Cursor,
291     stack: Vec<TokenTree<Group, Punct, Ident, Literal>>,
292 }
293
294 #[derive(Clone)]
295 pub struct Group {
296     delimiter: Delimiter,
297     stream: TokenStream,
298     span: DelimSpan,
299 }
300
301 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
302 pub struct Punct {
303     ch: char,
304     // NB. not using `Spacing` here because it doesn't implement `Hash`.
305     joint: bool,
306     span: Span,
307 }
308
309 impl Punct {
310     fn new(ch: char, joint: bool, span: Span) -> Punct {
311         const LEGAL_CHARS: &[char] = &['=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^',
312                                        '&', '|', '@', '.', ',', ';', ':', '#', '$', '?', '\''];
313         if !LEGAL_CHARS.contains(&ch) {
314             panic!("unsupported character `{:?}`", ch)
315         }
316         Punct { ch, joint, span }
317     }
318 }
319
320 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
321 pub struct Ident {
322     sym: Symbol,
323     is_raw: bool,
324     span: Span,
325 }
326
327 impl Ident {
328     fn is_valid(string: &str) -> bool {
329         let mut chars = string.chars();
330         if let Some(start) = chars.next() {
331             (start == '_' || start.is_xid_start())
332                 && chars.all(|cont| cont == '_' || cont.is_xid_continue())
333         } else {
334             false
335         }
336     }
337     fn new(sym: Symbol, is_raw: bool, span: Span) -> Ident {
338         let string = sym.as_str().get();
339         if !Self::is_valid(string) {
340             panic!("`{:?}` is not a valid identifier", string)
341         }
342         if is_raw {
343             let normalized_sym = Symbol::intern(string);
344             if normalized_sym == keywords::Underscore.name() ||
345                ast::Ident::with_empty_ctxt(normalized_sym).is_path_segment_keyword() {
346                 panic!("`{:?}` is not a valid raw identifier", string)
347             }
348         }
349         Ident { sym, is_raw, span }
350     }
351     fn dollar_crate(span: Span) -> Ident {
352         // `$crate` is accepted as an ident only if it comes from the compiler.
353         Ident { sym: keywords::DollarCrate.name(), is_raw: false, span }
354     }
355 }
356
357 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
358 #[derive(Clone, Debug)]
359 pub struct Literal {
360     lit: token::Lit,
361     suffix: Option<Symbol>,
362     span: Span,
363 }
364
365 pub(crate) struct Rustc<'a> {
366     sess: &'a ParseSess,
367     def_site: Span,
368     call_site: Span,
369 }
370
371 impl<'a> Rustc<'a> {
372     pub fn new(cx: &'a ExtCtxt) -> Self {
373         // No way to determine def location for a proc macro right now, so use call location.
374         let location = cx.current_expansion.mark.expn_info().unwrap().call_site;
375         let to_span = |transparency| {
376             location.with_ctxt(
377                 SyntaxContext::empty()
378                     .apply_mark_with_transparency(cx.current_expansion.mark, transparency),
379             )
380         };
381         Rustc {
382             sess: cx.parse_sess,
383             def_site: to_span(Transparency::Opaque),
384             call_site: to_span(Transparency::Transparent),
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         Literal {
543             lit: token::Lit::Integer(Symbol::intern(n)),
544             suffix: None,
545             span: server::Span::call_site(self),
546         }
547     }
548     fn typed_integer(&mut self, n: &str, kind: &str) -> Self::Literal {
549         Literal {
550             lit: token::Lit::Integer(Symbol::intern(n)),
551             suffix: Some(Symbol::intern(kind)),
552             span: server::Span::call_site(self),
553         }
554     }
555     fn float(&mut self, n: &str) -> Self::Literal {
556         Literal {
557             lit: token::Lit::Float(Symbol::intern(n)),
558             suffix: None,
559             span: server::Span::call_site(self),
560         }
561     }
562     fn f32(&mut self, n: &str) -> Self::Literal {
563         Literal {
564             lit: token::Lit::Float(Symbol::intern(n)),
565             suffix: Some(Symbol::intern("f32")),
566             span: server::Span::call_site(self),
567         }
568     }
569     fn f64(&mut self, n: &str) -> Self::Literal {
570         Literal {
571             lit: token::Lit::Float(Symbol::intern(n)),
572             suffix: Some(Symbol::intern("f64")),
573             span: server::Span::call_site(self),
574         }
575     }
576     fn string(&mut self, string: &str) -> Self::Literal {
577         let mut escaped = String::new();
578         for ch in string.chars() {
579             escaped.extend(ch.escape_debug());
580         }
581         Literal {
582             lit: token::Lit::Str_(Symbol::intern(&escaped)),
583             suffix: None,
584             span: server::Span::call_site(self),
585         }
586     }
587     fn character(&mut self, ch: char) -> Self::Literal {
588         let mut escaped = String::new();
589         escaped.extend(ch.escape_unicode());
590         Literal {
591             lit: token::Lit::Char(Symbol::intern(&escaped)),
592             suffix: None,
593             span: server::Span::call_site(self),
594         }
595     }
596     fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
597         let string = bytes
598             .iter()
599             .cloned()
600             .flat_map(ascii::escape_default)
601             .map(Into::<char>::into)
602             .collect::<String>();
603         Literal {
604             lit: token::Lit::ByteStr(Symbol::intern(&string)),
605             suffix: None,
606             span: server::Span::call_site(self),
607         }
608     }
609     fn span(&mut self, literal: &Self::Literal) -> Self::Span {
610         literal.span
611     }
612     fn set_span(&mut self, literal: &mut Self::Literal, span: Self::Span) {
613         literal.span = span;
614     }
615     fn subspan(
616         &mut self,
617         literal: &Self::Literal,
618         start: Bound<usize>,
619         end: Bound<usize>,
620     ) -> Option<Self::Span> {
621         let span = literal.span;
622         let length = span.hi().to_usize() - span.lo().to_usize();
623
624         let start = match start {
625             Bound::Included(lo) => lo,
626             Bound::Excluded(lo) => lo + 1,
627             Bound::Unbounded => 0,
628         };
629
630         let end = match end {
631             Bound::Included(hi) => hi + 1,
632             Bound::Excluded(hi) => hi,
633             Bound::Unbounded => length,
634         };
635
636         // Bounds check the values, preventing addition overflow and OOB spans.
637         if start > u32::max_value() as usize
638             || end > u32::max_value() as usize
639             || (u32::max_value() - start as u32) < span.lo().to_u32()
640             || (u32::max_value() - end as u32) < span.lo().to_u32()
641             || start >= end
642             || end > length
643         {
644             return None;
645         }
646
647         let new_lo = span.lo() + BytePos::from_usize(start);
648         let new_hi = span.lo() + BytePos::from_usize(end);
649         Some(span.with_lo(new_lo).with_hi(new_hi))
650     }
651 }
652
653 impl<'a> server::SourceFile for Rustc<'a> {
654     fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
655         Lrc::ptr_eq(file1, file2)
656     }
657     fn path(&mut self, file: &Self::SourceFile) -> String {
658         match file.name {
659             FileName::Real(ref path) => path
660                 .to_str()
661                 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
662                 .to_string(),
663             _ => file.name.to_string(),
664         }
665     }
666     fn is_real(&mut self, file: &Self::SourceFile) -> bool {
667         file.is_real_file()
668     }
669 }
670
671 impl server::MultiSpan for Rustc<'_> {
672     fn new(&mut self) -> Self::MultiSpan {
673         vec![]
674     }
675     fn push(&mut self, spans: &mut Self::MultiSpan, span: Self::Span) {
676         spans.push(span)
677     }
678 }
679
680 impl server::Diagnostic for Rustc<'_> {
681     fn new(&mut self, level: Level, msg: &str, spans: Self::MultiSpan) -> Self::Diagnostic {
682         let mut diag = Diagnostic::new(level.to_internal(), msg);
683         diag.set_span(MultiSpan::from_spans(spans));
684         diag
685     }
686     fn sub(
687         &mut self,
688         diag: &mut Self::Diagnostic,
689         level: Level,
690         msg: &str,
691         spans: Self::MultiSpan,
692     ) {
693         diag.sub(level.to_internal(), msg, MultiSpan::from_spans(spans), None);
694     }
695     fn emit(&mut self, diag: Self::Diagnostic) {
696         DiagnosticBuilder::new_diagnostic(&self.sess.span_diagnostic, diag).emit()
697     }
698 }
699
700 impl server::Span for Rustc<'_> {
701     fn debug(&mut self, span: Self::Span) -> String {
702         format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
703     }
704     fn def_site(&mut self) -> Self::Span {
705         self.def_site
706     }
707     fn call_site(&mut self) -> Self::Span {
708         self.call_site
709     }
710     fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
711         self.sess.source_map().lookup_char_pos(span.lo()).file
712     }
713     fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
714         span.ctxt().outer().expn_info().map(|i| i.call_site)
715     }
716     fn source(&mut self, span: Self::Span) -> Self::Span {
717         span.source_callsite()
718     }
719     fn start(&mut self, span: Self::Span) -> LineColumn {
720         let loc = self.sess.source_map().lookup_char_pos(span.lo());
721         LineColumn {
722             line: loc.line,
723             column: loc.col.to_usize(),
724         }
725     }
726     fn end(&mut self, span: Self::Span) -> LineColumn {
727         let loc = self.sess.source_map().lookup_char_pos(span.hi());
728         LineColumn {
729             line: loc.line,
730             column: loc.col.to_usize(),
731         }
732     }
733     fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
734         let self_loc = self.sess.source_map().lookup_char_pos(first.lo());
735         let other_loc = self.sess.source_map().lookup_char_pos(second.lo());
736
737         if self_loc.file.name != other_loc.file.name {
738             return None;
739         }
740
741         Some(first.to(second))
742     }
743     fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
744         span.with_ctxt(at.ctxt())
745     }
746 }