]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/proc_macro_server.rs
Rollup merge of #60981 - alexcrichton:update-compiler-builtins, r=cuviper
[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, 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 == 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, 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(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: 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();
340         if !Self::is_valid(&string) {
341             panic!("`{:?}` is not a valid identifier", string)
342         }
343         if is_raw && !ast::Ident::from_interned_str(sym.as_interned_str()).can_be_raw() {
344             panic!("`{}` cannot be a raw identifier", string);
345         }
346         Ident { sym, is_raw, span }
347     }
348     fn dollar_crate(span: Span) -> Ident {
349         // `$crate` is accepted as an ident only if it comes from the compiler.
350         Ident { sym: kw::DollarCrate, is_raw: false, span }
351     }
352 }
353
354 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
355 #[derive(Clone, Debug)]
356 pub struct Literal {
357     lit: token::Lit,
358     suffix: Option<Symbol>,
359     span: Span,
360 }
361
362 pub(crate) struct Rustc<'a> {
363     sess: &'a ParseSess,
364     def_site: Span,
365     call_site: Span,
366 }
367
368 impl<'a> Rustc<'a> {
369     pub fn new(cx: &'a ExtCtxt<'_>) -> Self {
370         // No way to determine def location for a proc macro right now, so use call location.
371         let location = cx.current_expansion.mark.expn_info().unwrap().call_site;
372         let to_span = |transparency| {
373             location.with_ctxt(
374                 SyntaxContext::empty()
375                     .apply_mark_with_transparency(cx.current_expansion.mark, transparency),
376             )
377         };
378         Rustc {
379             sess: cx.parse_sess,
380             def_site: to_span(Transparency::Opaque),
381             call_site: to_span(Transparency::Transparent),
382         }
383     }
384 }
385
386 impl server::Types for Rustc<'_> {
387     type TokenStream = TokenStream;
388     type TokenStreamBuilder = tokenstream::TokenStreamBuilder;
389     type TokenStreamIter = TokenStreamIter;
390     type Group = Group;
391     type Punct = Punct;
392     type Ident = Ident;
393     type Literal = Literal;
394     type SourceFile = Lrc<SourceFile>;
395     type MultiSpan = Vec<Span>;
396     type Diagnostic = Diagnostic;
397     type Span = Span;
398 }
399
400 impl server::TokenStream for Rustc<'_> {
401     fn new(&mut self) -> Self::TokenStream {
402         TokenStream::empty()
403     }
404     fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
405         stream.is_empty()
406     }
407     fn from_str(&mut self, src: &str) -> Self::TokenStream {
408         parse::parse_stream_from_source_str(
409             FileName::proc_macro_source_code(src.clone()),
410             src.to_string(),
411             self.sess,
412             Some(self.call_site),
413         )
414     }
415     fn to_string(&mut self, stream: &Self::TokenStream) -> String {
416         stream.to_string()
417     }
418     fn from_token_tree(
419         &mut self,
420         tree: TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>,
421     ) -> Self::TokenStream {
422         tree.to_internal()
423     }
424     fn into_iter(&mut self, stream: Self::TokenStream) -> Self::TokenStreamIter {
425         TokenStreamIter {
426             cursor: stream.trees(),
427             stack: vec![],
428         }
429     }
430 }
431
432 impl server::TokenStreamBuilder for Rustc<'_> {
433     fn new(&mut self) -> Self::TokenStreamBuilder {
434         tokenstream::TokenStreamBuilder::new()
435     }
436     fn push(&mut self, builder: &mut Self::TokenStreamBuilder, stream: Self::TokenStream) {
437         builder.push(stream);
438     }
439     fn build(&mut self, builder: Self::TokenStreamBuilder) -> Self::TokenStream {
440         builder.build()
441     }
442 }
443
444 impl server::TokenStreamIter for Rustc<'_> {
445     fn next(
446         &mut self,
447         iter: &mut Self::TokenStreamIter,
448     ) -> Option<TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>> {
449         loop {
450             let tree = iter.stack.pop().or_else(|| {
451                 let next = iter.cursor.next_with_joint()?;
452                 Some(TokenTree::from_internal((next, self.sess, &mut iter.stack)))
453             })?;
454             // HACK: The condition "dummy span + group with empty delimiter" represents an AST
455             // fragment approximately converted into a token stream. This may happen, for
456             // example, with inputs to proc macro attributes, including derives. Such "groups"
457             // need to flattened during iteration over stream's token trees.
458             // Eventually this needs to be removed in favor of keeping original token trees
459             // and not doing the roundtrip through AST.
460             if let TokenTree::Group(ref group) = tree {
461                 if group.delimiter == Delimiter::None && group.span.entire().is_dummy() {
462                     iter.cursor.append(group.stream.clone());
463                     continue;
464                 }
465             }
466             return Some(tree);
467         }
468     }
469 }
470
471 impl server::Group for Rustc<'_> {
472     fn new(&mut self, delimiter: Delimiter, stream: Self::TokenStream) -> Self::Group {
473         Group {
474             delimiter,
475             stream,
476             span: DelimSpan::from_single(server::Span::call_site(self)),
477         }
478     }
479     fn delimiter(&mut self, group: &Self::Group) -> Delimiter {
480         group.delimiter
481     }
482     fn stream(&mut self, group: &Self::Group) -> Self::TokenStream {
483         group.stream.clone()
484     }
485     fn span(&mut self, group: &Self::Group) -> Self::Span {
486         group.span.entire()
487     }
488     fn span_open(&mut self, group: &Self::Group) -> Self::Span {
489         group.span.open
490     }
491     fn span_close(&mut self, group: &Self::Group) -> Self::Span {
492         group.span.close
493     }
494     fn set_span(&mut self, group: &mut Self::Group, span: Self::Span) {
495         group.span = DelimSpan::from_single(span);
496     }
497 }
498
499 impl server::Punct for Rustc<'_> {
500     fn new(&mut self, ch: char, spacing: Spacing) -> Self::Punct {
501         Punct::new(ch, spacing == Spacing::Joint, server::Span::call_site(self))
502     }
503     fn as_char(&mut self, punct: Self::Punct) -> char {
504         punct.ch
505     }
506     fn spacing(&mut self, punct: Self::Punct) -> Spacing {
507         if punct.joint {
508             Spacing::Joint
509         } else {
510             Spacing::Alone
511         }
512     }
513     fn span(&mut self, punct: Self::Punct) -> Self::Span {
514         punct.span
515     }
516     fn with_span(&mut self, punct: Self::Punct, span: Self::Span) -> Self::Punct {
517         Punct { span, ..punct }
518     }
519 }
520
521 impl server::Ident for Rustc<'_> {
522     fn new(&mut self, string: &str, span: Self::Span, is_raw: bool) -> Self::Ident {
523         Ident::new(Symbol::intern(string), is_raw, span)
524     }
525     fn span(&mut self, ident: Self::Ident) -> Self::Span {
526         ident.span
527     }
528     fn with_span(&mut self, ident: Self::Ident, span: Self::Span) -> Self::Ident {
529         Ident { span, ..ident }
530     }
531 }
532
533 impl server::Literal for Rustc<'_> {
534     // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
535     fn debug(&mut self, literal: &Self::Literal) -> String {
536         format!("{:?}", literal)
537     }
538     fn integer(&mut self, n: &str) -> Self::Literal {
539         Literal {
540             lit: token::Lit::Integer(Symbol::intern(n)),
541             suffix: None,
542             span: server::Span::call_site(self),
543         }
544     }
545     fn typed_integer(&mut self, n: &str, kind: &str) -> Self::Literal {
546         Literal {
547             lit: token::Lit::Integer(Symbol::intern(n)),
548             suffix: Some(Symbol::intern(kind)),
549             span: server::Span::call_site(self),
550         }
551     }
552     fn float(&mut self, n: &str) -> Self::Literal {
553         Literal {
554             lit: token::Lit::Float(Symbol::intern(n)),
555             suffix: None,
556             span: server::Span::call_site(self),
557         }
558     }
559     fn f32(&mut self, n: &str) -> Self::Literal {
560         Literal {
561             lit: token::Lit::Float(Symbol::intern(n)),
562             suffix: Some(Symbol::intern("f32")),
563             span: server::Span::call_site(self),
564         }
565     }
566     fn f64(&mut self, n: &str) -> Self::Literal {
567         Literal {
568             lit: token::Lit::Float(Symbol::intern(n)),
569             suffix: Some(Symbol::intern("f64")),
570             span: server::Span::call_site(self),
571         }
572     }
573     fn string(&mut self, string: &str) -> Self::Literal {
574         let mut escaped = String::new();
575         for ch in string.chars() {
576             escaped.extend(ch.escape_debug());
577         }
578         Literal {
579             lit: token::Lit::Str_(Symbol::intern(&escaped)),
580             suffix: None,
581             span: server::Span::call_site(self),
582         }
583     }
584     fn character(&mut self, ch: char) -> Self::Literal {
585         let mut escaped = String::new();
586         escaped.extend(ch.escape_unicode());
587         Literal {
588             lit: token::Lit::Char(Symbol::intern(&escaped)),
589             suffix: None,
590             span: server::Span::call_site(self),
591         }
592     }
593     fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
594         let string = bytes
595             .iter()
596             .cloned()
597             .flat_map(ascii::escape_default)
598             .map(Into::<char>::into)
599             .collect::<String>();
600         Literal {
601             lit: token::Lit::ByteStr(Symbol::intern(&string)),
602             suffix: None,
603             span: server::Span::call_site(self),
604         }
605     }
606     fn span(&mut self, literal: &Self::Literal) -> Self::Span {
607         literal.span
608     }
609     fn set_span(&mut self, literal: &mut Self::Literal, span: Self::Span) {
610         literal.span = span;
611     }
612     fn subspan(
613         &mut self,
614         literal: &Self::Literal,
615         start: Bound<usize>,
616         end: Bound<usize>,
617     ) -> Option<Self::Span> {
618         let span = literal.span;
619         let length = span.hi().to_usize() - span.lo().to_usize();
620
621         let start = match start {
622             Bound::Included(lo) => lo,
623             Bound::Excluded(lo) => lo + 1,
624             Bound::Unbounded => 0,
625         };
626
627         let end = match end {
628             Bound::Included(hi) => hi + 1,
629             Bound::Excluded(hi) => hi,
630             Bound::Unbounded => length,
631         };
632
633         // Bounds check the values, preventing addition overflow and OOB spans.
634         if start > u32::max_value() as usize
635             || end > u32::max_value() as usize
636             || (u32::max_value() - start as u32) < span.lo().to_u32()
637             || (u32::max_value() - end as u32) < span.lo().to_u32()
638             || start >= end
639             || end > length
640         {
641             return None;
642         }
643
644         let new_lo = span.lo() + BytePos::from_usize(start);
645         let new_hi = span.lo() + BytePos::from_usize(end);
646         Some(span.with_lo(new_lo).with_hi(new_hi))
647     }
648 }
649
650 impl server::SourceFile for Rustc<'_> {
651     fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
652         Lrc::ptr_eq(file1, file2)
653     }
654     fn path(&mut self, file: &Self::SourceFile) -> String {
655         match file.name {
656             FileName::Real(ref path) => path
657                 .to_str()
658                 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
659                 .to_string(),
660             _ => file.name.to_string(),
661         }
662     }
663     fn is_real(&mut self, file: &Self::SourceFile) -> bool {
664         file.is_real_file()
665     }
666 }
667
668 impl server::MultiSpan for Rustc<'_> {
669     fn new(&mut self) -> Self::MultiSpan {
670         vec![]
671     }
672     fn push(&mut self, spans: &mut Self::MultiSpan, span: Self::Span) {
673         spans.push(span)
674     }
675 }
676
677 impl server::Diagnostic for Rustc<'_> {
678     fn new(&mut self, level: Level, msg: &str, spans: Self::MultiSpan) -> Self::Diagnostic {
679         let mut diag = Diagnostic::new(level.to_internal(), msg);
680         diag.set_span(MultiSpan::from_spans(spans));
681         diag
682     }
683     fn sub(
684         &mut self,
685         diag: &mut Self::Diagnostic,
686         level: Level,
687         msg: &str,
688         spans: Self::MultiSpan,
689     ) {
690         diag.sub(level.to_internal(), msg, MultiSpan::from_spans(spans), None);
691     }
692     fn emit(&mut self, diag: Self::Diagnostic) {
693         DiagnosticBuilder::new_diagnostic(&self.sess.span_diagnostic, diag).emit()
694     }
695 }
696
697 impl server::Span for Rustc<'_> {
698     fn debug(&mut self, span: Self::Span) -> String {
699         format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
700     }
701     fn def_site(&mut self) -> Self::Span {
702         self.def_site
703     }
704     fn call_site(&mut self) -> Self::Span {
705         self.call_site
706     }
707     fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
708         self.sess.source_map().lookup_char_pos(span.lo()).file
709     }
710     fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
711         span.ctxt().outer().expn_info().map(|i| i.call_site)
712     }
713     fn source(&mut self, span: Self::Span) -> Self::Span {
714         span.source_callsite()
715     }
716     fn start(&mut self, span: Self::Span) -> LineColumn {
717         let loc = self.sess.source_map().lookup_char_pos(span.lo());
718         LineColumn {
719             line: loc.line,
720             column: loc.col.to_usize(),
721         }
722     }
723     fn end(&mut self, span: Self::Span) -> LineColumn {
724         let loc = self.sess.source_map().lookup_char_pos(span.hi());
725         LineColumn {
726             line: loc.line,
727             column: loc.col.to_usize(),
728         }
729     }
730     fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
731         let self_loc = self.sess.source_map().lookup_char_pos(first.lo());
732         let other_loc = self.sess.source_map().lookup_char_pos(second.lo());
733
734         if self_loc.file.name != other_loc.file.name {
735             return None;
736         }
737
738         Some(first.to(second))
739     }
740     fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
741         span.with_ctxt(at.ctxt())
742     }
743     fn source_text(&mut self,  span: Self::Span) -> Option<String> {
744         self.sess.source_map().span_to_snippet(span).ok()
745     }
746 }