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(|(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 impl ToInternal<TokenStream> for (TokenTree<TokenStream, Span, Symbol>, &mut Rustc<'_, '_>) {
257 fn to_internal(self) -> TokenStream {
258 use rustc_ast::token::*;
260 let (tree, rustc) = self;
261 let (ch, joint, span) = match tree {
262 TokenTree::Punct(Punct { ch, joint, span }) => (ch, joint, span),
263 TokenTree::Group(Group { delimiter, stream, span: DelimSpan { open, close, .. } }) => {
264 return tokenstream::TokenStream::delimited(
265 tokenstream::DelimSpan { open, close },
266 delimiter.to_internal(),
267 stream.unwrap_or_default(),
270 TokenTree::Ident(self::Ident { sym, is_raw, span }) => {
271 rustc.sess().symbol_gallery.insert(sym, span);
272 return tokenstream::TokenStream::token_alone(Ident(sym, is_raw), span);
274 TokenTree::Literal(self::Literal {
275 kind: self::LitKind::Integer,
279 }) if symbol.as_str().starts_with('-') => {
280 let minus = BinOp(BinOpToken::Minus);
281 let symbol = Symbol::intern(&symbol.as_str()[1..]);
282 let integer = TokenKind::lit(token::Integer, symbol, suffix);
283 let a = tokenstream::TokenTree::token_alone(minus, span);
284 let b = tokenstream::TokenTree::token_alone(integer, span);
285 return [a, b].into_iter().collect();
287 TokenTree::Literal(self::Literal {
288 kind: self::LitKind::Float,
292 }) if symbol.as_str().starts_with('-') => {
293 let minus = BinOp(BinOpToken::Minus);
294 let symbol = Symbol::intern(&symbol.as_str()[1..]);
295 let float = TokenKind::lit(token::Float, symbol, suffix);
296 let a = tokenstream::TokenTree::token_alone(minus, span);
297 let b = tokenstream::TokenTree::token_alone(float, span);
298 return [a, b].into_iter().collect();
300 TokenTree::Literal(self::Literal { kind, symbol, suffix, span }) => {
301 return tokenstream::TokenStream::token_alone(
302 TokenKind::lit(kind.to_internal(), symbol, suffix),
308 let kind = match ch {
315 b'-' => BinOp(Minus),
317 b'/' => BinOp(Slash),
318 b'%' => BinOp(Percent),
319 b'^' => BinOp(Caret),
330 b'\'' => SingleQuote,
335 tokenstream::TokenStream::token_joint(kind, span)
337 tokenstream::TokenStream::token_alone(kind, span)
342 impl ToInternal<rustc_errors::Level> for Level {
343 fn to_internal(self) -> rustc_errors::Level {
345 Level::Error => rustc_errors::Level::Error { lint: false },
346 Level::Warning => rustc_errors::Level::Warning(None),
347 Level::Note => rustc_errors::Level::Note,
348 Level::Help => rustc_errors::Level::Help,
349 _ => unreachable!("unknown proc_macro::Level variant: {:?}", self),
354 pub struct FreeFunctions;
356 pub(crate) struct Rustc<'a, 'b> {
357 ecx: &'a mut ExtCtxt<'b>,
362 rebased_spans: FxHashMap<usize, Span>,
365 impl<'a, 'b> Rustc<'a, 'b> {
366 pub fn new(ecx: &'a mut ExtCtxt<'b>) -> Self {
367 let expn_data = ecx.current_expansion.id.expn_data();
369 def_site: ecx.with_def_site_ctxt(expn_data.def_site),
370 call_site: ecx.with_call_site_ctxt(expn_data.call_site),
371 mixed_site: ecx.with_mixed_site_ctxt(expn_data.call_site),
372 krate: expn_data.macro_def_id.unwrap().krate,
373 rebased_spans: FxHashMap::default(),
378 fn sess(&self) -> &ParseSess {
379 self.ecx.parse_sess()
383 impl server::Types for Rustc<'_, '_> {
384 type FreeFunctions = FreeFunctions;
385 type TokenStream = TokenStream;
386 type SourceFile = Lrc<SourceFile>;
388 type Symbol = Symbol;
391 impl server::FreeFunctions for Rustc<'_, '_> {
392 fn track_env_var(&mut self, var: &str, value: Option<&str>) {
396 .insert((Symbol::intern(var), value.map(Symbol::intern)));
399 fn track_path(&mut self, path: &str) {
400 self.sess().file_depinfo.borrow_mut().insert(Symbol::intern(path));
403 fn literal_from_str(&mut self, s: &str) -> Result<Literal<Self::Span, Self::Symbol>, ()> {
404 let name = FileName::proc_macro_source_code(s);
405 let mut parser = rustc_parse::new_parser_from_source_str(self.sess(), name, s.to_owned());
407 let first_span = parser.token.span.data();
408 let minus_present = parser.eat(&token::BinOp(token::Minus));
410 let lit_span = parser.token.span.data();
411 let token::Literal(mut lit) = parser.token.kind else {
415 // Check no comment or whitespace surrounding the (possibly negative)
416 // literal, or more tokens after it.
417 if (lit_span.hi.0 - first_span.lo.0) as usize != s.len() {
422 // If minus is present, check no comment or whitespace in between it
423 // and the literal token.
424 if first_span.hi.0 != lit_span.lo.0 {
428 // Check literal is a kind we allow to be negated in a proc macro token.
431 | token::LitKind::Byte
432 | token::LitKind::Char
433 | token::LitKind::Str
434 | token::LitKind::StrRaw(_)
435 | token::LitKind::ByteStr
436 | token::LitKind::ByteStrRaw(_)
437 | token::LitKind::Err => return Err(()),
438 token::LitKind::Integer | token::LitKind::Float => {}
441 // Synthesize a new symbol that includes the minus sign.
442 let symbol = Symbol::intern(&s[..1 + lit.symbol.as_str().len()]);
443 lit = token::Lit::new(lit.kind, symbol, lit.suffix);
445 let token::Lit { kind, symbol, suffix } = lit;
447 kind: FromInternal::from_internal(kind),
450 span: self.call_site,
454 fn emit_diagnostic(&mut self, diagnostic: Diagnostic<Self::Span>) {
456 rustc_errors::Diagnostic::new(diagnostic.level.to_internal(), diagnostic.message);
457 diag.set_span(MultiSpan::from_spans(diagnostic.spans));
458 for child in diagnostic.children {
460 child.level.to_internal(),
462 MultiSpan::from_spans(child.spans),
466 self.sess().span_diagnostic.emit_diagnostic(&mut diag);
470 impl server::TokenStream for Rustc<'_, '_> {
471 fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
475 fn from_str(&mut self, src: &str) -> Self::TokenStream {
476 parse_stream_from_source_str(
477 FileName::proc_macro_source_code(src),
480 Some(self.call_site),
484 fn to_string(&mut self, stream: &Self::TokenStream) -> String {
485 pprust::tts_to_string(stream)
488 fn expand_expr(&mut self, stream: &Self::TokenStream) -> Result<Self::TokenStream, ()> {
489 // Parse the expression from our tokenstream.
490 let expr: PResult<'_, _> = try {
491 let mut p = rustc_parse::stream_to_parser(
494 Some("proc_macro expand expr"),
496 let expr = p.parse_expr()?;
497 if p.token != token::Eof {
502 let expr = expr.map_err(|mut err| {
506 // Perform eager expansion on the expression.
510 .fully_expand_fragment(crate::expand::AstFragment::Expr(expr))
513 // NOTE: For now, limit `expand_expr` to exclusively expand to literals.
514 // This may be relaxed in the future.
515 // We don't use `TokenStream::from_ast` as the tokenstream currently cannot
516 // be recovered in the general case.
518 ast::ExprKind::Lit(l) if l.token_lit.kind == token::Bool => {
519 Ok(tokenstream::TokenStream::token_alone(
520 token::Ident(l.token_lit.symbol, false),
524 ast::ExprKind::Lit(l) => {
525 Ok(tokenstream::TokenStream::token_alone(token::Literal(l.token_lit), l.span))
527 ast::ExprKind::Unary(ast::UnOp::Neg, e) => match &e.kind {
528 ast::ExprKind::Lit(l) => match l.token_lit {
529 token::Lit { kind: token::Integer | token::Float, .. } => {
530 Ok(Self::TokenStream::from_iter([
531 // FIXME: The span of the `-` token is lost when
532 // parsing, so we cannot faithfully recover it here.
533 tokenstream::TokenTree::token_alone(token::BinOp(token::Minus), e.span),
534 tokenstream::TokenTree::token_alone(
535 token::Literal(l.token_lit),
550 tree: TokenTree<Self::TokenStream, Self::Span, Self::Symbol>,
551 ) -> Self::TokenStream {
552 (tree, &mut *self).to_internal()
557 base: Option<Self::TokenStream>,
558 trees: Vec<TokenTree<Self::TokenStream, Self::Span, Self::Symbol>>,
559 ) -> Self::TokenStream {
560 let mut builder = tokenstream::TokenStreamBuilder::new();
561 if let Some(base) = base {
565 builder.push((tree, &mut *self).to_internal());
572 base: Option<Self::TokenStream>,
573 streams: Vec<Self::TokenStream>,
574 ) -> Self::TokenStream {
575 let mut builder = tokenstream::TokenStreamBuilder::new();
576 if let Some(base) = base {
579 for stream in streams {
580 builder.push(stream);
587 stream: Self::TokenStream,
588 ) -> Vec<TokenTree<Self::TokenStream, Self::Span, Self::Symbol>> {
589 FromInternal::from_internal((stream, self))
593 impl server::SourceFile for Rustc<'_, '_> {
594 fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
595 Lrc::ptr_eq(file1, file2)
598 fn path(&mut self, file: &Self::SourceFile) -> String {
600 FileName::Real(ref name) => name
602 .expect("attempting to get a file path in an imported file in `proc_macro::SourceFile::path`")
604 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
606 _ => file.name.prefer_local().to_string(),
610 fn is_real(&mut self, file: &Self::SourceFile) -> bool {
615 impl server::Span for Rustc<'_, '_> {
616 fn debug(&mut self, span: Self::Span) -> String {
617 if self.ecx.ecfg.span_debug {
618 format!("{:?}", span)
620 format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
624 fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
625 self.sess().source_map().lookup_char_pos(span.lo()).file
628 fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
629 span.parent_callsite()
632 fn source(&mut self, span: Self::Span) -> Self::Span {
633 span.source_callsite()
636 fn start(&mut self, span: Self::Span) -> LineColumn {
637 let loc = self.sess().source_map().lookup_char_pos(span.lo());
638 LineColumn { line: loc.line, column: loc.col.to_usize() }
641 fn end(&mut self, span: Self::Span) -> LineColumn {
642 let loc = self.sess().source_map().lookup_char_pos(span.hi());
643 LineColumn { line: loc.line, column: loc.col.to_usize() }
646 fn before(&mut self, span: Self::Span) -> Self::Span {
650 fn after(&mut self, span: Self::Span) -> Self::Span {
654 fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
655 let self_loc = self.sess().source_map().lookup_char_pos(first.lo());
656 let other_loc = self.sess().source_map().lookup_char_pos(second.lo());
658 if self_loc.file.name != other_loc.file.name {
662 Some(first.to(second))
670 ) -> Option<Self::Span> {
671 let length = span.hi().to_usize() - span.lo().to_usize();
673 let start = match start {
674 Bound::Included(lo) => lo,
675 Bound::Excluded(lo) => lo.checked_add(1)?,
676 Bound::Unbounded => 0,
679 let end = match end {
680 Bound::Included(hi) => hi.checked_add(1)?,
681 Bound::Excluded(hi) => hi,
682 Bound::Unbounded => length,
685 // Bounds check the values, preventing addition overflow and OOB spans.
686 if start > u32::MAX as usize
687 || end > u32::MAX as usize
688 || (u32::MAX - start as u32) < span.lo().to_u32()
689 || (u32::MAX - end as u32) < span.lo().to_u32()
696 let new_lo = span.lo() + BytePos::from_usize(start);
697 let new_hi = span.lo() + BytePos::from_usize(end);
698 Some(span.with_lo(new_lo).with_hi(new_hi))
701 fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
702 span.with_ctxt(at.ctxt())
705 fn source_text(&mut self, span: Self::Span) -> Option<String> {
706 self.sess().source_map().span_to_snippet(span).ok()
708 /// Saves the provided span into the metadata of
709 /// *the crate we are currently compiling*, which must
710 /// be a proc-macro crate. This id can be passed to
711 /// `recover_proc_macro_span` when our current crate
712 /// is *run* as a proc-macro.
714 /// Let's suppose that we have two crates - `my_client`
715 /// and `my_proc_macro`. The `my_proc_macro` crate
716 /// contains a procedural macro `my_macro`, which
717 /// is implemented as: `quote! { "hello" }`
719 /// When we *compile* `my_proc_macro`, we will execute
720 /// the `quote` proc-macro. This will save the span of
721 /// "hello" into the metadata of `my_proc_macro`. As a result,
722 /// the body of `my_proc_macro` (after expansion) will end
723 /// up containing a call that looks like this:
724 /// `proc_macro::Ident::new("hello", proc_macro::Span::recover_proc_macro_span(0))`
726 /// where `0` is the id returned by this function.
727 /// When `my_proc_macro` *executes* (during the compilation of `my_client`),
728 /// the call to `recover_proc_macro_span` will load the corresponding
729 /// span from the metadata of `my_proc_macro` (which we have access to,
730 /// since we've loaded `my_proc_macro` from disk in order to execute it).
731 /// In this way, we have obtained a span pointing into `my_proc_macro`
732 fn save_span(&mut self, span: Self::Span) -> usize {
733 self.sess().save_proc_macro_span(span)
736 fn recover_proc_macro_span(&mut self, id: usize) -> Self::Span {
737 let (resolver, krate, def_site) = (&*self.ecx.resolver, self.krate, self.def_site);
738 *self.rebased_spans.entry(id).or_insert_with(|| {
739 // FIXME: `SyntaxContext` for spans from proc macro crates is lost during encoding,
740 // replace it with a def-site context until we are encoding it properly.
741 resolver.get_proc_macro_quoted_span(krate, id).with_ctxt(def_site.ctxt())
746 impl server::Symbol for Rustc<'_, '_> {
747 fn normalize_and_validate_ident(&mut self, string: &str) -> Result<Self::Symbol, ()> {
748 let sym = nfc_normalize(string);
749 if rustc_lexer::is_ident(sym.as_str()) { Ok(sym) } else { Err(()) }
753 impl server::Server for Rustc<'_, '_> {
754 fn globals(&mut self) -> ExpnGlobals<Self::Span> {
756 def_site: self.def_site,
757 call_site: self.call_site,
758 mixed_site: self.mixed_site,
762 fn intern_symbol(string: &str) -> Self::Symbol {
763 Symbol::intern(string)
766 fn with_symbol_string(symbol: &Self::Symbol, f: impl FnOnce(&str)) {