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