]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/proc_macro_server.rs
Rollup merge of #58260 - taiki-e:librustc_borrowck-2018, r=Centril
[rust.git] / src / libsyntax_ext / proc_macro_server.rs
1 use crate::errors::{self, 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::{keywords, 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 (span, token) = 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(span, token) => (span, 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 token {
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 == keywords::DollarCrate.name() =>
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, suffix) => tt!(Literal { lit, suffix }),
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(Symbol::intern("doc"), span), false),
163                     Eq,
164                     Literal(Lit::Str_(Symbol::intern(&escaped)), None),
165                 ]
166                 .into_iter()
167                 .map(|token| tokenstream::TokenTree::Token(span, token))
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(_) => {
181                 let stream = token.interpolated_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: Lit::Integer(ref a),
219                 suffix,
220                 span,
221             }) if a.as_str().starts_with("-") => {
222                 let minus = BinOp(BinOpToken::Minus);
223                 let integer = Symbol::intern(&a.as_str()[1..]);
224                 let integer = Literal(Lit::Integer(integer), suffix);
225                 let a = tokenstream::TokenTree::Token(span, minus);
226                 let b = tokenstream::TokenTree::Token(span, integer);
227                 return vec![a, b].into_iter().collect();
228             }
229             TokenTree::Literal(self::Literal {
230                 lit: Lit::Float(ref a),
231                 suffix,
232                 span,
233             }) if a.as_str().starts_with("-") => {
234                 let minus = BinOp(BinOpToken::Minus);
235                 let float = Symbol::intern(&a.as_str()[1..]);
236                 let float = Literal(Lit::Float(float), suffix);
237                 let a = tokenstream::TokenTree::Token(span, minus);
238                 let b = tokenstream::TokenTree::Token(span, float);
239                 return vec![a, b].into_iter().collect();
240             }
241             TokenTree::Literal(self::Literal { lit, suffix, span }) => {
242                 return tokenstream::TokenTree::Token(span, Literal(lit, suffix)).into()
243             }
244         };
245
246         let token = match ch {
247             '=' => Eq,
248             '<' => Lt,
249             '>' => Gt,
250             '!' => Not,
251             '~' => Tilde,
252             '+' => BinOp(Plus),
253             '-' => BinOp(Minus),
254             '*' => BinOp(Star),
255             '/' => BinOp(Slash),
256             '%' => BinOp(Percent),
257             '^' => BinOp(Caret),
258             '&' => BinOp(And),
259             '|' => BinOp(Or),
260             '@' => At,
261             '.' => Dot,
262             ',' => Comma,
263             ';' => Semi,
264             ':' => Colon,
265             '#' => Pound,
266             '$' => Dollar,
267             '?' => Question,
268             '\'' => SingleQuote,
269             _ => unreachable!(),
270         };
271
272         let tree = tokenstream::TokenTree::Token(span, token);
273         TokenStream::new(vec![(tree, if joint { Joint } else { NonJoint })])
274     }
275 }
276
277 impl ToInternal<errors::Level> for Level {
278     fn to_internal(self) -> errors::Level {
279         match self {
280             Level::Error => errors::Level::Error,
281             Level::Warning => errors::Level::Warning,
282             Level::Note => errors::Level::Note,
283             Level::Help => errors::Level::Help,
284             _ => unreachable!("unknown proc_macro::Level variant: {:?}", self),
285         }
286     }
287 }
288
289 #[derive(Clone)]
290 pub struct TokenStreamIter {
291     cursor: tokenstream::Cursor,
292     stack: Vec<TokenTree<Group, Punct, Ident, Literal>>,
293 }
294
295 #[derive(Clone)]
296 pub struct Group {
297     delimiter: Delimiter,
298     stream: TokenStream,
299     span: DelimSpan,
300 }
301
302 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
303 pub struct Punct {
304     ch: char,
305     // NB. not using `Spacing` here because it doesn't implement `Hash`.
306     joint: bool,
307     span: Span,
308 }
309
310 impl Punct {
311     fn new(ch: char, joint: bool, span: Span) -> Punct {
312         const LEGAL_CHARS: &[char] = &['=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^',
313                                        '&', '|', '@', '.', ',', ';', ':', '#', '$', '?', '\''];
314         if !LEGAL_CHARS.contains(&ch) {
315             panic!("unsupported character `{:?}`", ch)
316         }
317         Punct { ch, joint, span }
318     }
319 }
320
321 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
322 pub struct Ident {
323     sym: Symbol,
324     is_raw: bool,
325     span: Span,
326 }
327
328 impl Ident {
329     fn is_valid(string: &str) -> bool {
330         let mut chars = string.chars();
331         if let Some(start) = chars.next() {
332             (start == '_' || start.is_xid_start())
333                 && chars.all(|cont| cont == '_' || cont.is_xid_continue())
334         } else {
335             false
336         }
337     }
338     fn new(sym: Symbol, is_raw: bool, span: Span) -> Ident {
339         let string = sym.as_str().get();
340         if !Self::is_valid(string) {
341             panic!("`{:?}` is not a valid identifier", string)
342         }
343         if is_raw {
344             let normalized_sym = Symbol::intern(string);
345             if normalized_sym == keywords::Underscore.name() ||
346                ast::Ident::with_empty_ctxt(normalized_sym).is_path_segment_keyword() {
347                 panic!("`{:?}` is not a valid raw identifier", string)
348             }
349         }
350         Ident { sym, is_raw, span }
351     }
352     fn dollar_crate(span: Span) -> Ident {
353         // `$crate` is accepted as an ident only if it comes from the compiler.
354         Ident { sym: keywords::DollarCrate.name(), is_raw: false, span }
355     }
356 }
357
358 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
359 #[derive(Clone, Debug)]
360 pub struct Literal {
361     lit: token::Lit,
362     suffix: Option<Symbol>,
363     span: Span,
364 }
365
366 pub(crate) struct Rustc<'a> {
367     sess: &'a ParseSess,
368     def_site: Span,
369     call_site: Span,
370 }
371
372 impl<'a> Rustc<'a> {
373     pub fn new(cx: &'a ExtCtxt<'_>) -> Self {
374         // No way to determine def location for a proc macro right now, so use call location.
375         let location = cx.current_expansion.mark.expn_info().unwrap().call_site;
376         let to_span = |transparency| {
377             location.with_ctxt(
378                 SyntaxContext::empty()
379                     .apply_mark_with_transparency(cx.current_expansion.mark, transparency),
380             )
381         };
382         Rustc {
383             sess: cx.parse_sess,
384             def_site: to_span(Transparency::Opaque),
385             call_site: to_span(Transparency::Transparent),
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         Literal {
544             lit: token::Lit::Integer(Symbol::intern(n)),
545             suffix: None,
546             span: server::Span::call_site(self),
547         }
548     }
549     fn typed_integer(&mut self, n: &str, kind: &str) -> Self::Literal {
550         Literal {
551             lit: token::Lit::Integer(Symbol::intern(n)),
552             suffix: Some(Symbol::intern(kind)),
553             span: server::Span::call_site(self),
554         }
555     }
556     fn float(&mut self, n: &str) -> Self::Literal {
557         Literal {
558             lit: token::Lit::Float(Symbol::intern(n)),
559             suffix: None,
560             span: server::Span::call_site(self),
561         }
562     }
563     fn f32(&mut self, n: &str) -> Self::Literal {
564         Literal {
565             lit: token::Lit::Float(Symbol::intern(n)),
566             suffix: Some(Symbol::intern("f32")),
567             span: server::Span::call_site(self),
568         }
569     }
570     fn f64(&mut self, n: &str) -> Self::Literal {
571         Literal {
572             lit: token::Lit::Float(Symbol::intern(n)),
573             suffix: Some(Symbol::intern("f64")),
574             span: server::Span::call_site(self),
575         }
576     }
577     fn string(&mut self, string: &str) -> Self::Literal {
578         let mut escaped = String::new();
579         for ch in string.chars() {
580             escaped.extend(ch.escape_debug());
581         }
582         Literal {
583             lit: token::Lit::Str_(Symbol::intern(&escaped)),
584             suffix: None,
585             span: server::Span::call_site(self),
586         }
587     }
588     fn character(&mut self, ch: char) -> Self::Literal {
589         let mut escaped = String::new();
590         escaped.extend(ch.escape_unicode());
591         Literal {
592             lit: token::Lit::Char(Symbol::intern(&escaped)),
593             suffix: None,
594             span: server::Span::call_site(self),
595         }
596     }
597     fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
598         let string = bytes
599             .iter()
600             .cloned()
601             .flat_map(ascii::escape_default)
602             .map(Into::<char>::into)
603             .collect::<String>();
604         Literal {
605             lit: token::Lit::ByteStr(Symbol::intern(&string)),
606             suffix: None,
607             span: server::Span::call_site(self),
608         }
609     }
610     fn span(&mut self, literal: &Self::Literal) -> Self::Span {
611         literal.span
612     }
613     fn set_span(&mut self, literal: &mut Self::Literal, span: Self::Span) {
614         literal.span = span;
615     }
616     fn subspan(
617         &mut self,
618         literal: &Self::Literal,
619         start: Bound<usize>,
620         end: Bound<usize>,
621     ) -> Option<Self::Span> {
622         let span = literal.span;
623         let length = span.hi().to_usize() - span.lo().to_usize();
624
625         let start = match start {
626             Bound::Included(lo) => lo,
627             Bound::Excluded(lo) => lo + 1,
628             Bound::Unbounded => 0,
629         };
630
631         let end = match end {
632             Bound::Included(hi) => hi + 1,
633             Bound::Excluded(hi) => hi,
634             Bound::Unbounded => length,
635         };
636
637         // Bounds check the values, preventing addition overflow and OOB spans.
638         if start > u32::max_value() as usize
639             || end > u32::max_value() as usize
640             || (u32::max_value() - start as u32) < span.lo().to_u32()
641             || (u32::max_value() - end as u32) < span.lo().to_u32()
642             || start >= end
643             || end > length
644         {
645             return None;
646         }
647
648         let new_lo = span.lo() + BytePos::from_usize(start);
649         let new_hi = span.lo() + BytePos::from_usize(end);
650         Some(span.with_lo(new_lo).with_hi(new_hi))
651     }
652 }
653
654 impl server::SourceFile for Rustc<'_> {
655     fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
656         Lrc::ptr_eq(file1, file2)
657     }
658     fn path(&mut self, file: &Self::SourceFile) -> String {
659         match file.name {
660             FileName::Real(ref path) => path
661                 .to_str()
662                 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
663                 .to_string(),
664             _ => file.name.to_string(),
665         }
666     }
667     fn is_real(&mut self, file: &Self::SourceFile) -> bool {
668         file.is_real_file()
669     }
670 }
671
672 impl server::MultiSpan for Rustc<'_> {
673     fn new(&mut self) -> Self::MultiSpan {
674         vec![]
675     }
676     fn push(&mut self, spans: &mut Self::MultiSpan, span: Self::Span) {
677         spans.push(span)
678     }
679 }
680
681 impl server::Diagnostic for Rustc<'_> {
682     fn new(&mut self, level: Level, msg: &str, spans: Self::MultiSpan) -> Self::Diagnostic {
683         let mut diag = Diagnostic::new(level.to_internal(), msg);
684         diag.set_span(MultiSpan::from_spans(spans));
685         diag
686     }
687     fn sub(
688         &mut self,
689         diag: &mut Self::Diagnostic,
690         level: Level,
691         msg: &str,
692         spans: Self::MultiSpan,
693     ) {
694         diag.sub(level.to_internal(), msg, MultiSpan::from_spans(spans), None);
695     }
696     fn emit(&mut self, diag: Self::Diagnostic) {
697         DiagnosticBuilder::new_diagnostic(&self.sess.span_diagnostic, diag).emit()
698     }
699 }
700
701 impl server::Span for Rustc<'_> {
702     fn debug(&mut self, span: Self::Span) -> String {
703         format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
704     }
705     fn def_site(&mut self) -> Self::Span {
706         self.def_site
707     }
708     fn call_site(&mut self) -> Self::Span {
709         self.call_site
710     }
711     fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
712         self.sess.source_map().lookup_char_pos(span.lo()).file
713     }
714     fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
715         span.ctxt().outer().expn_info().map(|i| i.call_site)
716     }
717     fn source(&mut self, span: Self::Span) -> Self::Span {
718         span.source_callsite()
719     }
720     fn start(&mut self, span: Self::Span) -> LineColumn {
721         let loc = self.sess.source_map().lookup_char_pos(span.lo());
722         LineColumn {
723             line: loc.line,
724             column: loc.col.to_usize(),
725         }
726     }
727     fn end(&mut self, span: Self::Span) -> LineColumn {
728         let loc = self.sess.source_map().lookup_char_pos(span.hi());
729         LineColumn {
730             line: loc.line,
731             column: loc.col.to_usize(),
732         }
733     }
734     fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
735         let self_loc = self.sess.source_map().lookup_char_pos(first.lo());
736         let other_loc = self.sess.source_map().lookup_char_pos(second.lo());
737
738         if self_loc.file.name != other_loc.file.name {
739             return None;
740         }
741
742         Some(first.to(second))
743     }
744     fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
745         span.with_ctxt(at.ctxt())
746     }
747 }