1 use crate::base::ExtCtxt;
5 use rustc_ast::tokenstream::{self, Spacing::*, TokenStream};
6 use rustc_ast_pretty::pprust;
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_data_structures::sync::Lrc;
9 use rustc_errors::{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, sym, Symbol};
15 use rustc_span::{BytePos, FileName, Pos, SourceFile, Span};
18 server, DelimSpan, Diagnostic, ExpnGlobals, Group, Ident, LitKind, Literal, Punct, TokenTree,
20 use pm::{Delimiter, Level, LineColumn};
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(|(idx, ch)| {
119 let is_final = idx == s.len() - 1;
120 TokenTree::Punct(Punct { ch, joint: if is_final { joint } else { true }, span })
136 BinOp(Plus) => op("+"),
137 BinOp(Minus) => op("-"),
138 BinOp(Star) => op("*"),
139 BinOp(Slash) => op("/"),
140 BinOp(Percent) => op("%"),
141 BinOp(Caret) => op("^"),
142 BinOp(And) => op("&"),
143 BinOp(Or) => op("|"),
144 BinOp(Shl) => op("<<"),
145 BinOp(Shr) => op(">>"),
146 BinOpEq(Plus) => op("+="),
147 BinOpEq(Minus) => op("-="),
148 BinOpEq(Star) => op("*="),
149 BinOpEq(Slash) => op("/="),
150 BinOpEq(Percent) => op("%="),
151 BinOpEq(Caret) => op("^="),
152 BinOpEq(And) => op("&="),
153 BinOpEq(Or) => op("|="),
154 BinOpEq(Shl) => op("<<="),
155 BinOpEq(Shr) => op(">>="),
159 DotDotDot => op("..."),
160 DotDotEq => op("..="),
167 FatArrow => op("=>"),
171 SingleQuote => op("'"),
173 Ident(sym, is_raw) => trees.push(TokenTree::Ident(Ident { sym, is_raw, span })),
175 let ident = symbol::Ident::new(name, span).without_first_quote();
177 TokenTree::Punct(Punct { ch: b'\'', joint: true, span }),
178 TokenTree::Ident(Ident { sym: ident.name, is_raw: false, span }),
181 Literal(token::Lit { kind, symbol, suffix }) => {
182 trees.push(TokenTree::Literal(self::Literal {
183 kind: FromInternal::from_internal(kind),
189 DocComment(_, attr_style, data) => {
190 let mut escaped = String::new();
191 for ch in data.as_str().chars() {
192 escaped.extend(ch.escape_debug());
195 Ident(sym::doc, false),
197 TokenKind::lit(token::Str, Symbol::intern(&escaped), None),
200 .map(|kind| tokenstream::TokenTree::token_alone(kind, span))
202 trees.push(TokenTree::Punct(Punct { ch: b'#', joint: false, span }));
203 if attr_style == ast::AttrStyle::Inner {
204 trees.push(TokenTree::Punct(Punct { ch: b'!', joint: false, span }));
206 trees.push(TokenTree::Group(Group {
207 delimiter: pm::Delimiter::Bracket,
208 stream: Some(stream),
209 span: DelimSpan::from_single(span),
213 Interpolated(nt) if let NtIdent(ident, is_raw) = *nt => {
214 trees.push(TokenTree::Ident(Ident { sym: ident.name, is_raw, span: ident.span }))
217 Interpolated(nt) => {
218 let stream = TokenStream::from_nonterminal_ast(&nt);
219 // A hack used to pass AST fragments to attribute and derive
220 // macros as a single nonterminal token instead of a token
221 // stream. Such token needs to be "unwrapped" and not
222 // represented as a delimited group.
223 // FIXME: It needs to be removed, but there are some
224 // compatibility issues (see #73345).
225 if crate::base::nt_pretty_printing_compatibility_hack(&nt, rustc.sess()) {
226 trees.extend(Self::from_internal((stream, rustc)));
228 trees.push(TokenTree::Group(Group {
229 delimiter: pm::Delimiter::None,
230 stream: Some(stream),
231 span: DelimSpan::from_single(span),
236 OpenDelim(..) | CloseDelim(..) => unreachable!(),
237 Eof => unreachable!(),
244 impl ToInternal<TokenStream> for (TokenTree<TokenStream, Span, Symbol>, &mut Rustc<'_, '_>) {
245 fn to_internal(self) -> TokenStream {
246 use rustc_ast::token::*;
248 let (tree, rustc) = self;
249 let (ch, joint, span) = match tree {
250 TokenTree::Punct(Punct { ch, joint, span }) => (ch, joint, span),
251 TokenTree::Group(Group { delimiter, stream, span: DelimSpan { open, close, .. } }) => {
252 return tokenstream::TokenStream::delimited(
253 tokenstream::DelimSpan { open, close },
254 delimiter.to_internal(),
255 stream.unwrap_or_default(),
258 TokenTree::Ident(self::Ident { sym, is_raw, span }) => {
259 rustc.sess().symbol_gallery.insert(sym, span);
260 return tokenstream::TokenStream::token_alone(Ident(sym, is_raw), span);
262 TokenTree::Literal(self::Literal {
263 kind: self::LitKind::Integer,
267 }) if symbol.as_str().starts_with('-') => {
268 let minus = BinOp(BinOpToken::Minus);
269 let symbol = Symbol::intern(&symbol.as_str()[1..]);
270 let integer = TokenKind::lit(token::Integer, symbol, suffix);
271 let a = tokenstream::TokenTree::token_alone(minus, span);
272 let b = tokenstream::TokenTree::token_alone(integer, span);
273 return [a, b].into_iter().collect();
275 TokenTree::Literal(self::Literal {
276 kind: self::LitKind::Float,
280 }) if symbol.as_str().starts_with('-') => {
281 let minus = BinOp(BinOpToken::Minus);
282 let symbol = Symbol::intern(&symbol.as_str()[1..]);
283 let float = TokenKind::lit(token::Float, symbol, suffix);
284 let a = tokenstream::TokenTree::token_alone(minus, span);
285 let b = tokenstream::TokenTree::token_alone(float, span);
286 return [a, b].into_iter().collect();
288 TokenTree::Literal(self::Literal { kind, symbol, suffix, span }) => {
289 return tokenstream::TokenStream::token_alone(
290 TokenKind::lit(kind.to_internal(), symbol, suffix),
296 let kind = match ch {
303 b'-' => BinOp(Minus),
305 b'/' => BinOp(Slash),
306 b'%' => BinOp(Percent),
307 b'^' => BinOp(Caret),
318 b'\'' => SingleQuote,
323 tokenstream::TokenStream::token_joint(kind, span)
325 tokenstream::TokenStream::token_alone(kind, span)
330 impl ToInternal<rustc_errors::Level> for Level {
331 fn to_internal(self) -> rustc_errors::Level {
333 Level::Error => rustc_errors::Level::Error { lint: false },
334 Level::Warning => rustc_errors::Level::Warning(None),
335 Level::Note => rustc_errors::Level::Note,
336 Level::Help => rustc_errors::Level::Help,
337 _ => unreachable!("unknown proc_macro::Level variant: {:?}", self),
342 pub struct FreeFunctions;
344 pub(crate) struct Rustc<'a, 'b> {
345 ecx: &'a mut ExtCtxt<'b>,
350 rebased_spans: FxHashMap<usize, Span>,
353 impl<'a, 'b> Rustc<'a, 'b> {
354 pub fn new(ecx: &'a mut ExtCtxt<'b>) -> Self {
355 let expn_data = ecx.current_expansion.id.expn_data();
357 def_site: ecx.with_def_site_ctxt(expn_data.def_site),
358 call_site: ecx.with_call_site_ctxt(expn_data.call_site),
359 mixed_site: ecx.with_mixed_site_ctxt(expn_data.call_site),
360 krate: expn_data.macro_def_id.unwrap().krate,
361 rebased_spans: FxHashMap::default(),
366 fn sess(&self) -> &ParseSess {
367 self.ecx.parse_sess()
371 impl server::Types for Rustc<'_, '_> {
372 type FreeFunctions = FreeFunctions;
373 type TokenStream = TokenStream;
374 type SourceFile = Lrc<SourceFile>;
376 type Symbol = Symbol;
379 impl server::FreeFunctions for Rustc<'_, '_> {
380 fn track_env_var(&mut self, var: &str, value: Option<&str>) {
384 .insert((Symbol::intern(var), value.map(Symbol::intern)));
387 fn track_path(&mut self, path: &str) {
388 self.sess().file_depinfo.borrow_mut().insert(Symbol::intern(path));
391 fn literal_from_str(&mut self, s: &str) -> Result<Literal<Self::Span, Self::Symbol>, ()> {
392 let name = FileName::proc_macro_source_code(s);
393 let mut parser = rustc_parse::new_parser_from_source_str(self.sess(), name, s.to_owned());
395 let first_span = parser.token.span.data();
396 let minus_present = parser.eat(&token::BinOp(token::Minus));
398 let lit_span = parser.token.span.data();
399 let token::Literal(mut lit) = parser.token.kind else {
403 // Check no comment or whitespace surrounding the (possibly negative)
404 // literal, or more tokens after it.
405 if (lit_span.hi.0 - first_span.lo.0) as usize != s.len() {
410 // If minus is present, check no comment or whitespace in between it
411 // and the literal token.
412 if first_span.hi.0 != lit_span.lo.0 {
416 // Check literal is a kind we allow to be negated in a proc macro token.
419 | token::LitKind::Byte
420 | token::LitKind::Char
421 | token::LitKind::Str
422 | token::LitKind::StrRaw(_)
423 | token::LitKind::ByteStr
424 | token::LitKind::ByteStrRaw(_)
425 | token::LitKind::Err => return Err(()),
426 token::LitKind::Integer | token::LitKind::Float => {}
429 // Synthesize a new symbol that includes the minus sign.
430 let symbol = Symbol::intern(&s[..1 + lit.symbol.as_str().len()]);
431 lit = token::Lit::new(lit.kind, symbol, lit.suffix);
433 let token::Lit { kind, symbol, suffix } = lit;
435 kind: FromInternal::from_internal(kind),
438 span: self.call_site,
442 fn emit_diagnostic(&mut self, diagnostic: Diagnostic<Self::Span>) {
444 rustc_errors::Diagnostic::new(diagnostic.level.to_internal(), diagnostic.message);
445 diag.set_span(MultiSpan::from_spans(diagnostic.spans));
446 for child in diagnostic.children {
448 child.level.to_internal(),
450 MultiSpan::from_spans(child.spans),
454 self.sess().span_diagnostic.emit_diagnostic(&mut diag);
458 impl server::TokenStream for Rustc<'_, '_> {
459 fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
463 fn from_str(&mut self, src: &str) -> Self::TokenStream {
464 parse_stream_from_source_str(
465 FileName::proc_macro_source_code(src),
468 Some(self.call_site),
472 fn to_string(&mut self, stream: &Self::TokenStream) -> String {
473 pprust::tts_to_string(stream)
476 fn expand_expr(&mut self, stream: &Self::TokenStream) -> Result<Self::TokenStream, ()> {
477 // Parse the expression from our tokenstream.
478 let expr: PResult<'_, _> = try {
479 let mut p = rustc_parse::stream_to_parser(
482 Some("proc_macro expand expr"),
484 let expr = p.parse_expr()?;
485 if p.token != token::Eof {
490 let expr = expr.map_err(|mut err| {
494 // Perform eager expansion on the expression.
498 .fully_expand_fragment(crate::expand::AstFragment::Expr(expr))
501 // NOTE: For now, limit `expand_expr` to exclusively expand to literals.
502 // This may be relaxed in the future.
503 // We don't use `TokenStream::from_ast` as the tokenstream currently cannot
504 // be recovered in the general case.
506 ast::ExprKind::Lit(l) if l.token_lit.kind == token::Bool => {
507 Ok(tokenstream::TokenStream::token_alone(
508 token::Ident(l.token_lit.symbol, false),
512 ast::ExprKind::Lit(l) => {
513 Ok(tokenstream::TokenStream::token_alone(token::Literal(l.token_lit), l.span))
515 ast::ExprKind::Unary(ast::UnOp::Neg, e) => match &e.kind {
516 ast::ExprKind::Lit(l) => match l.token_lit {
517 token::Lit { kind: token::Integer | token::Float, .. } => {
518 Ok(Self::TokenStream::from_iter([
519 // FIXME: The span of the `-` token is lost when
520 // parsing, so we cannot faithfully recover it here.
521 tokenstream::TokenTree::token_alone(token::BinOp(token::Minus), e.span),
522 tokenstream::TokenTree::token_alone(
523 token::Literal(l.token_lit),
538 tree: TokenTree<Self::TokenStream, Self::Span, Self::Symbol>,
539 ) -> Self::TokenStream {
540 (tree, &mut *self).to_internal()
545 base: Option<Self::TokenStream>,
546 trees: Vec<TokenTree<Self::TokenStream, Self::Span, Self::Symbol>>,
547 ) -> Self::TokenStream {
548 let mut builder = tokenstream::TokenStreamBuilder::new();
549 if let Some(base) = base {
553 builder.push((tree, &mut *self).to_internal());
560 base: Option<Self::TokenStream>,
561 streams: Vec<Self::TokenStream>,
562 ) -> Self::TokenStream {
563 let mut builder = tokenstream::TokenStreamBuilder::new();
564 if let Some(base) = base {
567 for stream in streams {
568 builder.push(stream);
575 stream: Self::TokenStream,
576 ) -> Vec<TokenTree<Self::TokenStream, Self::Span, Self::Symbol>> {
577 FromInternal::from_internal((stream, self))
581 impl server::SourceFile for Rustc<'_, '_> {
582 fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
583 Lrc::ptr_eq(file1, file2)
586 fn path(&mut self, file: &Self::SourceFile) -> String {
588 FileName::Real(ref name) => name
590 .expect("attempting to get a file path in an imported file in `proc_macro::SourceFile::path`")
592 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
594 _ => file.name.prefer_local().to_string(),
598 fn is_real(&mut self, file: &Self::SourceFile) -> bool {
603 impl server::Span for Rustc<'_, '_> {
604 fn debug(&mut self, span: Self::Span) -> String {
605 if self.ecx.ecfg.span_debug {
606 format!("{:?}", span)
608 format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
612 fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
613 self.sess().source_map().lookup_char_pos(span.lo()).file
616 fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
617 span.parent_callsite()
620 fn source(&mut self, span: Self::Span) -> Self::Span {
621 span.source_callsite()
624 fn start(&mut self, span: Self::Span) -> LineColumn {
625 let loc = self.sess().source_map().lookup_char_pos(span.lo());
626 LineColumn { line: loc.line, column: loc.col.to_usize() }
629 fn end(&mut self, span: Self::Span) -> LineColumn {
630 let loc = self.sess().source_map().lookup_char_pos(span.hi());
631 LineColumn { line: loc.line, column: loc.col.to_usize() }
634 fn before(&mut self, span: Self::Span) -> Self::Span {
638 fn after(&mut self, span: Self::Span) -> Self::Span {
642 fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
643 let self_loc = self.sess().source_map().lookup_char_pos(first.lo());
644 let other_loc = self.sess().source_map().lookup_char_pos(second.lo());
646 if self_loc.file.name != other_loc.file.name {
650 Some(first.to(second))
658 ) -> Option<Self::Span> {
659 let length = span.hi().to_usize() - span.lo().to_usize();
661 let start = match start {
662 Bound::Included(lo) => lo,
663 Bound::Excluded(lo) => lo.checked_add(1)?,
664 Bound::Unbounded => 0,
667 let end = match end {
668 Bound::Included(hi) => hi.checked_add(1)?,
669 Bound::Excluded(hi) => hi,
670 Bound::Unbounded => length,
673 // Bounds check the values, preventing addition overflow and OOB spans.
674 if start > u32::MAX as usize
675 || end > u32::MAX as usize
676 || (u32::MAX - start as u32) < span.lo().to_u32()
677 || (u32::MAX - end as u32) < span.lo().to_u32()
684 let new_lo = span.lo() + BytePos::from_usize(start);
685 let new_hi = span.lo() + BytePos::from_usize(end);
686 Some(span.with_lo(new_lo).with_hi(new_hi))
689 fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
690 span.with_ctxt(at.ctxt())
693 fn source_text(&mut self, span: Self::Span) -> Option<String> {
694 self.sess().source_map().span_to_snippet(span).ok()
696 /// Saves the provided span into the metadata of
697 /// *the crate we are currently compiling*, which must
698 /// be a proc-macro crate. This id can be passed to
699 /// `recover_proc_macro_span` when our current crate
700 /// is *run* as a proc-macro.
702 /// Let's suppose that we have two crates - `my_client`
703 /// and `my_proc_macro`. The `my_proc_macro` crate
704 /// contains a procedural macro `my_macro`, which
705 /// is implemented as: `quote! { "hello" }`
707 /// When we *compile* `my_proc_macro`, we will execute
708 /// the `quote` proc-macro. This will save the span of
709 /// "hello" into the metadata of `my_proc_macro`. As a result,
710 /// the body of `my_proc_macro` (after expansion) will end
711 /// up containing a call that looks like this:
712 /// `proc_macro::Ident::new("hello", proc_macro::Span::recover_proc_macro_span(0))`
714 /// where `0` is the id returned by this function.
715 /// When `my_proc_macro` *executes* (during the compilation of `my_client`),
716 /// the call to `recover_proc_macro_span` will load the corresponding
717 /// span from the metadata of `my_proc_macro` (which we have access to,
718 /// since we've loaded `my_proc_macro` from disk in order to execute it).
719 /// In this way, we have obtained a span pointing into `my_proc_macro`
720 fn save_span(&mut self, span: Self::Span) -> usize {
721 self.sess().save_proc_macro_span(span)
724 fn recover_proc_macro_span(&mut self, id: usize) -> Self::Span {
725 let (resolver, krate, def_site) = (&*self.ecx.resolver, self.krate, self.def_site);
726 *self.rebased_spans.entry(id).or_insert_with(|| {
727 // FIXME: `SyntaxContext` for spans from proc macro crates is lost during encoding,
728 // replace it with a def-site context until we are encoding it properly.
729 resolver.get_proc_macro_quoted_span(krate, id).with_ctxt(def_site.ctxt())
734 impl server::Symbol for Rustc<'_, '_> {
735 fn normalize_and_validate_ident(&mut self, string: &str) -> Result<Self::Symbol, ()> {
736 let sym = nfc_normalize(string);
737 if rustc_lexer::is_ident(sym.as_str()) { Ok(sym) } else { Err(()) }
741 impl server::Server for Rustc<'_, '_> {
742 fn globals(&mut self) -> ExpnGlobals<Self::Span> {
744 def_site: self.def_site,
745 call_site: self.call_site,
746 mixed_site: self.mixed_site,
750 fn intern_symbol(string: &str) -> Self::Symbol {
751 Symbol::intern(string)
754 fn with_symbol_string(symbol: &Self::Symbol, f: impl FnOnce(&str)) {