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,
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 }
332 fn dollar_crate(span: Span) -> Ident {
333 // `$crate` is accepted as an ident only if it comes from the compiler.
334 Ident { sym: kw::DollarCrate, is_raw: false, span }
338 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
339 #[derive(Clone, Debug)]
345 pub(crate) struct Rustc<'a, 'b> {
346 ecx: &'a mut ExtCtxt<'b>,
351 rebased_spans: FxHashMap<usize, Span>,
354 impl<'a, 'b> Rustc<'a, 'b> {
355 pub fn new(ecx: &'a mut ExtCtxt<'b>) -> Self {
356 let expn_data = ecx.current_expansion.id.expn_data();
358 def_site: ecx.with_def_site_ctxt(expn_data.def_site),
359 call_site: ecx.with_call_site_ctxt(expn_data.call_site),
360 mixed_site: ecx.with_mixed_site_ctxt(expn_data.call_site),
361 krate: expn_data.macro_def_id.unwrap().krate,
362 rebased_spans: FxHashMap::default(),
367 fn sess(&self) -> &ParseSess {
368 self.ecx.parse_sess()
371 fn lit(&mut self, kind: token::LitKind, symbol: Symbol, suffix: Option<Symbol>) -> Literal {
372 Literal { lit: token::Lit::new(kind, symbol, suffix), span: server::Span::call_site(self) }
376 impl server::Types for Rustc<'_, '_> {
377 type FreeFunctions = FreeFunctions;
378 type TokenStream = TokenStream;
382 type Literal = Literal;
383 type SourceFile = Lrc<SourceFile>;
384 type MultiSpan = Vec<Span>;
385 type Diagnostic = Diagnostic;
389 impl server::FreeFunctions for Rustc<'_, '_> {
390 fn track_env_var(&mut self, var: &str, value: Option<&str>) {
394 .insert((Symbol::intern(var), value.map(Symbol::intern)));
397 fn track_path(&mut self, path: &str) {
398 self.sess().file_depinfo.borrow_mut().insert(Symbol::intern(path));
402 impl server::TokenStream for Rustc<'_, '_> {
403 fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
406 fn from_str(&mut self, src: &str) -> Self::TokenStream {
407 parse_stream_from_source_str(
408 FileName::proc_macro_source_code(src),
411 Some(self.call_site),
414 fn to_string(&mut self, stream: &Self::TokenStream) -> String {
415 pprust::tts_to_string(stream)
417 fn expand_expr(&mut self, stream: &Self::TokenStream) -> Result<Self::TokenStream, ()> {
418 // Parse the expression from our tokenstream.
419 let expr: PResult<'_, _> = try {
420 let mut p = rustc_parse::stream_to_parser(
423 Some("proc_macro expand expr"),
425 let expr = p.parse_expr()?;
426 if p.token != token::Eof {
431 let expr = expr.map_err(|mut err| {
435 // Perform eager expansion on the expression.
439 .fully_expand_fragment(crate::expand::AstFragment::Expr(expr))
442 // NOTE: For now, limit `expand_expr` to exclusively expand to literals.
443 // This may be relaxed in the future.
444 // We don't use `TokenStream::from_ast` as the tokenstream currently cannot
445 // be recovered in the general case.
447 ast::ExprKind::Lit(l) => {
448 Ok(tokenstream::TokenTree::token(token::Literal(l.token), l.span).into())
450 ast::ExprKind::Unary(ast::UnOp::Neg, e) => match &e.kind {
451 ast::ExprKind::Lit(l) => match l.token {
452 token::Lit { kind: token::Integer | token::Float, .. } => {
453 Ok(Self::TokenStream::from_iter([
454 // FIXME: The span of the `-` token is lost when
455 // parsing, so we cannot faithfully recover it here.
456 tokenstream::TokenTree::token(token::BinOp(token::Minus), e.span),
457 tokenstream::TokenTree::token(token::Literal(l.token), l.span),
469 tree: TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>,
470 ) -> Self::TokenStream {
475 base: Option<Self::TokenStream>,
476 trees: Vec<TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>>,
477 ) -> Self::TokenStream {
478 let mut builder = tokenstream::TokenStreamBuilder::new();
479 if let Some(base) = base {
483 builder.push(tree.to_internal());
489 base: Option<Self::TokenStream>,
490 streams: Vec<Self::TokenStream>,
491 ) -> Self::TokenStream {
492 let mut builder = tokenstream::TokenStreamBuilder::new();
493 if let Some(base) = base {
496 for stream in streams {
497 builder.push(stream);
503 stream: Self::TokenStream,
504 ) -> Vec<TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>> {
505 // XXX: This is a raw port of the previous approach, and can probably be
507 let mut cursor = stream.into_trees();
508 let mut stack = Vec::new();
509 let mut tts = Vec::new();
511 let next = stack.pop().or_else(|| {
512 let next = cursor.next_with_spacing()?;
513 Some(TokenTree::from_internal((next, &mut stack, self)))
516 Some(TokenTree::Group(group)) => {
517 // A hack used to pass AST fragments to attribute and derive
518 // macros as a single nonterminal token instead of a token
519 // stream. Such token needs to be "unwrapped" and not
520 // represented as a delimited group.
521 // FIXME: It needs to be removed, but there are some
522 // compatibility issues (see #73345).
524 cursor.append(group.stream);
527 tts.push(TokenTree::Group(group));
529 Some(tt) => tts.push(tt),
536 impl server::Group for Rustc<'_, '_> {
537 fn new(&mut self, delimiter: Delimiter, stream: Option<Self::TokenStream>) -> Self::Group {
540 stream: stream.unwrap_or_default(),
541 span: DelimSpan::from_single(server::Span::call_site(self)),
545 fn delimiter(&mut self, group: &Self::Group) -> Delimiter {
548 fn stream(&mut self, group: &Self::Group) -> Self::TokenStream {
551 fn span(&mut self, group: &Self::Group) -> Self::Span {
554 fn span_open(&mut self, group: &Self::Group) -> Self::Span {
557 fn span_close(&mut self, group: &Self::Group) -> Self::Span {
560 fn set_span(&mut self, group: &mut Self::Group, span: Self::Span) {
561 group.span = DelimSpan::from_single(span);
565 impl server::Punct for Rustc<'_, '_> {
566 fn new(&mut self, ch: char, spacing: Spacing) -> Self::Punct {
567 Punct::new(ch, spacing == Spacing::Joint, server::Span::call_site(self))
569 fn as_char(&mut self, punct: Self::Punct) -> char {
572 fn spacing(&mut self, punct: Self::Punct) -> Spacing {
573 if punct.joint { Spacing::Joint } else { Spacing::Alone }
575 fn span(&mut self, punct: Self::Punct) -> Self::Span {
578 fn with_span(&mut self, punct: Self::Punct, span: Self::Span) -> Self::Punct {
579 Punct { span, ..punct }
583 impl server::Ident for Rustc<'_, '_> {
584 fn new(&mut self, string: &str, span: Self::Span, is_raw: bool) -> Self::Ident {
585 Ident::new(self.sess(), Symbol::intern(string), is_raw, span)
587 fn span(&mut self, ident: Self::Ident) -> Self::Span {
590 fn with_span(&mut self, ident: Self::Ident, span: Self::Span) -> Self::Ident {
591 Ident { span, ..ident }
595 impl server::Literal for Rustc<'_, '_> {
596 fn from_str(&mut self, s: &str) -> Result<Self::Literal, ()> {
597 let name = FileName::proc_macro_source_code(s);
598 let mut parser = rustc_parse::new_parser_from_source_str(self.sess(), name, s.to_owned());
600 let first_span = parser.token.span.data();
601 let minus_present = parser.eat(&token::BinOp(token::Minus));
603 let lit_span = parser.token.span.data();
604 let token::Literal(mut lit) = parser.token.kind else {
608 // Check no comment or whitespace surrounding the (possibly negative)
609 // literal, or more tokens after it.
610 if (lit_span.hi.0 - first_span.lo.0) as usize != s.len() {
615 // If minus is present, check no comment or whitespace in between it
616 // and the literal token.
617 if first_span.hi.0 != lit_span.lo.0 {
621 // Check literal is a kind we allow to be negated in a proc macro token.
624 | token::LitKind::Byte
625 | token::LitKind::Char
626 | token::LitKind::Str
627 | token::LitKind::StrRaw(_)
628 | token::LitKind::ByteStr
629 | token::LitKind::ByteStrRaw(_)
630 | token::LitKind::Err => return Err(()),
631 token::LitKind::Integer | token::LitKind::Float => {}
634 // Synthesize a new symbol that includes the minus sign.
635 let symbol = Symbol::intern(&s[..1 + lit.symbol.as_str().len()]);
636 lit = token::Lit::new(lit.kind, symbol, lit.suffix);
639 Ok(Literal { lit, span: self.call_site })
641 fn to_string(&mut self, literal: &Self::Literal) -> String {
642 literal.lit.to_string()
644 fn debug_kind(&mut self, literal: &Self::Literal) -> String {
645 format!("{:?}", literal.lit.kind)
647 fn symbol(&mut self, literal: &Self::Literal) -> String {
648 literal.lit.symbol.to_string()
650 fn suffix(&mut self, literal: &Self::Literal) -> Option<String> {
651 literal.lit.suffix.as_ref().map(Symbol::to_string)
653 fn integer(&mut self, n: &str) -> Self::Literal {
654 self.lit(token::Integer, Symbol::intern(n), None)
656 fn typed_integer(&mut self, n: &str, kind: &str) -> Self::Literal {
657 self.lit(token::Integer, Symbol::intern(n), Some(Symbol::intern(kind)))
659 fn float(&mut self, n: &str) -> Self::Literal {
660 self.lit(token::Float, Symbol::intern(n), None)
662 fn f32(&mut self, n: &str) -> Self::Literal {
663 self.lit(token::Float, Symbol::intern(n), Some(sym::f32))
665 fn f64(&mut self, n: &str) -> Self::Literal {
666 self.lit(token::Float, Symbol::intern(n), Some(sym::f64))
668 fn string(&mut self, string: &str) -> Self::Literal {
669 let quoted = format!("{:?}", string);
670 assert!(quoted.starts_with('"') && quoted.ends_with('"'));
671 let symbol = "ed[1..quoted.len() - 1];
672 self.lit(token::Str, Symbol::intern(symbol), None)
674 fn character(&mut self, ch: char) -> Self::Literal {
675 let quoted = format!("{:?}", ch);
676 assert!(quoted.starts_with('\'') && quoted.ends_with('\''));
677 let symbol = "ed[1..quoted.len() - 1];
678 self.lit(token::Char, Symbol::intern(symbol), None)
680 fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
684 .flat_map(ascii::escape_default)
685 .map(Into::<char>::into)
686 .collect::<String>();
687 self.lit(token::ByteStr, Symbol::intern(&string), None)
689 fn span(&mut self, literal: &Self::Literal) -> Self::Span {
692 fn set_span(&mut self, literal: &mut Self::Literal, span: Self::Span) {
697 literal: &Self::Literal,
700 ) -> Option<Self::Span> {
701 let span = literal.span;
702 let length = span.hi().to_usize() - span.lo().to_usize();
704 let start = match start {
705 Bound::Included(lo) => lo,
706 Bound::Excluded(lo) => lo.checked_add(1)?,
707 Bound::Unbounded => 0,
710 let end = match end {
711 Bound::Included(hi) => hi.checked_add(1)?,
712 Bound::Excluded(hi) => hi,
713 Bound::Unbounded => length,
716 // Bounds check the values, preventing addition overflow and OOB spans.
717 if start > u32::MAX as usize
718 || end > u32::MAX as usize
719 || (u32::MAX - start as u32) < span.lo().to_u32()
720 || (u32::MAX - end as u32) < span.lo().to_u32()
727 let new_lo = span.lo() + BytePos::from_usize(start);
728 let new_hi = span.lo() + BytePos::from_usize(end);
729 Some(span.with_lo(new_lo).with_hi(new_hi))
733 impl server::SourceFile for Rustc<'_, '_> {
734 fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
735 Lrc::ptr_eq(file1, file2)
737 fn path(&mut self, file: &Self::SourceFile) -> String {
739 FileName::Real(ref name) => name
741 .expect("attempting to get a file path in an imported file in `proc_macro::SourceFile::path`")
743 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
745 _ => file.name.prefer_local().to_string(),
748 fn is_real(&mut self, file: &Self::SourceFile) -> bool {
753 impl server::MultiSpan for Rustc<'_, '_> {
754 fn new(&mut self) -> Self::MultiSpan {
757 fn push(&mut self, spans: &mut Self::MultiSpan, span: Self::Span) {
762 impl server::Diagnostic for Rustc<'_, '_> {
763 fn new(&mut self, level: Level, msg: &str, spans: Self::MultiSpan) -> Self::Diagnostic {
764 let mut diag = Diagnostic::new(level.to_internal(), msg);
765 diag.set_span(MultiSpan::from_spans(spans));
770 diag: &mut Self::Diagnostic,
773 spans: Self::MultiSpan,
775 diag.sub(level.to_internal(), msg, MultiSpan::from_spans(spans), None);
777 fn emit(&mut self, mut diag: Self::Diagnostic) {
778 self.sess().span_diagnostic.emit_diagnostic(&mut diag);
782 impl server::Span for Rustc<'_, '_> {
783 fn debug(&mut self, span: Self::Span) -> String {
784 if self.ecx.ecfg.span_debug {
785 format!("{:?}", span)
787 format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
790 fn def_site(&mut self) -> Self::Span {
793 fn call_site(&mut self) -> Self::Span {
796 fn mixed_site(&mut self) -> Self::Span {
799 fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
800 self.sess().source_map().lookup_char_pos(span.lo()).file
802 fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
803 span.parent_callsite()
805 fn source(&mut self, span: Self::Span) -> Self::Span {
806 span.source_callsite()
808 fn start(&mut self, span: Self::Span) -> LineColumn {
809 let loc = self.sess().source_map().lookup_char_pos(span.lo());
810 LineColumn { line: loc.line, column: loc.col.to_usize() }
812 fn end(&mut self, span: Self::Span) -> LineColumn {
813 let loc = self.sess().source_map().lookup_char_pos(span.hi());
814 LineColumn { line: loc.line, column: loc.col.to_usize() }
816 fn before(&mut self, span: Self::Span) -> Self::Span {
819 fn after(&mut self, span: Self::Span) -> Self::Span {
822 fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
823 let self_loc = self.sess().source_map().lookup_char_pos(first.lo());
824 let other_loc = self.sess().source_map().lookup_char_pos(second.lo());
826 if self_loc.file.name != other_loc.file.name {
830 Some(first.to(second))
832 fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
833 span.with_ctxt(at.ctxt())
835 fn source_text(&mut self, span: Self::Span) -> Option<String> {
836 self.sess().source_map().span_to_snippet(span).ok()
838 /// Saves the provided span into the metadata of
839 /// *the crate we are currently compiling*, which must
840 /// be a proc-macro crate. This id can be passed to
841 /// `recover_proc_macro_span` when our current crate
842 /// is *run* as a proc-macro.
844 /// Let's suppose that we have two crates - `my_client`
845 /// and `my_proc_macro`. The `my_proc_macro` crate
846 /// contains a procedural macro `my_macro`, which
847 /// is implemented as: `quote! { "hello" }`
849 /// When we *compile* `my_proc_macro`, we will execute
850 /// the `quote` proc-macro. This will save the span of
851 /// "hello" into the metadata of `my_proc_macro`. As a result,
852 /// the body of `my_proc_macro` (after expansion) will end
853 /// up containing a call that looks like this:
854 /// `proc_macro::Ident::new("hello", proc_macro::Span::recover_proc_macro_span(0))`
856 /// where `0` is the id returned by this function.
857 /// When `my_proc_macro` *executes* (during the compilation of `my_client`),
858 /// the call to `recover_proc_macro_span` will load the corresponding
859 /// span from the metadata of `my_proc_macro` (which we have access to,
860 /// since we've loaded `my_proc_macro` from disk in order to execute it).
861 /// In this way, we have obtained a span pointing into `my_proc_macro`
862 fn save_span(&mut self, span: Self::Span) -> usize {
863 self.sess().save_proc_macro_span(span)
865 fn recover_proc_macro_span(&mut self, id: usize) -> Self::Span {
866 let (resolver, krate, def_site) = (&*self.ecx.resolver, self.krate, self.def_site);
867 *self.rebased_spans.entry(id).or_insert_with(|| {
868 // FIXME: `SyntaxContext` for spans from proc macro crates is lost during encoding,
869 // replace it with a def-site context until we are encoding it properly.
870 resolver.get_proc_macro_quoted_span(krate, id).with_ctxt(def_site.ctxt())