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