1 use crate::base::ExtCtxt;
3 server, DelimSpan, Diagnostic, ExpnGlobals, Group, Ident, LitKind, Literal, Punct, TokenTree,
5 use pm::{Delimiter, Level, LineColumn};
8 use rustc_ast::tokenstream::{self, Spacing::*, TokenStream};
9 use rustc_ast::util::literal::escape_byte_str_symbol;
10 use rustc_ast_pretty::pprust;
11 use rustc_data_structures::fx::FxHashMap;
12 use rustc_data_structures::sync::Lrc;
13 use rustc_errors::{MultiSpan, PResult};
14 use rustc_parse::lexer::nfc_normalize;
15 use rustc_parse::parse_stream_from_source_str;
16 use rustc_session::parse::ParseSess;
17 use rustc_span::def_id::CrateNum;
18 use rustc_span::symbol::{self, sym, Symbol};
19 use rustc_span::{BytePos, FileName, Pos, SourceFile, Span};
20 use smallvec::{smallvec, SmallVec};
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<token::LitKind> for LitKind {
54 fn from_internal(kind: token::LitKind) -> Self {
56 token::Byte => LitKind::Byte,
57 token::Char => LitKind::Char,
58 token::Integer => LitKind::Integer,
59 token::Float => LitKind::Float,
60 token::Str => LitKind::Str,
61 token::StrRaw(n) => LitKind::StrRaw(n),
62 token::ByteStr => LitKind::ByteStr,
63 token::ByteStrRaw(n) => LitKind::ByteStrRaw(n),
64 token::Err => LitKind::Err,
65 token::Bool => unreachable!(),
70 impl ToInternal<token::LitKind> for LitKind {
71 fn to_internal(self) -> token::LitKind {
73 LitKind::Byte => token::Byte,
74 LitKind::Char => token::Char,
75 LitKind::Integer => token::Integer,
76 LitKind::Float => token::Float,
77 LitKind::Str => token::Str,
78 LitKind::StrRaw(n) => token::StrRaw(n),
79 LitKind::ByteStr => token::ByteStr,
80 LitKind::ByteStrRaw(n) => token::ByteStrRaw(n),
81 LitKind::Err => token::Err,
86 impl FromInternal<(TokenStream, &mut Rustc<'_, '_>)> for Vec<TokenTree<TokenStream, Span, Symbol>> {
87 fn from_internal((stream, rustc): (TokenStream, &mut Rustc<'_, '_>)) -> Self {
88 use rustc_ast::token::*;
90 // Estimate the capacity as `stream.len()` rounded up to the next power
91 // of two to limit the number of required reallocations.
92 let mut trees = Vec::with_capacity(stream.len().next_power_of_two());
93 let mut cursor = stream.into_trees();
95 while let Some(tree) = cursor.next() {
96 let (Token { kind, span }, joint) = match tree {
97 tokenstream::TokenTree::Delimited(span, delim, tts) => {
98 let delimiter = pm::Delimiter::from_internal(delim);
99 trees.push(TokenTree::Group(Group {
105 entire: span.entire(),
110 tokenstream::TokenTree::Token(token, spacing) => (token, spacing == Joint),
113 // Split the operator into one or more `Punct`s, one per character.
114 // The final one inherits the jointness of the original token. Any
115 // before that get `joint = true`.
116 let mut op = |s: &str| {
117 assert!(s.is_ascii());
118 trees.extend(s.bytes().enumerate().map(|(i, ch)| {
119 let is_final = i == s.len() - 1;
120 // Split the token span into single chars. Unless the span
121 // is an unusual one, e.g. due to proc macro expansion. We
122 // determine this by assuming any span with a length that
123 // matches the operator length is a normal one, and any
124 // span with a different length is an unusual one.
125 let span = if (span.hi() - span.lo()).to_usize() == s.len() {
126 let lo = span.lo() + BytePos::from_usize(i);
127 let hi = lo + BytePos::from_usize(1);
128 span.with_lo(lo).with_hi(hi)
132 TokenTree::Punct(Punct { ch, joint: if is_final { joint } else { true }, span })
148 BinOp(Plus) => op("+"),
149 BinOp(Minus) => op("-"),
150 BinOp(Star) => op("*"),
151 BinOp(Slash) => op("/"),
152 BinOp(Percent) => op("%"),
153 BinOp(Caret) => op("^"),
154 BinOp(And) => op("&"),
155 BinOp(Or) => op("|"),
156 BinOp(Shl) => op("<<"),
157 BinOp(Shr) => op(">>"),
158 BinOpEq(Plus) => op("+="),
159 BinOpEq(Minus) => op("-="),
160 BinOpEq(Star) => op("*="),
161 BinOpEq(Slash) => op("/="),
162 BinOpEq(Percent) => op("%="),
163 BinOpEq(Caret) => op("^="),
164 BinOpEq(And) => op("&="),
165 BinOpEq(Or) => op("|="),
166 BinOpEq(Shl) => op("<<="),
167 BinOpEq(Shr) => op(">>="),
171 DotDotDot => op("..."),
172 DotDotEq => op("..="),
179 FatArrow => op("=>"),
183 SingleQuote => op("'"),
185 Ident(sym, is_raw) => trees.push(TokenTree::Ident(Ident { sym, is_raw, span })),
187 let ident = symbol::Ident::new(name, span).without_first_quote();
189 TokenTree::Punct(Punct { ch: b'\'', joint: true, span }),
190 TokenTree::Ident(Ident { sym: ident.name, is_raw: false, span }),
193 Literal(token::Lit { kind, symbol, suffix }) => {
194 trees.push(TokenTree::Literal(self::Literal {
195 kind: FromInternal::from_internal(kind),
201 DocComment(_, attr_style, data) => {
202 let mut escaped = String::new();
203 for ch in data.as_str().chars() {
204 escaped.extend(ch.escape_debug());
207 Ident(sym::doc, false),
209 TokenKind::lit(token::Str, Symbol::intern(&escaped), None),
212 .map(|kind| tokenstream::TokenTree::token_alone(kind, span))
214 trees.push(TokenTree::Punct(Punct { ch: b'#', joint: false, span }));
215 if attr_style == ast::AttrStyle::Inner {
216 trees.push(TokenTree::Punct(Punct { ch: b'!', joint: false, span }));
218 trees.push(TokenTree::Group(Group {
219 delimiter: pm::Delimiter::Bracket,
220 stream: Some(stream),
221 span: DelimSpan::from_single(span),
225 Interpolated(nt) if let NtIdent(ident, is_raw) = *nt => {
226 trees.push(TokenTree::Ident(Ident { sym: ident.name, is_raw, span: ident.span }))
229 Interpolated(nt) => {
230 let stream = TokenStream::from_nonterminal_ast(&nt);
231 // A hack used to pass AST fragments to attribute and derive
232 // macros as a single nonterminal token instead of a token
233 // stream. Such token needs to be "unwrapped" and not
234 // represented as a delimited group.
235 // FIXME: It needs to be removed, but there are some
236 // compatibility issues (see #73345).
237 if crate::base::nt_pretty_printing_compatibility_hack(&nt, rustc.sess()) {
238 trees.extend(Self::from_internal((stream, rustc)));
240 trees.push(TokenTree::Group(Group {
241 delimiter: pm::Delimiter::None,
242 stream: Some(stream),
243 span: DelimSpan::from_single(span),
248 OpenDelim(..) | CloseDelim(..) => unreachable!(),
249 Eof => unreachable!(),
256 // We use a `SmallVec` because the output size is always one or two `TokenTree`s.
257 impl ToInternal<SmallVec<[tokenstream::TokenTree; 2]>>
258 for (TokenTree<TokenStream, Span, Symbol>, &mut Rustc<'_, '_>)
260 fn to_internal(self) -> SmallVec<[tokenstream::TokenTree; 2]> {
261 use rustc_ast::token::*;
263 let (tree, rustc) = self;
265 TokenTree::Punct(Punct { ch, joint, span }) => {
266 let kind = match ch {
273 b'-' => BinOp(Minus),
275 b'/' => BinOp(Slash),
276 b'%' => BinOp(Percent),
277 b'^' => BinOp(Caret),
288 b'\'' => SingleQuote,
292 tokenstream::TokenTree::token_joint(kind, span)
294 tokenstream::TokenTree::token_alone(kind, span)
297 TokenTree::Group(Group { delimiter, stream, span: DelimSpan { open, close, .. } }) => {
298 smallvec![tokenstream::TokenTree::Delimited(
299 tokenstream::DelimSpan { open, close },
300 delimiter.to_internal(),
301 stream.unwrap_or_default(),
304 TokenTree::Ident(self::Ident { sym, is_raw, span }) => {
305 rustc.sess().symbol_gallery.insert(sym, span);
306 smallvec![tokenstream::TokenTree::token_alone(Ident(sym, is_raw), span)]
308 TokenTree::Literal(self::Literal {
309 kind: self::LitKind::Integer,
313 }) if symbol.as_str().starts_with('-') => {
314 let minus = BinOp(BinOpToken::Minus);
315 let symbol = Symbol::intern(&symbol.as_str()[1..]);
316 let integer = TokenKind::lit(token::Integer, symbol, suffix);
317 let a = tokenstream::TokenTree::token_alone(minus, span);
318 let b = tokenstream::TokenTree::token_alone(integer, span);
321 TokenTree::Literal(self::Literal {
322 kind: self::LitKind::Float,
326 }) if symbol.as_str().starts_with('-') => {
327 let minus = BinOp(BinOpToken::Minus);
328 let symbol = Symbol::intern(&symbol.as_str()[1..]);
329 let float = TokenKind::lit(token::Float, symbol, suffix);
330 let a = tokenstream::TokenTree::token_alone(minus, span);
331 let b = tokenstream::TokenTree::token_alone(float, span);
334 TokenTree::Literal(self::Literal { kind, symbol, suffix, span }) => {
335 smallvec![tokenstream::TokenTree::token_alone(
336 TokenKind::lit(kind.to_internal(), symbol, suffix),
344 impl ToInternal<rustc_errors::Level> for Level {
345 fn to_internal(self) -> rustc_errors::Level {
347 Level::Error => rustc_errors::Level::Error { lint: false },
348 Level::Warning => rustc_errors::Level::Warning(None),
349 Level::Note => rustc_errors::Level::Note,
350 Level::Help => rustc_errors::Level::Help,
351 _ => unreachable!("unknown proc_macro::Level variant: {:?}", self),
356 pub struct FreeFunctions;
358 pub(crate) struct Rustc<'a, 'b> {
359 ecx: &'a mut ExtCtxt<'b>,
364 rebased_spans: FxHashMap<usize, Span>,
367 impl<'a, 'b> Rustc<'a, 'b> {
368 pub fn new(ecx: &'a mut ExtCtxt<'b>) -> Self {
369 let expn_data = ecx.current_expansion.id.expn_data();
371 def_site: ecx.with_def_site_ctxt(expn_data.def_site),
372 call_site: ecx.with_call_site_ctxt(expn_data.call_site),
373 mixed_site: ecx.with_mixed_site_ctxt(expn_data.call_site),
374 krate: expn_data.macro_def_id.unwrap().krate,
375 rebased_spans: FxHashMap::default(),
380 fn sess(&self) -> &ParseSess {
381 self.ecx.parse_sess()
385 impl server::Types for Rustc<'_, '_> {
386 type FreeFunctions = FreeFunctions;
387 type TokenStream = TokenStream;
388 type SourceFile = Lrc<SourceFile>;
390 type Symbol = Symbol;
393 impl server::FreeFunctions for Rustc<'_, '_> {
394 fn track_env_var(&mut self, var: &str, value: Option<&str>) {
398 .insert((Symbol::intern(var), value.map(Symbol::intern)));
401 fn track_path(&mut self, path: &str) {
402 self.sess().file_depinfo.borrow_mut().insert(Symbol::intern(path));
405 fn literal_from_str(&mut self, s: &str) -> Result<Literal<Self::Span, Self::Symbol>, ()> {
406 let name = FileName::proc_macro_source_code(s);
407 let mut parser = rustc_parse::new_parser_from_source_str(self.sess(), name, s.to_owned());
409 let first_span = parser.token.span.data();
410 let minus_present = parser.eat(&token::BinOp(token::Minus));
412 let lit_span = parser.token.span.data();
413 let token::Literal(mut lit) = parser.token.kind else {
417 // Check no comment or whitespace surrounding the (possibly negative)
418 // literal, or more tokens after it.
419 if (lit_span.hi.0 - first_span.lo.0) as usize != s.len() {
424 // If minus is present, check no comment or whitespace in between it
425 // and the literal token.
426 if first_span.hi.0 != lit_span.lo.0 {
430 // Check literal is a kind we allow to be negated in a proc macro token.
433 | token::LitKind::Byte
434 | token::LitKind::Char
435 | token::LitKind::Str
436 | token::LitKind::StrRaw(_)
437 | token::LitKind::ByteStr
438 | token::LitKind::ByteStrRaw(_)
439 | token::LitKind::Err => return Err(()),
440 token::LitKind::Integer | token::LitKind::Float => {}
443 // Synthesize a new symbol that includes the minus sign.
444 let symbol = Symbol::intern(&s[..1 + lit.symbol.as_str().len()]);
445 lit = token::Lit::new(lit.kind, symbol, lit.suffix);
447 let token::Lit { kind, symbol, suffix } = lit;
449 kind: FromInternal::from_internal(kind),
452 span: self.call_site,
456 fn emit_diagnostic(&mut self, diagnostic: Diagnostic<Self::Span>) {
458 rustc_errors::Diagnostic::new(diagnostic.level.to_internal(), diagnostic.message);
459 diag.set_span(MultiSpan::from_spans(diagnostic.spans));
460 for child in diagnostic.children {
462 child.level.to_internal(),
464 MultiSpan::from_spans(child.spans),
468 self.sess().span_diagnostic.emit_diagnostic(&mut diag);
472 impl server::TokenStream for Rustc<'_, '_> {
473 fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
477 fn from_str(&mut self, src: &str) -> Self::TokenStream {
478 parse_stream_from_source_str(
479 FileName::proc_macro_source_code(src),
482 Some(self.call_site),
486 fn to_string(&mut self, stream: &Self::TokenStream) -> String {
487 pprust::tts_to_string(stream)
490 fn expand_expr(&mut self, stream: &Self::TokenStream) -> Result<Self::TokenStream, ()> {
491 // Parse the expression from our tokenstream.
492 let expr: PResult<'_, _> = try {
493 let mut p = rustc_parse::stream_to_parser(
496 Some("proc_macro expand expr"),
498 let expr = p.parse_expr()?;
499 if p.token != token::Eof {
504 let expr = expr.map_err(|mut err| {
508 // Perform eager expansion on the expression.
512 .fully_expand_fragment(crate::expand::AstFragment::Expr(expr))
515 // NOTE: For now, limit `expand_expr` to exclusively expand to literals.
516 // This may be relaxed in the future.
517 // We don't use `TokenStream::from_ast` as the tokenstream currently cannot
518 // be recovered in the general case.
520 ast::ExprKind::Lit(token_lit) if token_lit.kind == token::Bool => {
521 Ok(tokenstream::TokenStream::token_alone(
522 token::Ident(token_lit.symbol, false),
526 ast::ExprKind::Lit(token_lit) => {
527 Ok(tokenstream::TokenStream::token_alone(token::Literal(*token_lit), expr.span))
529 ast::ExprKind::IncludedBytes(bytes) => {
530 let lit = token::Lit::new(token::ByteStr, escape_byte_str_symbol(bytes), None);
531 Ok(tokenstream::TokenStream::token_alone(token::TokenKind::Literal(lit), expr.span))
533 ast::ExprKind::Unary(ast::UnOp::Neg, e) => match &e.kind {
534 ast::ExprKind::Lit(token_lit) => match token_lit {
535 token::Lit { kind: token::Integer | token::Float, .. } => {
536 Ok(Self::TokenStream::from_iter([
537 // FIXME: The span of the `-` token is lost when
538 // parsing, so we cannot faithfully recover it here.
539 tokenstream::TokenTree::token_alone(token::BinOp(token::Minus), e.span),
540 tokenstream::TokenTree::token_alone(token::Literal(*token_lit), e.span),
553 tree: TokenTree<Self::TokenStream, Self::Span, Self::Symbol>,
554 ) -> Self::TokenStream {
555 Self::TokenStream::new((tree, &mut *self).to_internal().into_iter().collect::<Vec<_>>())
560 base: Option<Self::TokenStream>,
561 trees: Vec<TokenTree<Self::TokenStream, Self::Span, Self::Symbol>>,
562 ) -> Self::TokenStream {
564 if let Some(base) = base { base } else { tokenstream::TokenStream::default() };
566 for tt in (tree, &mut *self).to_internal() {
567 stream.push_tree(tt);
575 base: Option<Self::TokenStream>,
576 streams: Vec<Self::TokenStream>,
577 ) -> Self::TokenStream {
579 if let Some(base) = base { base } else { tokenstream::TokenStream::default() };
581 stream.push_stream(s);
588 stream: Self::TokenStream,
589 ) -> Vec<TokenTree<Self::TokenStream, Self::Span, Self::Symbol>> {
590 FromInternal::from_internal((stream, self))
594 impl server::SourceFile for Rustc<'_, '_> {
595 fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
596 Lrc::ptr_eq(file1, file2)
599 fn path(&mut self, file: &Self::SourceFile) -> String {
601 FileName::Real(name) => name
603 .expect("attempting to get a file path in an imported file in `proc_macro::SourceFile::path`")
605 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
607 _ => file.name.prefer_local().to_string(),
611 fn is_real(&mut self, file: &Self::SourceFile) -> bool {
616 impl server::Span for Rustc<'_, '_> {
617 fn debug(&mut self, span: Self::Span) -> String {
618 if self.ecx.ecfg.span_debug {
619 format!("{:?}", span)
621 format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
625 fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
626 self.sess().source_map().lookup_char_pos(span.lo()).file
629 fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
630 span.parent_callsite()
633 fn source(&mut self, span: Self::Span) -> Self::Span {
634 span.source_callsite()
637 fn start(&mut self, span: Self::Span) -> LineColumn {
638 let loc = self.sess().source_map().lookup_char_pos(span.lo());
639 LineColumn { line: loc.line, column: loc.col.to_usize() }
642 fn end(&mut self, span: Self::Span) -> LineColumn {
643 let loc = self.sess().source_map().lookup_char_pos(span.hi());
644 LineColumn { line: loc.line, column: loc.col.to_usize() }
647 fn before(&mut self, span: Self::Span) -> Self::Span {
651 fn after(&mut self, span: Self::Span) -> Self::Span {
655 fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
656 let self_loc = self.sess().source_map().lookup_char_pos(first.lo());
657 let other_loc = self.sess().source_map().lookup_char_pos(second.lo());
659 if self_loc.file.name != other_loc.file.name {
663 Some(first.to(second))
671 ) -> Option<Self::Span> {
672 let length = span.hi().to_usize() - span.lo().to_usize();
674 let start = match start {
675 Bound::Included(lo) => lo,
676 Bound::Excluded(lo) => lo.checked_add(1)?,
677 Bound::Unbounded => 0,
680 let end = match end {
681 Bound::Included(hi) => hi.checked_add(1)?,
682 Bound::Excluded(hi) => hi,
683 Bound::Unbounded => length,
686 // Bounds check the values, preventing addition overflow and OOB spans.
687 if start > u32::MAX as usize
688 || end > u32::MAX as usize
689 || (u32::MAX - start as u32) < span.lo().to_u32()
690 || (u32::MAX - end as u32) < span.lo().to_u32()
697 let new_lo = span.lo() + BytePos::from_usize(start);
698 let new_hi = span.lo() + BytePos::from_usize(end);
699 Some(span.with_lo(new_lo).with_hi(new_hi))
702 fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
703 span.with_ctxt(at.ctxt())
706 fn source_text(&mut self, span: Self::Span) -> Option<String> {
707 self.sess().source_map().span_to_snippet(span).ok()
710 /// Saves the provided span into the metadata of
711 /// *the crate we are currently compiling*, which must
712 /// be a proc-macro crate. This id can be passed to
713 /// `recover_proc_macro_span` when our current crate
714 /// is *run* as a proc-macro.
716 /// Let's suppose that we have two crates - `my_client`
717 /// and `my_proc_macro`. The `my_proc_macro` crate
718 /// contains a procedural macro `my_macro`, which
719 /// is implemented as: `quote! { "hello" }`
721 /// When we *compile* `my_proc_macro`, we will execute
722 /// the `quote` proc-macro. This will save the span of
723 /// "hello" into the metadata of `my_proc_macro`. As a result,
724 /// the body of `my_proc_macro` (after expansion) will end
725 /// up containing a call that looks like this:
726 /// `proc_macro::Ident::new("hello", proc_macro::Span::recover_proc_macro_span(0))`
728 /// where `0` is the id returned by this function.
729 /// When `my_proc_macro` *executes* (during the compilation of `my_client`),
730 /// the call to `recover_proc_macro_span` will load the corresponding
731 /// span from the metadata of `my_proc_macro` (which we have access to,
732 /// since we've loaded `my_proc_macro` from disk in order to execute it).
733 /// In this way, we have obtained a span pointing into `my_proc_macro`
734 fn save_span(&mut self, span: Self::Span) -> usize {
735 self.sess().save_proc_macro_span(span)
738 fn recover_proc_macro_span(&mut self, id: usize) -> Self::Span {
739 let (resolver, krate, def_site) = (&*self.ecx.resolver, self.krate, self.def_site);
740 *self.rebased_spans.entry(id).or_insert_with(|| {
741 // FIXME: `SyntaxContext` for spans from proc macro crates is lost during encoding,
742 // replace it with a def-site context until we are encoding it properly.
743 resolver.get_proc_macro_quoted_span(krate, id).with_ctxt(def_site.ctxt())
748 impl server::Symbol for Rustc<'_, '_> {
749 fn normalize_and_validate_ident(&mut self, string: &str) -> Result<Self::Symbol, ()> {
750 let sym = nfc_normalize(string);
751 if rustc_lexer::is_ident(sym.as_str()) { Ok(sym) } else { Err(()) }
755 impl server::Server for Rustc<'_, '_> {
756 fn globals(&mut self) -> ExpnGlobals<Self::Span> {
758 def_site: self.def_site,
759 call_site: self.call_site,
760 mixed_site: self.mixed_site,
764 fn intern_symbol(string: &str) -> Self::Symbol {
765 Symbol::intern(string)
768 fn with_symbol_string(symbol: &Self::Symbol, f: impl FnOnce(&str)) {