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