1 use crate::base::ExtCtxt;
5 use rustc_ast::tokenstream::{self, DelimSpan, Spacing::*, TokenStream, TreeAndSpacing};
6 use rustc_ast_pretty::pprust;
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_data_structures::sync::Lrc;
9 use rustc_errors::{Diagnostic, MultiSpan, PResult};
10 use rustc_parse::lexer::nfc_normalize;
11 use rustc_parse::parse_stream_from_source_str;
12 use rustc_session::parse::ParseSess;
13 use rustc_span::def_id::CrateNum;
14 use rustc_span::symbol::{self, kw, sym, Symbol};
15 use rustc_span::{BytePos, FileName, Pos, SourceFile, Span};
17 use pm::bridge::{server, TokenTree};
18 use pm::{Delimiter, Level, LineColumn, Spacing};
20 use std::{ascii, panic};
22 trait FromInternal<T> {
23 fn from_internal(x: T) -> Self;
27 fn to_internal(self) -> T;
30 impl FromInternal<token::Delimiter> for Delimiter {
31 fn from_internal(delim: token::Delimiter) -> Delimiter {
33 token::Delimiter::Parenthesis => Delimiter::Parenthesis,
34 token::Delimiter::Brace => Delimiter::Brace,
35 token::Delimiter::Bracket => Delimiter::Bracket,
36 token::Delimiter::Invisible => Delimiter::None,
41 impl ToInternal<token::Delimiter> for Delimiter {
42 fn to_internal(self) -> token::Delimiter {
44 Delimiter::Parenthesis => token::Delimiter::Parenthesis,
45 Delimiter::Brace => token::Delimiter::Brace,
46 Delimiter::Bracket => token::Delimiter::Bracket,
47 Delimiter::None => token::Delimiter::Invisible,
52 impl FromInternal<(TreeAndSpacing, &'_ mut Vec<Self>, &mut Rustc<'_, '_>)>
53 for TokenTree<Group, Punct, Ident, Literal>
56 ((tree, spacing), stack, rustc): (TreeAndSpacing, &mut Vec<Self>, &mut Rustc<'_, '_>),
58 use rustc_ast::token::*;
60 let joint = spacing == Joint;
61 let Token { kind, span } = match tree {
62 tokenstream::TokenTree::Delimited(span, delim, tts) => {
63 let delimiter = pm::Delimiter::from_internal(delim);
64 return TokenTree::Group(Group { delimiter, stream: tts, span, flatten: false });
66 tokenstream::TokenTree::Token(token) => token,
70 ($ty:ident { $($field:ident $(: $value:expr)*),+ $(,)? }) => (
71 TokenTree::$ty(self::$ty {
72 $($field $(: $value)*,)+
76 ($ty:ident::$method:ident($($value:expr),*)) => (
77 TokenTree::$ty(self::$ty::$method($($value,)* span))
82 tt!(Punct::new($a, joint))
84 ($a:expr, $b:expr) => {{
85 stack.push(tt!(Punct::new($b, joint)));
86 tt!(Punct::new($a, true))
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))
99 EqEq => op!('=', '='),
103 AndAnd => op!('&', '&'),
104 OrOr => 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!('>', '>', '='),
129 DotDot => op!('.', '.'),
130 DotDotDot => op!('.', '.', '.'),
131 DotDotEq => op!('.', '.', '='),
135 ModSep => op!(':', ':'),
136 RArrow => op!('-', '>'),
137 LArrow => op!('<', '-'),
138 FatArrow => op!('=', '>'),
141 Question => op!('?'),
142 SingleQuote => op!('\''),
144 Ident(name, false) if name == kw::DollarCrate => tt!(Ident::dollar_crate()),
145 Ident(name, is_raw) => tt!(Ident::new(rustc.sess(), name, is_raw)),
147 let ident = symbol::Ident::new(name, span).without_first_quote();
148 stack.push(tt!(Ident::new(rustc.sess(), ident.name, false)));
149 tt!(Punct::new('\'', true))
151 Literal(lit) => tt!(Literal { lit }),
152 DocComment(_, attr_style, data) => {
153 let mut escaped = String::new();
154 for ch in data.as_str().chars() {
155 escaped.extend(ch.escape_debug());
158 Ident(sym::doc, false),
160 TokenKind::lit(token::Str, Symbol::intern(&escaped), None),
163 .map(|kind| tokenstream::TokenTree::token(kind, span))
165 stack.push(TokenTree::Group(Group {
166 delimiter: pm::Delimiter::Bracket,
168 span: DelimSpan::from_single(span),
171 if attr_style == ast::AttrStyle::Inner {
172 stack.push(tt!(Punct::new('!', false)));
174 tt!(Punct::new('#', false))
177 Interpolated(nt) if let NtIdent(ident, is_raw) = *nt => {
178 TokenTree::Ident(Ident::new(rustc.sess(), ident.name, is_raw, ident.span))
180 Interpolated(nt) => {
181 TokenTree::Group(Group {
182 delimiter: pm::Delimiter::None,
183 stream: TokenStream::from_nonterminal_ast(&nt),
184 span: DelimSpan::from_single(span),
185 flatten: crate::base::nt_pretty_printing_compatibility_hack(&nt, rustc.sess()),
189 OpenDelim(..) | CloseDelim(..) => unreachable!(),
190 Eof => unreachable!(),
195 impl ToInternal<TokenStream> for TokenTree<Group, Punct, Ident, Literal> {
196 fn to_internal(self) -> TokenStream {
197 use rustc_ast::token::*;
199 let (ch, joint, span) = match self {
200 TokenTree::Punct(Punct { ch, joint, span }) => (ch, joint, span),
201 TokenTree::Group(Group { delimiter, stream, span, .. }) => {
202 return tokenstream::TokenTree::Delimited(span, delimiter.to_internal(), stream)
205 TokenTree::Ident(self::Ident { sym, is_raw, span }) => {
206 return tokenstream::TokenTree::token(Ident(sym, is_raw), span).into();
208 TokenTree::Literal(self::Literal {
209 lit: token::Lit { kind: token::Integer, symbol, suffix },
211 }) if symbol.as_str().starts_with('-') => {
212 let minus = BinOp(BinOpToken::Minus);
213 let symbol = Symbol::intern(&symbol.as_str()[1..]);
214 let integer = TokenKind::lit(token::Integer, symbol, suffix);
215 let a = tokenstream::TokenTree::token(minus, span);
216 let b = tokenstream::TokenTree::token(integer, span);
217 return [a, b].into_iter().collect();
219 TokenTree::Literal(self::Literal {
220 lit: token::Lit { kind: token::Float, symbol, suffix },
222 }) if symbol.as_str().starts_with('-') => {
223 let minus = BinOp(BinOpToken::Minus);
224 let symbol = Symbol::intern(&symbol.as_str()[1..]);
225 let float = TokenKind::lit(token::Float, symbol, suffix);
226 let a = tokenstream::TokenTree::token(minus, span);
227 let b = tokenstream::TokenTree::token(float, span);
228 return [a, b].into_iter().collect();
230 TokenTree::Literal(self::Literal { lit, span }) => {
231 return tokenstream::TokenTree::token(Literal(lit), span).into();
235 let kind = match ch {
245 '%' => BinOp(Percent),
261 let tree = tokenstream::TokenTree::token(kind, span);
262 TokenStream::new(vec![(tree, if joint { Joint } else { Alone })])
266 impl ToInternal<rustc_errors::Level> for Level {
267 fn to_internal(self) -> rustc_errors::Level {
269 Level::Error => rustc_errors::Level::Error { lint: false },
270 Level::Warning => rustc_errors::Level::Warning(None),
271 Level::Note => rustc_errors::Level::Note,
272 Level::Help => rustc_errors::Level::Help,
273 _ => unreachable!("unknown proc_macro::Level variant: {:?}", self),
278 pub struct FreeFunctions;
282 delimiter: Delimiter,
285 /// A hack used to pass AST fragments to attribute and derive macros
286 /// as a single nonterminal token instead of a token stream.
287 /// FIXME: It needs to be removed, but there are some compatibility issues (see #73345).
291 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
294 // NB. not using `Spacing` here because it doesn't implement `Hash`.
300 fn new(ch: char, joint: bool, span: Span) -> Punct {
301 const LEGAL_CHARS: &[char] = &[
302 '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
303 ':', '#', '$', '?', '\'',
305 if !LEGAL_CHARS.contains(&ch) {
306 panic!("unsupported character `{:?}`", ch)
308 Punct { ch, joint, span }
312 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
320 fn new(sess: &ParseSess, sym: Symbol, is_raw: bool, span: Span) -> Ident {
321 let sym = nfc_normalize(sym.as_str());
322 let string = sym.as_str();
323 if !rustc_lexer::is_ident(string) {
324 panic!("`{:?}` is not a valid identifier", string)
326 if is_raw && !sym.can_be_raw() {
327 panic!("`{}` cannot be a raw identifier", string);
329 sess.symbol_gallery.insert(sym, span);
330 Ident { sym, is_raw, span }
333 fn dollar_crate(span: Span) -> Ident {
334 // `$crate` is accepted as an ident only if it comes from the compiler.
335 Ident { sym: kw::DollarCrate, is_raw: false, span }
339 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
340 #[derive(Clone, Debug)]
346 pub(crate) struct Rustc<'a, 'b> {
347 ecx: &'a mut ExtCtxt<'b>,
352 rebased_spans: FxHashMap<usize, Span>,
355 impl<'a, 'b> Rustc<'a, 'b> {
356 pub fn new(ecx: &'a mut ExtCtxt<'b>) -> Self {
357 let expn_data = ecx.current_expansion.id.expn_data();
359 def_site: ecx.with_def_site_ctxt(expn_data.def_site),
360 call_site: ecx.with_call_site_ctxt(expn_data.call_site),
361 mixed_site: ecx.with_mixed_site_ctxt(expn_data.call_site),
362 krate: expn_data.macro_def_id.unwrap().krate,
363 rebased_spans: FxHashMap::default(),
368 fn sess(&self) -> &ParseSess {
369 self.ecx.parse_sess()
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) }
377 impl server::Types for Rustc<'_, '_> {
378 type FreeFunctions = FreeFunctions;
379 type TokenStream = TokenStream;
383 type Literal = Literal;
384 type SourceFile = Lrc<SourceFile>;
385 type MultiSpan = Vec<Span>;
386 type Diagnostic = Diagnostic;
390 impl server::FreeFunctions for Rustc<'_, '_> {
391 fn track_env_var(&mut self, var: &str, value: Option<&str>) {
395 .insert((Symbol::intern(var), value.map(Symbol::intern)));
398 fn track_path(&mut self, path: &str) {
399 self.sess().file_depinfo.borrow_mut().insert(Symbol::intern(path));
403 impl server::TokenStream for Rustc<'_, '_> {
404 fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
408 fn from_str(&mut self, src: &str) -> Self::TokenStream {
409 parse_stream_from_source_str(
410 FileName::proc_macro_source_code(src),
413 Some(self.call_site),
417 fn to_string(&mut self, stream: &Self::TokenStream) -> String {
418 pprust::tts_to_string(stream)
421 fn expand_expr(&mut self, stream: &Self::TokenStream) -> Result<Self::TokenStream, ()> {
422 // Parse the expression from our tokenstream.
423 let expr: PResult<'_, _> = try {
424 let mut p = rustc_parse::stream_to_parser(
427 Some("proc_macro expand expr"),
429 let expr = p.parse_expr()?;
430 if p.token != token::Eof {
435 let expr = expr.map_err(|mut err| {
439 // Perform eager expansion on the expression.
443 .fully_expand_fragment(crate::expand::AstFragment::Expr(expr))
446 // NOTE: For now, limit `expand_expr` to exclusively expand to literals.
447 // This may be relaxed in the future.
448 // We don't use `TokenStream::from_ast` as the tokenstream currently cannot
449 // be recovered in the general case.
451 ast::ExprKind::Lit(l) => {
452 Ok(tokenstream::TokenTree::token(token::Literal(l.token), l.span).into())
454 ast::ExprKind::Unary(ast::UnOp::Neg, e) => match &e.kind {
455 ast::ExprKind::Lit(l) => match l.token {
456 token::Lit { kind: token::Integer | token::Float, .. } => {
457 Ok(Self::TokenStream::from_iter([
458 // FIXME: The span of the `-` token is lost when
459 // parsing, so we cannot faithfully recover it here.
460 tokenstream::TokenTree::token(token::BinOp(token::Minus), e.span),
461 tokenstream::TokenTree::token(token::Literal(l.token), l.span),
474 tree: TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>,
475 ) -> Self::TokenStream {
481 base: Option<Self::TokenStream>,
482 trees: Vec<TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>>,
483 ) -> Self::TokenStream {
484 let mut builder = tokenstream::TokenStreamBuilder::new();
485 if let Some(base) = base {
489 builder.push(tree.to_internal());
496 base: Option<Self::TokenStream>,
497 streams: Vec<Self::TokenStream>,
498 ) -> Self::TokenStream {
499 let mut builder = tokenstream::TokenStreamBuilder::new();
500 if let Some(base) = base {
503 for stream in streams {
504 builder.push(stream);
511 stream: Self::TokenStream,
512 ) -> Vec<TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>> {
513 // FIXME: This is a raw port of the previous approach (which had a
514 // `TokenStreamIter` server-side object with a single `next` method),
515 // and can probably be optimized (for bulk conversion).
516 let mut cursor = stream.into_trees();
517 let mut stack = Vec::new();
518 let mut tts = Vec::new();
520 let next = stack.pop().or_else(|| {
521 let next = cursor.next_with_spacing()?;
522 Some(TokenTree::from_internal((next, &mut stack, self)))
525 Some(TokenTree::Group(group)) => {
526 // A hack used to pass AST fragments to attribute and derive
527 // macros as a single nonterminal token instead of a token
528 // stream. Such token needs to be "unwrapped" and not
529 // represented as a delimited group.
530 // FIXME: It needs to be removed, but there are some
531 // compatibility issues (see #73345).
533 tts.append(&mut self.into_trees(group.stream));
535 tts.push(TokenTree::Group(group));
538 Some(tt) => tts.push(tt),
545 impl server::Group for Rustc<'_, '_> {
546 fn new(&mut self, delimiter: Delimiter, stream: Option<Self::TokenStream>) -> Self::Group {
549 stream: stream.unwrap_or_default(),
550 span: DelimSpan::from_single(server::Span::call_site(self)),
555 fn delimiter(&mut self, group: &Self::Group) -> Delimiter {
559 fn stream(&mut self, group: &Self::Group) -> Self::TokenStream {
563 fn span(&mut self, group: &Self::Group) -> Self::Span {
567 fn span_open(&mut self, group: &Self::Group) -> Self::Span {
571 fn span_close(&mut self, group: &Self::Group) -> Self::Span {
575 fn set_span(&mut self, group: &mut Self::Group, span: Self::Span) {
576 group.span = DelimSpan::from_single(span);
580 impl server::Punct for Rustc<'_, '_> {
581 fn new(&mut self, ch: char, spacing: Spacing) -> Self::Punct {
582 Punct::new(ch, spacing == Spacing::Joint, server::Span::call_site(self))
585 fn as_char(&mut self, punct: Self::Punct) -> char {
589 fn spacing(&mut self, punct: Self::Punct) -> Spacing {
590 if punct.joint { Spacing::Joint } else { Spacing::Alone }
593 fn span(&mut self, punct: Self::Punct) -> Self::Span {
597 fn with_span(&mut self, punct: Self::Punct, span: Self::Span) -> Self::Punct {
598 Punct { span, ..punct }
602 impl server::Ident for Rustc<'_, '_> {
603 fn new(&mut self, string: &str, span: Self::Span, is_raw: bool) -> Self::Ident {
604 Ident::new(self.sess(), Symbol::intern(string), is_raw, span)
607 fn span(&mut self, ident: Self::Ident) -> Self::Span {
611 fn with_span(&mut self, ident: Self::Ident, span: Self::Span) -> Self::Ident {
612 Ident { span, ..ident }
616 impl server::Literal for Rustc<'_, '_> {
617 fn from_str(&mut self, s: &str) -> Result<Self::Literal, ()> {
618 let name = FileName::proc_macro_source_code(s);
619 let mut parser = rustc_parse::new_parser_from_source_str(self.sess(), name, s.to_owned());
621 let first_span = parser.token.span.data();
622 let minus_present = parser.eat(&token::BinOp(token::Minus));
624 let lit_span = parser.token.span.data();
625 let token::Literal(mut lit) = parser.token.kind else {
629 // Check no comment or whitespace surrounding the (possibly negative)
630 // literal, or more tokens after it.
631 if (lit_span.hi.0 - first_span.lo.0) as usize != s.len() {
636 // If minus is present, check no comment or whitespace in between it
637 // and the literal token.
638 if first_span.hi.0 != lit_span.lo.0 {
642 // Check literal is a kind we allow to be negated in a proc macro token.
645 | token::LitKind::Byte
646 | token::LitKind::Char
647 | token::LitKind::Str
648 | token::LitKind::StrRaw(_)
649 | token::LitKind::ByteStr
650 | token::LitKind::ByteStrRaw(_)
651 | token::LitKind::Err => return Err(()),
652 token::LitKind::Integer | token::LitKind::Float => {}
655 // Synthesize a new symbol that includes the minus sign.
656 let symbol = Symbol::intern(&s[..1 + lit.symbol.as_str().len()]);
657 lit = token::Lit::new(lit.kind, symbol, lit.suffix);
660 Ok(Literal { lit, span: self.call_site })
663 fn to_string(&mut self, literal: &Self::Literal) -> String {
664 literal.lit.to_string()
667 fn debug_kind(&mut self, literal: &Self::Literal) -> String {
668 format!("{:?}", literal.lit.kind)
671 fn symbol(&mut self, literal: &Self::Literal) -> String {
672 literal.lit.symbol.to_string()
675 fn suffix(&mut self, literal: &Self::Literal) -> Option<String> {
676 literal.lit.suffix.as_ref().map(Symbol::to_string)
679 fn integer(&mut self, n: &str) -> Self::Literal {
680 self.lit(token::Integer, Symbol::intern(n), None)
683 fn typed_integer(&mut self, n: &str, kind: &str) -> Self::Literal {
684 self.lit(token::Integer, Symbol::intern(n), Some(Symbol::intern(kind)))
687 fn float(&mut self, n: &str) -> Self::Literal {
688 self.lit(token::Float, Symbol::intern(n), None)
691 fn f32(&mut self, n: &str) -> Self::Literal {
692 self.lit(token::Float, Symbol::intern(n), Some(sym::f32))
695 fn f64(&mut self, n: &str) -> Self::Literal {
696 self.lit(token::Float, Symbol::intern(n), Some(sym::f64))
699 fn string(&mut self, string: &str) -> Self::Literal {
700 let quoted = format!("{:?}", string);
701 assert!(quoted.starts_with('"') && quoted.ends_with('"'));
702 let symbol = "ed[1..quoted.len() - 1];
703 self.lit(token::Str, Symbol::intern(symbol), None)
706 fn character(&mut self, ch: char) -> Self::Literal {
707 let quoted = format!("{:?}", ch);
708 assert!(quoted.starts_with('\'') && quoted.ends_with('\''));
709 let symbol = "ed[1..quoted.len() - 1];
710 self.lit(token::Char, Symbol::intern(symbol), None)
713 fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
717 .flat_map(ascii::escape_default)
718 .map(Into::<char>::into)
719 .collect::<String>();
720 self.lit(token::ByteStr, Symbol::intern(&string), None)
723 fn span(&mut self, literal: &Self::Literal) -> Self::Span {
727 fn set_span(&mut self, literal: &mut Self::Literal, span: Self::Span) {
733 literal: &Self::Literal,
736 ) -> Option<Self::Span> {
737 let span = literal.span;
738 let length = span.hi().to_usize() - span.lo().to_usize();
740 let start = match start {
741 Bound::Included(lo) => lo,
742 Bound::Excluded(lo) => lo.checked_add(1)?,
743 Bound::Unbounded => 0,
746 let end = match end {
747 Bound::Included(hi) => hi.checked_add(1)?,
748 Bound::Excluded(hi) => hi,
749 Bound::Unbounded => length,
752 // Bounds check the values, preventing addition overflow and OOB spans.
753 if start > u32::MAX as usize
754 || end > u32::MAX as usize
755 || (u32::MAX - start as u32) < span.lo().to_u32()
756 || (u32::MAX - end as u32) < span.lo().to_u32()
763 let new_lo = span.lo() + BytePos::from_usize(start);
764 let new_hi = span.lo() + BytePos::from_usize(end);
765 Some(span.with_lo(new_lo).with_hi(new_hi))
769 impl server::SourceFile for Rustc<'_, '_> {
770 fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
771 Lrc::ptr_eq(file1, file2)
774 fn path(&mut self, file: &Self::SourceFile) -> String {
776 FileName::Real(ref name) => name
778 .expect("attempting to get a file path in an imported file in `proc_macro::SourceFile::path`")
780 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
782 _ => file.name.prefer_local().to_string(),
786 fn is_real(&mut self, file: &Self::SourceFile) -> bool {
791 impl server::MultiSpan for Rustc<'_, '_> {
792 fn new(&mut self) -> Self::MultiSpan {
796 fn push(&mut self, spans: &mut Self::MultiSpan, span: Self::Span) {
801 impl server::Diagnostic for Rustc<'_, '_> {
802 fn new(&mut self, level: Level, msg: &str, spans: Self::MultiSpan) -> Self::Diagnostic {
803 let mut diag = Diagnostic::new(level.to_internal(), msg);
804 diag.set_span(MultiSpan::from_spans(spans));
810 diag: &mut Self::Diagnostic,
813 spans: Self::MultiSpan,
815 diag.sub(level.to_internal(), msg, MultiSpan::from_spans(spans), None);
818 fn emit(&mut self, mut diag: Self::Diagnostic) {
819 self.sess().span_diagnostic.emit_diagnostic(&mut diag);
823 impl server::Span for Rustc<'_, '_> {
824 fn debug(&mut self, span: Self::Span) -> String {
825 if self.ecx.ecfg.span_debug {
826 format!("{:?}", span)
828 format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
832 fn def_site(&mut self) -> Self::Span {
836 fn call_site(&mut self) -> Self::Span {
840 fn mixed_site(&mut self) -> Self::Span {
844 fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
845 self.sess().source_map().lookup_char_pos(span.lo()).file
848 fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
849 span.parent_callsite()
852 fn source(&mut self, span: Self::Span) -> Self::Span {
853 span.source_callsite()
856 fn start(&mut self, span: Self::Span) -> LineColumn {
857 let loc = self.sess().source_map().lookup_char_pos(span.lo());
858 LineColumn { line: loc.line, column: loc.col.to_usize() }
861 fn end(&mut self, span: Self::Span) -> LineColumn {
862 let loc = self.sess().source_map().lookup_char_pos(span.hi());
863 LineColumn { line: loc.line, column: loc.col.to_usize() }
866 fn before(&mut self, span: Self::Span) -> Self::Span {
870 fn after(&mut self, span: Self::Span) -> Self::Span {
874 fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
875 let self_loc = self.sess().source_map().lookup_char_pos(first.lo());
876 let other_loc = self.sess().source_map().lookup_char_pos(second.lo());
878 if self_loc.file.name != other_loc.file.name {
882 Some(first.to(second))
885 fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
886 span.with_ctxt(at.ctxt())
889 fn source_text(&mut self, span: Self::Span) -> Option<String> {
890 self.sess().source_map().span_to_snippet(span).ok()
892 /// Saves the provided span into the metadata of
893 /// *the crate we are currently compiling*, which must
894 /// be a proc-macro crate. This id can be passed to
895 /// `recover_proc_macro_span` when our current crate
896 /// is *run* as a proc-macro.
898 /// Let's suppose that we have two crates - `my_client`
899 /// and `my_proc_macro`. The `my_proc_macro` crate
900 /// contains a procedural macro `my_macro`, which
901 /// is implemented as: `quote! { "hello" }`
903 /// When we *compile* `my_proc_macro`, we will execute
904 /// the `quote` proc-macro. This will save the span of
905 /// "hello" into the metadata of `my_proc_macro`. As a result,
906 /// the body of `my_proc_macro` (after expansion) will end
907 /// up containing a call that looks like this:
908 /// `proc_macro::Ident::new("hello", proc_macro::Span::recover_proc_macro_span(0))`
910 /// where `0` is the id returned by this function.
911 /// When `my_proc_macro` *executes* (during the compilation of `my_client`),
912 /// the call to `recover_proc_macro_span` will load the corresponding
913 /// span from the metadata of `my_proc_macro` (which we have access to,
914 /// since we've loaded `my_proc_macro` from disk in order to execute it).
915 /// In this way, we have obtained a span pointing into `my_proc_macro`
916 fn save_span(&mut self, span: Self::Span) -> usize {
917 self.sess().save_proc_macro_span(span)
920 fn recover_proc_macro_span(&mut self, id: usize) -> Self::Span {
921 let (resolver, krate, def_site) = (&*self.ecx.resolver, self.krate, self.def_site);
922 *self.rebased_spans.entry(id).or_insert_with(|| {
923 // FIXME: `SyntaxContext` for spans from proc macro crates is lost during encoding,
924 // replace it with a def-site context until we are encoding it properly.
925 resolver.get_proc_macro_quoted_span(krate, id).with_ctxt(def_site.ctxt())