1 use crate::base::ExtCtxt;
5 use rustc_ast::tokenstream::{self, CanSynthesizeMissingTokens};
6 use rustc_ast::tokenstream::{DelimSpan, Spacing::*, TokenStream, TreeAndSpacing};
7 use rustc_ast_pretty::pprust;
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc_data_structures::sync::Lrc;
10 use rustc_errors::{Diagnostic, MultiSpan, PResult};
11 use rustc_parse::lexer::nfc_normalize;
12 use rustc_parse::{nt_to_tokenstream, parse_stream_from_source_str};
13 use rustc_session::parse::ParseSess;
14 use rustc_span::def_id::CrateNum;
15 use rustc_span::symbol::{self, kw, sym, Symbol};
16 use rustc_span::{BytePos, FileName, Pos, SourceFile, Span};
18 use pm::bridge::{server, TokenTree};
19 use pm::{Delimiter, Level, LineColumn, Spacing};
21 use std::{ascii, panic};
23 trait FromInternal<T> {
24 fn from_internal(x: T) -> Self;
28 fn to_internal(self) -> T;
31 impl FromInternal<token::Delimiter> for Delimiter {
32 fn from_internal(delim: token::Delimiter) -> Delimiter {
34 token::Delimiter::Parenthesis => Delimiter::Parenthesis,
35 token::Delimiter::Brace => Delimiter::Brace,
36 token::Delimiter::Bracket => Delimiter::Bracket,
37 token::Delimiter::Invisible => Delimiter::None,
42 impl ToInternal<token::Delimiter> for Delimiter {
43 fn to_internal(self) -> token::Delimiter {
45 Delimiter::Parenthesis => token::Delimiter::Parenthesis,
46 Delimiter::Brace => token::Delimiter::Brace,
47 Delimiter::Bracket => token::Delimiter::Bracket,
48 Delimiter::None => token::Delimiter::Invisible,
53 impl FromInternal<(TreeAndSpacing, &'_ mut Vec<Self>, &mut Rustc<'_, '_>)>
54 for TokenTree<Group, Punct, Ident, Literal>
57 ((tree, spacing), stack, rustc): (TreeAndSpacing, &mut Vec<Self>, &mut Rustc<'_, '_>),
59 use rustc_ast::token::*;
61 let joint = spacing == Joint;
62 let Token { kind, span } = match tree {
63 tokenstream::TokenTree::Delimited(span, delim, tts) => {
64 let delimiter = pm::Delimiter::from_internal(delim);
65 return TokenTree::Group(Group { delimiter, stream: tts, span, flatten: false });
67 tokenstream::TokenTree::Token(token) => token,
71 ($ty:ident { $($field:ident $(: $value:expr)*),+ $(,)? }) => (
72 TokenTree::$ty(self::$ty {
73 $($field $(: $value)*,)+
77 ($ty:ident::$method:ident($($value:expr),*)) => (
78 TokenTree::$ty(self::$ty::$method($($value,)* span))
83 tt!(Punct::new($a, joint))
85 ($a:expr, $b:expr) => {{
86 stack.push(tt!(Punct::new($b, joint)));
87 tt!(Punct::new($a, true))
89 ($a:expr, $b:expr, $c:expr) => {{
90 stack.push(tt!(Punct::new($c, joint)));
91 stack.push(tt!(Punct::new($b, true)));
92 tt!(Punct::new($a, true))
100 EqEq => op!('=', '='),
104 AndAnd => op!('&', '&'),
105 OrOr => op!('|', '|'),
108 BinOp(Plus) => op!('+'),
109 BinOp(Minus) => op!('-'),
110 BinOp(Star) => op!('*'),
111 BinOp(Slash) => op!('/'),
112 BinOp(Percent) => op!('%'),
113 BinOp(Caret) => op!('^'),
114 BinOp(And) => op!('&'),
115 BinOp(Or) => op!('|'),
116 BinOp(Shl) => op!('<', '<'),
117 BinOp(Shr) => op!('>', '>'),
118 BinOpEq(Plus) => op!('+', '='),
119 BinOpEq(Minus) => op!('-', '='),
120 BinOpEq(Star) => op!('*', '='),
121 BinOpEq(Slash) => op!('/', '='),
122 BinOpEq(Percent) => op!('%', '='),
123 BinOpEq(Caret) => op!('^', '='),
124 BinOpEq(And) => op!('&', '='),
125 BinOpEq(Or) => op!('|', '='),
126 BinOpEq(Shl) => op!('<', '<', '='),
127 BinOpEq(Shr) => op!('>', '>', '='),
130 DotDot => op!('.', '.'),
131 DotDotDot => op!('.', '.', '.'),
132 DotDotEq => op!('.', '.', '='),
136 ModSep => op!(':', ':'),
137 RArrow => op!('-', '>'),
138 LArrow => op!('<', '-'),
139 FatArrow => op!('=', '>'),
142 Question => op!('?'),
143 SingleQuote => op!('\''),
145 Ident(name, false) if name == kw::DollarCrate => tt!(Ident::dollar_crate()),
146 Ident(name, is_raw) => tt!(Ident::new(rustc.sess(), name, is_raw)),
148 let ident = symbol::Ident::new(name, span).without_first_quote();
149 stack.push(tt!(Ident::new(rustc.sess(), ident.name, false)));
150 tt!(Punct::new('\'', true))
152 Literal(lit) => tt!(Literal { lit }),
153 DocComment(_, attr_style, data) => {
154 let mut escaped = String::new();
155 for ch in data.as_str().chars() {
156 escaped.extend(ch.escape_debug());
159 Ident(sym::doc, false),
161 TokenKind::lit(token::Str, Symbol::intern(&escaped), None),
164 .map(|kind| tokenstream::TokenTree::token(kind, span))
166 stack.push(TokenTree::Group(Group {
167 delimiter: pm::Delimiter::Bracket,
169 span: DelimSpan::from_single(span),
172 if attr_style == ast::AttrStyle::Inner {
173 stack.push(tt!(Punct::new('!', false)));
175 tt!(Punct::new('#', false))
178 Interpolated(nt) if let NtIdent(ident, is_raw) = *nt => {
179 TokenTree::Ident(Ident::new(rustc.sess(), ident.name, is_raw, ident.span))
181 Interpolated(nt) => {
182 let stream = nt_to_tokenstream(&nt, rustc.sess(), CanSynthesizeMissingTokens::No);
183 TokenTree::Group(Group {
184 delimiter: pm::Delimiter::None,
186 span: DelimSpan::from_single(span),
187 flatten: crate::base::nt_pretty_printing_compatibility_hack(&nt, rustc.sess()),
191 OpenDelim(..) | CloseDelim(..) => unreachable!(),
192 Eof => unreachable!(),
197 impl ToInternal<TokenStream> for TokenTree<Group, Punct, Ident, Literal> {
198 fn to_internal(self) -> TokenStream {
199 use rustc_ast::token::*;
201 let (ch, joint, span) = match self {
202 TokenTree::Punct(Punct { ch, joint, span }) => (ch, joint, span),
203 TokenTree::Group(Group { delimiter, stream, span, .. }) => {
204 return tokenstream::TokenTree::Delimited(span, delimiter.to_internal(), stream)
207 TokenTree::Ident(self::Ident { sym, is_raw, span }) => {
208 return tokenstream::TokenTree::token(Ident(sym, is_raw), span).into();
210 TokenTree::Literal(self::Literal {
211 lit: token::Lit { kind: token::Integer, symbol, suffix },
213 }) if symbol.as_str().starts_with('-') => {
214 let minus = BinOp(BinOpToken::Minus);
215 let symbol = Symbol::intern(&symbol.as_str()[1..]);
216 let integer = TokenKind::lit(token::Integer, symbol, suffix);
217 let a = tokenstream::TokenTree::token(minus, span);
218 let b = tokenstream::TokenTree::token(integer, span);
219 return [a, b].into_iter().collect();
221 TokenTree::Literal(self::Literal {
222 lit: token::Lit { kind: token::Float, symbol, suffix },
224 }) if symbol.as_str().starts_with('-') => {
225 let minus = BinOp(BinOpToken::Minus);
226 let symbol = Symbol::intern(&symbol.as_str()[1..]);
227 let float = TokenKind::lit(token::Float, symbol, suffix);
228 let a = tokenstream::TokenTree::token(minus, span);
229 let b = tokenstream::TokenTree::token(float, span);
230 return [a, b].into_iter().collect();
232 TokenTree::Literal(self::Literal { lit, span }) => {
233 return tokenstream::TokenTree::token(Literal(lit), span).into();
237 let kind = match ch {
247 '%' => BinOp(Percent),
263 let tree = tokenstream::TokenTree::token(kind, span);
264 TokenStream::new(vec![(tree, if joint { Joint } else { Alone })])
268 impl ToInternal<rustc_errors::Level> for Level {
269 fn to_internal(self) -> rustc_errors::Level {
271 Level::Error => rustc_errors::Level::Error { lint: false },
272 Level::Warning => rustc_errors::Level::Warning,
273 Level::Note => rustc_errors::Level::Note,
274 Level::Help => rustc_errors::Level::Help,
275 _ => unreachable!("unknown proc_macro::Level variant: {:?}", self),
280 pub struct FreeFunctions;
283 pub struct TokenStreamIter {
284 cursor: tokenstream::Cursor,
285 stack: Vec<TokenTree<Group, Punct, Ident, Literal>>,
290 delimiter: Delimiter,
293 /// A hack used to pass AST fragments to attribute and derive macros
294 /// as a single nonterminal token instead of a token stream.
295 /// FIXME: It needs to be removed, but there are some compatibility issues (see #73345).
299 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
302 // NB. not using `Spacing` here because it doesn't implement `Hash`.
308 fn new(ch: char, joint: bool, span: Span) -> Punct {
309 const LEGAL_CHARS: &[char] = &[
310 '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
311 ':', '#', '$', '?', '\'',
313 if !LEGAL_CHARS.contains(&ch) {
314 panic!("unsupported character `{:?}`", ch)
316 Punct { ch, joint, span }
320 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
328 fn new(sess: &ParseSess, sym: Symbol, is_raw: bool, span: Span) -> Ident {
329 let sym = nfc_normalize(sym.as_str());
330 let string = sym.as_str();
331 if !rustc_lexer::is_ident(string) {
332 panic!("`{:?}` is not a valid identifier", string)
334 if is_raw && !sym.can_be_raw() {
335 panic!("`{}` cannot be a raw identifier", string);
337 sess.symbol_gallery.insert(sym, span);
338 Ident { sym, is_raw, span }
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 }
346 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
347 #[derive(Clone, Debug)]
353 pub(crate) struct Rustc<'a, 'b> {
354 ecx: &'a mut ExtCtxt<'b>,
359 rebased_spans: FxHashMap<usize, Span>,
362 impl<'a, 'b> Rustc<'a, 'b> {
363 pub fn new(ecx: &'a mut ExtCtxt<'b>) -> Self {
364 let expn_data = ecx.current_expansion.id.expn_data();
366 def_site: ecx.with_def_site_ctxt(expn_data.def_site),
367 call_site: ecx.with_call_site_ctxt(expn_data.call_site),
368 mixed_site: ecx.with_mixed_site_ctxt(expn_data.call_site),
369 krate: expn_data.macro_def_id.unwrap().krate,
370 rebased_spans: FxHashMap::default(),
375 fn sess(&self) -> &ParseSess {
376 self.ecx.parse_sess()
379 fn lit(&mut self, kind: token::LitKind, symbol: Symbol, suffix: Option<Symbol>) -> Literal {
380 Literal { lit: token::Lit::new(kind, symbol, suffix), span: server::Span::call_site(self) }
384 impl server::Types for Rustc<'_, '_> {
385 type FreeFunctions = FreeFunctions;
386 type TokenStream = TokenStream;
387 type TokenStreamBuilder = tokenstream::TokenStreamBuilder;
388 type TokenStreamIter = TokenStreamIter;
392 type Literal = Literal;
393 type SourceFile = Lrc<SourceFile>;
394 type MultiSpan = Vec<Span>;
395 type Diagnostic = Diagnostic;
399 impl server::FreeFunctions for Rustc<'_, '_> {
400 fn track_env_var(&mut self, var: &str, value: Option<&str>) {
404 .insert((Symbol::intern(var), value.map(Symbol::intern)));
407 fn track_path(&mut self, path: &str) {
408 self.sess().file_depinfo.borrow_mut().insert(Symbol::intern(path));
412 impl server::TokenStream for Rustc<'_, '_> {
413 fn new(&mut self) -> Self::TokenStream {
414 TokenStream::default()
416 fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
419 fn from_str(&mut self, src: &str) -> Self::TokenStream {
420 parse_stream_from_source_str(
421 FileName::proc_macro_source_code(src),
424 Some(self.call_site),
427 fn to_string(&mut self, stream: &Self::TokenStream) -> String {
428 pprust::tts_to_string(stream)
430 fn expand_expr(&mut self, stream: &Self::TokenStream) -> Result<Self::TokenStream, ()> {
431 // Parse the expression from our tokenstream.
432 let expr: PResult<'_, _> = try {
433 let mut p = rustc_parse::stream_to_parser(
436 Some("proc_macro expand expr"),
438 let expr = p.parse_expr()?;
439 if p.token != token::Eof {
444 let expr = expr.map_err(|mut err| {
448 // Perform eager expansion on the expression.
452 .fully_expand_fragment(crate::expand::AstFragment::Expr(expr))
455 // NOTE: For now, limit `expand_expr` to exclusively expand to literals.
456 // This may be relaxed in the future.
457 // We don't use `nt_to_tokenstream` as the tokenstream currently cannot
458 // be recovered in the general case.
460 ast::ExprKind::Lit(l) => {
461 Ok(tokenstream::TokenTree::token(token::Literal(l.token), l.span).into())
463 ast::ExprKind::Unary(ast::UnOp::Neg, e) => match &e.kind {
464 ast::ExprKind::Lit(l) => match l.token {
465 token::Lit { kind: token::Integer | token::Float, .. } => {
466 Ok(Self::TokenStream::from_iter([
467 // FIXME: The span of the `-` token is lost when
468 // parsing, so we cannot faithfully recover it here.
469 tokenstream::TokenTree::token(token::BinOp(token::Minus), e.span),
470 tokenstream::TokenTree::token(token::Literal(l.token), l.span),
482 tree: TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>,
483 ) -> Self::TokenStream {
486 fn into_iter(&mut self, stream: Self::TokenStream) -> Self::TokenStreamIter {
487 TokenStreamIter { cursor: stream.into_trees(), stack: vec![] }
491 impl server::TokenStreamBuilder for Rustc<'_, '_> {
492 fn new(&mut self) -> Self::TokenStreamBuilder {
493 tokenstream::TokenStreamBuilder::new()
495 fn push(&mut self, builder: &mut Self::TokenStreamBuilder, stream: Self::TokenStream) {
496 builder.push(stream);
498 fn build(&mut self, builder: Self::TokenStreamBuilder) -> Self::TokenStream {
503 impl server::TokenStreamIter for Rustc<'_, '_> {
506 iter: &mut Self::TokenStreamIter,
507 ) -> Option<TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>> {
509 let tree = iter.stack.pop().or_else(|| {
510 let next = iter.cursor.next_with_spacing()?;
511 Some(TokenTree::from_internal((next, &mut iter.stack, self)))
513 // A hack used to pass AST fragments to attribute and derive macros
514 // as a single nonterminal token instead of a token stream.
515 // Such token needs to be "unwrapped" and not represented as a delimited group.
516 // FIXME: It needs to be removed, but there are some compatibility issues (see #73345).
517 if let TokenTree::Group(ref group) = tree {
519 iter.cursor.append(group.stream.clone());
528 impl server::Group for Rustc<'_, '_> {
529 fn new(&mut self, delimiter: Delimiter, stream: Self::TokenStream) -> Self::Group {
533 span: DelimSpan::from_single(server::Span::call_site(self)),
537 fn delimiter(&mut self, group: &Self::Group) -> Delimiter {
540 fn stream(&mut self, group: &Self::Group) -> Self::TokenStream {
543 fn span(&mut self, group: &Self::Group) -> Self::Span {
546 fn span_open(&mut self, group: &Self::Group) -> Self::Span {
549 fn span_close(&mut self, group: &Self::Group) -> Self::Span {
552 fn set_span(&mut self, group: &mut Self::Group, span: Self::Span) {
553 group.span = DelimSpan::from_single(span);
557 impl server::Punct for Rustc<'_, '_> {
558 fn new(&mut self, ch: char, spacing: Spacing) -> Self::Punct {
559 Punct::new(ch, spacing == Spacing::Joint, server::Span::call_site(self))
561 fn as_char(&mut self, punct: Self::Punct) -> char {
564 fn spacing(&mut self, punct: Self::Punct) -> Spacing {
565 if punct.joint { Spacing::Joint } else { Spacing::Alone }
567 fn span(&mut self, punct: Self::Punct) -> Self::Span {
570 fn with_span(&mut self, punct: Self::Punct, span: Self::Span) -> Self::Punct {
571 Punct { span, ..punct }
575 impl server::Ident for Rustc<'_, '_> {
576 fn new(&mut self, string: &str, span: Self::Span, is_raw: bool) -> Self::Ident {
577 Ident::new(self.sess(), Symbol::intern(string), is_raw, span)
579 fn span(&mut self, ident: Self::Ident) -> Self::Span {
582 fn with_span(&mut self, ident: Self::Ident, span: Self::Span) -> Self::Ident {
583 Ident { span, ..ident }
587 impl server::Literal for Rustc<'_, '_> {
588 fn from_str(&mut self, s: &str) -> Result<Self::Literal, ()> {
589 let name = FileName::proc_macro_source_code(s);
590 let mut parser = rustc_parse::new_parser_from_source_str(self.sess(), name, s.to_owned());
592 let first_span = parser.token.span.data();
593 let minus_present = parser.eat(&token::BinOp(token::Minus));
595 let lit_span = parser.token.span.data();
596 let token::Literal(mut lit) = parser.token.kind else {
600 // Check no comment or whitespace surrounding the (possibly negative)
601 // literal, or more tokens after it.
602 if (lit_span.hi.0 - first_span.lo.0) as usize != s.len() {
607 // If minus is present, check no comment or whitespace in between it
608 // and the literal token.
609 if first_span.hi.0 != lit_span.lo.0 {
613 // Check literal is a kind we allow to be negated in a proc macro token.
616 | token::LitKind::Byte
617 | token::LitKind::Char
618 | token::LitKind::Str
619 | token::LitKind::StrRaw(_)
620 | token::LitKind::ByteStr
621 | token::LitKind::ByteStrRaw(_)
622 | token::LitKind::Err => return Err(()),
623 token::LitKind::Integer | token::LitKind::Float => {}
626 // Synthesize a new symbol that includes the minus sign.
627 let symbol = Symbol::intern(&s[..1 + lit.symbol.as_str().len()]);
628 lit = token::Lit::new(lit.kind, symbol, lit.suffix);
631 Ok(Literal { lit, span: self.call_site })
633 fn to_string(&mut self, literal: &Self::Literal) -> String {
634 literal.lit.to_string()
636 fn debug_kind(&mut self, literal: &Self::Literal) -> String {
637 format!("{:?}", literal.lit.kind)
639 fn symbol(&mut self, literal: &Self::Literal) -> String {
640 literal.lit.symbol.to_string()
642 fn suffix(&mut self, literal: &Self::Literal) -> Option<String> {
643 literal.lit.suffix.as_ref().map(Symbol::to_string)
645 fn integer(&mut self, n: &str) -> Self::Literal {
646 self.lit(token::Integer, Symbol::intern(n), None)
648 fn typed_integer(&mut self, n: &str, kind: &str) -> Self::Literal {
649 self.lit(token::Integer, Symbol::intern(n), Some(Symbol::intern(kind)))
651 fn float(&mut self, n: &str) -> Self::Literal {
652 self.lit(token::Float, Symbol::intern(n), None)
654 fn f32(&mut self, n: &str) -> Self::Literal {
655 self.lit(token::Float, Symbol::intern(n), Some(sym::f32))
657 fn f64(&mut self, n: &str) -> Self::Literal {
658 self.lit(token::Float, Symbol::intern(n), Some(sym::f64))
660 fn string(&mut self, string: &str) -> Self::Literal {
661 let quoted = format!("{:?}", string);
662 assert!(quoted.starts_with('"') && quoted.ends_with('"'));
663 let symbol = "ed[1..quoted.len() - 1];
664 self.lit(token::Str, Symbol::intern(symbol), None)
666 fn character(&mut self, ch: char) -> Self::Literal {
667 let quoted = format!("{:?}", ch);
668 assert!(quoted.starts_with('\'') && quoted.ends_with('\''));
669 let symbol = "ed[1..quoted.len() - 1];
670 self.lit(token::Char, Symbol::intern(symbol), None)
672 fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
676 .flat_map(ascii::escape_default)
677 .map(Into::<char>::into)
678 .collect::<String>();
679 self.lit(token::ByteStr, Symbol::intern(&string), None)
681 fn span(&mut self, literal: &Self::Literal) -> Self::Span {
684 fn set_span(&mut self, literal: &mut Self::Literal, span: Self::Span) {
689 literal: &Self::Literal,
692 ) -> Option<Self::Span> {
693 let span = literal.span;
694 let length = span.hi().to_usize() - span.lo().to_usize();
696 let start = match start {
697 Bound::Included(lo) => lo,
698 Bound::Excluded(lo) => lo.checked_add(1)?,
699 Bound::Unbounded => 0,
702 let end = match end {
703 Bound::Included(hi) => hi.checked_add(1)?,
704 Bound::Excluded(hi) => hi,
705 Bound::Unbounded => length,
708 // Bounds check the values, preventing addition overflow and OOB spans.
709 if start > u32::MAX as usize
710 || end > u32::MAX as usize
711 || (u32::MAX - start as u32) < span.lo().to_u32()
712 || (u32::MAX - end as u32) < span.lo().to_u32()
719 let new_lo = span.lo() + BytePos::from_usize(start);
720 let new_hi = span.lo() + BytePos::from_usize(end);
721 Some(span.with_lo(new_lo).with_hi(new_hi))
725 impl server::SourceFile for Rustc<'_, '_> {
726 fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
727 Lrc::ptr_eq(file1, file2)
729 fn path(&mut self, file: &Self::SourceFile) -> String {
731 FileName::Real(ref name) => name
733 .expect("attempting to get a file path in an imported file in `proc_macro::SourceFile::path`")
735 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
737 _ => file.name.prefer_local().to_string(),
740 fn is_real(&mut self, file: &Self::SourceFile) -> bool {
745 impl server::MultiSpan for Rustc<'_, '_> {
746 fn new(&mut self) -> Self::MultiSpan {
749 fn push(&mut self, spans: &mut Self::MultiSpan, span: Self::Span) {
754 impl server::Diagnostic for Rustc<'_, '_> {
755 fn new(&mut self, level: Level, msg: &str, spans: Self::MultiSpan) -> Self::Diagnostic {
756 let mut diag = Diagnostic::new(level.to_internal(), msg);
757 diag.set_span(MultiSpan::from_spans(spans));
762 diag: &mut Self::Diagnostic,
765 spans: Self::MultiSpan,
767 diag.sub(level.to_internal(), msg, MultiSpan::from_spans(spans), None);
769 fn emit(&mut self, mut diag: Self::Diagnostic) {
770 self.sess().span_diagnostic.emit_diagnostic(&mut diag);
774 impl server::Span for Rustc<'_, '_> {
775 fn debug(&mut self, span: Self::Span) -> String {
776 if self.ecx.ecfg.span_debug {
777 format!("{:?}", span)
779 format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
782 fn def_site(&mut self) -> Self::Span {
785 fn call_site(&mut self) -> Self::Span {
788 fn mixed_site(&mut self) -> Self::Span {
791 fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
792 self.sess().source_map().lookup_char_pos(span.lo()).file
794 fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
795 span.parent_callsite()
797 fn source(&mut self, span: Self::Span) -> Self::Span {
798 span.source_callsite()
800 fn start(&mut self, span: Self::Span) -> LineColumn {
801 let loc = self.sess().source_map().lookup_char_pos(span.lo());
802 LineColumn { line: loc.line, column: loc.col.to_usize() }
804 fn end(&mut self, span: Self::Span) -> LineColumn {
805 let loc = self.sess().source_map().lookup_char_pos(span.hi());
806 LineColumn { line: loc.line, column: loc.col.to_usize() }
808 fn before(&mut self, span: Self::Span) -> Self::Span {
811 fn after(&mut self, span: Self::Span) -> Self::Span {
814 fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
815 let self_loc = self.sess().source_map().lookup_char_pos(first.lo());
816 let other_loc = self.sess().source_map().lookup_char_pos(second.lo());
818 if self_loc.file.name != other_loc.file.name {
822 Some(first.to(second))
824 fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
825 span.with_ctxt(at.ctxt())
827 fn source_text(&mut self, span: Self::Span) -> Option<String> {
828 self.sess().source_map().span_to_snippet(span).ok()
830 /// Saves the provided span into the metadata of
831 /// *the crate we are currently compiling*, which must
832 /// be a proc-macro crate. This id can be passed to
833 /// `recover_proc_macro_span` when our current crate
834 /// is *run* as a proc-macro.
836 /// Let's suppose that we have two crates - `my_client`
837 /// and `my_proc_macro`. The `my_proc_macro` crate
838 /// contains a procedural macro `my_macro`, which
839 /// is implemented as: `quote! { "hello" }`
841 /// When we *compile* `my_proc_macro`, we will execute
842 /// the `quote` proc-macro. This will save the span of
843 /// "hello" into the metadata of `my_proc_macro`. As a result,
844 /// the body of `my_proc_macro` (after expansion) will end
845 /// up containing a call that looks like this:
846 /// `proc_macro::Ident::new("hello", proc_macro::Span::recover_proc_macro_span(0))`
848 /// where `0` is the id returned by this function.
849 /// When `my_proc_macro` *executes* (during the compilation of `my_client`),
850 /// the call to `recover_proc_macro_span` will load the corresponding
851 /// span from the metadata of `my_proc_macro` (which we have access to,
852 /// since we've loaded `my_proc_macro` from disk in order to execute it).
853 /// In this way, we have obtained a span pointing into `my_proc_macro`
854 fn save_span(&mut self, span: Self::Span) -> usize {
855 self.sess().save_proc_macro_span(span)
857 fn recover_proc_macro_span(&mut self, id: usize) -> Self::Span {
858 let (resolver, krate, def_site) = (&*self.ecx.resolver, self.krate, self.def_site);
859 *self.rebased_spans.entry(id).or_insert_with(|| {
860 // FIXME: `SyntaxContext` for spans from proc macro crates is lost during encoding,
861 // replace it with a def-site context until we are encoding it properly.
862 resolver.get_proc_macro_quoted_span(krate, id).with_ctxt(def_site.ctxt())