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