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::{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, sym, Symbol};
15 use rustc_span::{BytePos, FileName, Pos, SourceFile, Span};
18 server, DelimSpan, 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 let mut op = |s: &str| {
114 assert!(s.is_ascii());
115 trees.extend(s.as_bytes().iter().enumerate().map(|(idx, &ch)| {
116 TokenTree::Punct(Punct { ch, joint: joint || idx != s.len() - 1, span })
132 BinOp(Plus) => op("+"),
133 BinOp(Minus) => op("-"),
134 BinOp(Star) => op("*"),
135 BinOp(Slash) => op("/"),
136 BinOp(Percent) => op("%"),
137 BinOp(Caret) => op("^"),
138 BinOp(And) => op("&"),
139 BinOp(Or) => op("|"),
140 BinOp(Shl) => op("<<"),
141 BinOp(Shr) => op(">>"),
142 BinOpEq(Plus) => op("+="),
143 BinOpEq(Minus) => op("-="),
144 BinOpEq(Star) => op("*="),
145 BinOpEq(Slash) => op("/="),
146 BinOpEq(Percent) => op("%="),
147 BinOpEq(Caret) => op("^="),
148 BinOpEq(And) => op("&="),
149 BinOpEq(Or) => op("|="),
150 BinOpEq(Shl) => op("<<="),
151 BinOpEq(Shr) => op(">>="),
155 DotDotDot => op("..."),
156 DotDotEq => op("..="),
163 FatArrow => op("=>"),
167 SingleQuote => op("'"),
169 Ident(sym, is_raw) => trees.push(TokenTree::Ident(Ident { sym, is_raw, span })),
171 let ident = symbol::Ident::new(name, span).without_first_quote();
173 TokenTree::Punct(Punct { ch: b'\'', joint: true, span }),
174 TokenTree::Ident(Ident { sym: ident.name, is_raw: false, span }),
177 Literal(token::Lit { kind, symbol, suffix }) => {
178 trees.push(TokenTree::Literal(self::Literal {
179 kind: FromInternal::from_internal(kind),
185 DocComment(_, attr_style, data) => {
186 let mut escaped = String::new();
187 for ch in data.as_str().chars() {
188 escaped.extend(ch.escape_debug());
191 Ident(sym::doc, false),
193 TokenKind::lit(token::Str, Symbol::intern(&escaped), None),
196 .map(|kind| tokenstream::TokenTree::token_alone(kind, span))
198 trees.push(TokenTree::Punct(Punct { ch: b'#', joint: false, span }));
199 if attr_style == ast::AttrStyle::Inner {
200 trees.push(TokenTree::Punct(Punct { ch: b'!', joint: false, span }));
202 trees.push(TokenTree::Group(Group {
203 delimiter: pm::Delimiter::Bracket,
204 stream: Some(stream),
205 span: DelimSpan::from_single(span),
209 Interpolated(nt) if let NtIdent(ident, is_raw) = *nt => {
210 trees.push(TokenTree::Ident(Ident { sym: ident.name, is_raw, span: ident.span }))
213 Interpolated(nt) => {
214 let stream = TokenStream::from_nonterminal_ast(&nt);
215 // A hack used to pass AST fragments to attribute and derive
216 // macros as a single nonterminal token instead of a token
217 // stream. Such token needs to be "unwrapped" and not
218 // represented as a delimited group.
219 // FIXME: It needs to be removed, but there are some
220 // compatibility issues (see #73345).
221 if crate::base::nt_pretty_printing_compatibility_hack(&nt, rustc.sess()) {
222 trees.extend(Self::from_internal((stream, rustc)));
224 trees.push(TokenTree::Group(Group {
225 delimiter: pm::Delimiter::None,
226 stream: Some(stream),
227 span: DelimSpan::from_single(span),
232 OpenDelim(..) | CloseDelim(..) => unreachable!(),
233 Eof => unreachable!(),
240 impl ToInternal<TokenStream> for (TokenTree<TokenStream, Span, Symbol>, &mut Rustc<'_, '_>) {
241 fn to_internal(self) -> TokenStream {
242 use rustc_ast::token::*;
244 let (tree, rustc) = self;
245 let (ch, joint, span) = match tree {
246 TokenTree::Punct(Punct { ch, joint, span }) => (ch, joint, span),
247 TokenTree::Group(Group { delimiter, stream, span: DelimSpan { open, close, .. } }) => {
248 return tokenstream::TokenStream::delimited(
249 tokenstream::DelimSpan { open, close },
250 delimiter.to_internal(),
251 stream.unwrap_or_default(),
254 TokenTree::Ident(self::Ident { sym, is_raw, span }) => {
255 rustc.sess().symbol_gallery.insert(sym, span);
256 return tokenstream::TokenStream::token_alone(Ident(sym, is_raw), span);
258 TokenTree::Literal(self::Literal {
259 kind: self::LitKind::Integer,
263 }) if symbol.as_str().starts_with('-') => {
264 let minus = BinOp(BinOpToken::Minus);
265 let symbol = Symbol::intern(&symbol.as_str()[1..]);
266 let integer = TokenKind::lit(token::Integer, symbol, suffix);
267 let a = tokenstream::TokenTree::token_alone(minus, span);
268 let b = tokenstream::TokenTree::token_alone(integer, span);
269 return [a, b].into_iter().collect();
271 TokenTree::Literal(self::Literal {
272 kind: self::LitKind::Float,
276 }) if symbol.as_str().starts_with('-') => {
277 let minus = BinOp(BinOpToken::Minus);
278 let symbol = Symbol::intern(&symbol.as_str()[1..]);
279 let float = TokenKind::lit(token::Float, symbol, suffix);
280 let a = tokenstream::TokenTree::token_alone(minus, span);
281 let b = tokenstream::TokenTree::token_alone(float, span);
282 return [a, b].into_iter().collect();
284 TokenTree::Literal(self::Literal { kind, symbol, suffix, span }) => {
285 return tokenstream::TokenStream::token_alone(
286 TokenKind::lit(kind.to_internal(), symbol, suffix),
292 let kind = match ch {
299 b'-' => BinOp(Minus),
301 b'/' => BinOp(Slash),
302 b'%' => BinOp(Percent),
303 b'^' => BinOp(Caret),
314 b'\'' => SingleQuote,
319 tokenstream::TokenStream::token_joint(kind, span)
321 tokenstream::TokenStream::token_alone(kind, span)
326 impl ToInternal<rustc_errors::Level> for Level {
327 fn to_internal(self) -> rustc_errors::Level {
329 Level::Error => rustc_errors::Level::Error { lint: false },
330 Level::Warning => rustc_errors::Level::Warning(None),
331 Level::Note => rustc_errors::Level::Note,
332 Level::Help => rustc_errors::Level::Help,
333 _ => unreachable!("unknown proc_macro::Level variant: {:?}", self),
338 pub struct FreeFunctions;
340 pub(crate) struct Rustc<'a, 'b> {
341 ecx: &'a mut ExtCtxt<'b>,
346 rebased_spans: FxHashMap<usize, Span>,
349 impl<'a, 'b> Rustc<'a, 'b> {
350 pub fn new(ecx: &'a mut ExtCtxt<'b>) -> Self {
351 let expn_data = ecx.current_expansion.id.expn_data();
353 def_site: ecx.with_def_site_ctxt(expn_data.def_site),
354 call_site: ecx.with_call_site_ctxt(expn_data.call_site),
355 mixed_site: ecx.with_mixed_site_ctxt(expn_data.call_site),
356 krate: expn_data.macro_def_id.unwrap().krate,
357 rebased_spans: FxHashMap::default(),
362 fn sess(&self) -> &ParseSess {
363 self.ecx.parse_sess()
367 impl server::Types for Rustc<'_, '_> {
368 type FreeFunctions = FreeFunctions;
369 type TokenStream = TokenStream;
370 type SourceFile = Lrc<SourceFile>;
371 type MultiSpan = Vec<Span>;
372 type Diagnostic = Diagnostic;
374 type Symbol = Symbol;
377 impl server::FreeFunctions for Rustc<'_, '_> {
378 fn track_env_var(&mut self, var: &str, value: Option<&str>) {
382 .insert((Symbol::intern(var), value.map(Symbol::intern)));
385 fn track_path(&mut self, path: &str) {
386 self.sess().file_depinfo.borrow_mut().insert(Symbol::intern(path));
389 fn literal_from_str(&mut self, s: &str) -> Result<Literal<Self::Span, Self::Symbol>, ()> {
390 let name = FileName::proc_macro_source_code(s);
391 let mut parser = rustc_parse::new_parser_from_source_str(self.sess(), name, s.to_owned());
393 let first_span = parser.token.span.data();
394 let minus_present = parser.eat(&token::BinOp(token::Minus));
396 let lit_span = parser.token.span.data();
397 let token::Literal(mut lit) = parser.token.kind else {
401 // Check no comment or whitespace surrounding the (possibly negative)
402 // literal, or more tokens after it.
403 if (lit_span.hi.0 - first_span.lo.0) as usize != s.len() {
408 // If minus is present, check no comment or whitespace in between it
409 // and the literal token.
410 if first_span.hi.0 != lit_span.lo.0 {
414 // Check literal is a kind we allow to be negated in a proc macro token.
417 | token::LitKind::Byte
418 | token::LitKind::Char
419 | token::LitKind::Str
420 | token::LitKind::StrRaw(_)
421 | token::LitKind::ByteStr
422 | token::LitKind::ByteStrRaw(_)
423 | token::LitKind::Err => return Err(()),
424 token::LitKind::Integer | token::LitKind::Float => {}
427 // Synthesize a new symbol that includes the minus sign.
428 let symbol = Symbol::intern(&s[..1 + lit.symbol.as_str().len()]);
429 lit = token::Lit::new(lit.kind, symbol, lit.suffix);
431 let token::Lit { kind, symbol, suffix } = lit;
433 kind: FromInternal::from_internal(kind),
436 span: self.call_site,
441 impl server::TokenStream for Rustc<'_, '_> {
442 fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
446 fn from_str(&mut self, src: &str) -> Self::TokenStream {
447 parse_stream_from_source_str(
448 FileName::proc_macro_source_code(src),
451 Some(self.call_site),
455 fn to_string(&mut self, stream: &Self::TokenStream) -> String {
456 pprust::tts_to_string(stream)
459 fn expand_expr(&mut self, stream: &Self::TokenStream) -> Result<Self::TokenStream, ()> {
460 // Parse the expression from our tokenstream.
461 let expr: PResult<'_, _> = try {
462 let mut p = rustc_parse::stream_to_parser(
465 Some("proc_macro expand expr"),
467 let expr = p.parse_expr()?;
468 if p.token != token::Eof {
473 let expr = expr.map_err(|mut err| {
477 // Perform eager expansion on the expression.
481 .fully_expand_fragment(crate::expand::AstFragment::Expr(expr))
484 // NOTE: For now, limit `expand_expr` to exclusively expand to literals.
485 // This may be relaxed in the future.
486 // We don't use `TokenStream::from_ast` as the tokenstream currently cannot
487 // be recovered in the general case.
489 ast::ExprKind::Lit(l) if l.token.kind == token::Bool => Ok(
490 tokenstream::TokenStream::token_alone(token::Ident(l.token.symbol, false), l.span),
492 ast::ExprKind::Lit(l) => {
493 Ok(tokenstream::TokenStream::token_alone(token::Literal(l.token), l.span))
495 ast::ExprKind::Unary(ast::UnOp::Neg, e) => match &e.kind {
496 ast::ExprKind::Lit(l) => match l.token {
497 token::Lit { kind: token::Integer | token::Float, .. } => {
498 Ok(Self::TokenStream::from_iter([
499 // FIXME: The span of the `-` token is lost when
500 // parsing, so we cannot faithfully recover it here.
501 tokenstream::TokenTree::token_alone(token::BinOp(token::Minus), e.span),
502 tokenstream::TokenTree::token_alone(token::Literal(l.token), l.span),
515 tree: TokenTree<Self::TokenStream, Self::Span, Self::Symbol>,
516 ) -> Self::TokenStream {
517 (tree, &mut *self).to_internal()
522 base: Option<Self::TokenStream>,
523 trees: Vec<TokenTree<Self::TokenStream, Self::Span, Self::Symbol>>,
524 ) -> Self::TokenStream {
525 let mut builder = tokenstream::TokenStreamBuilder::new();
526 if let Some(base) = base {
530 builder.push((tree, &mut *self).to_internal());
537 base: Option<Self::TokenStream>,
538 streams: Vec<Self::TokenStream>,
539 ) -> Self::TokenStream {
540 let mut builder = tokenstream::TokenStreamBuilder::new();
541 if let Some(base) = base {
544 for stream in streams {
545 builder.push(stream);
552 stream: Self::TokenStream,
553 ) -> Vec<TokenTree<Self::TokenStream, Self::Span, Self::Symbol>> {
554 FromInternal::from_internal((stream, self))
558 impl server::SourceFile for Rustc<'_, '_> {
559 fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
560 Lrc::ptr_eq(file1, file2)
563 fn path(&mut self, file: &Self::SourceFile) -> String {
565 FileName::Real(ref name) => name
567 .expect("attempting to get a file path in an imported file in `proc_macro::SourceFile::path`")
569 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
571 _ => file.name.prefer_local().to_string(),
575 fn is_real(&mut self, file: &Self::SourceFile) -> bool {
580 impl server::MultiSpan for Rustc<'_, '_> {
581 fn new(&mut self) -> Self::MultiSpan {
585 fn push(&mut self, spans: &mut Self::MultiSpan, span: Self::Span) {
590 impl server::Diagnostic for Rustc<'_, '_> {
591 fn new(&mut self, level: Level, msg: &str, spans: Self::MultiSpan) -> Self::Diagnostic {
592 let mut diag = Diagnostic::new(level.to_internal(), msg);
593 diag.set_span(MultiSpan::from_spans(spans));
599 diag: &mut Self::Diagnostic,
602 spans: Self::MultiSpan,
604 diag.sub(level.to_internal(), msg, MultiSpan::from_spans(spans), None);
607 fn emit(&mut self, mut diag: Self::Diagnostic) {
608 self.sess().span_diagnostic.emit_diagnostic(&mut diag);
612 impl server::Span for Rustc<'_, '_> {
613 fn debug(&mut self, span: Self::Span) -> String {
614 if self.ecx.ecfg.span_debug {
615 format!("{:?}", span)
617 format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
621 fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
622 self.sess().source_map().lookup_char_pos(span.lo()).file
625 fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
626 span.parent_callsite()
629 fn source(&mut self, span: Self::Span) -> Self::Span {
630 span.source_callsite()
633 fn start(&mut self, span: Self::Span) -> LineColumn {
634 let loc = self.sess().source_map().lookup_char_pos(span.lo());
635 LineColumn { line: loc.line, column: loc.col.to_usize() }
638 fn end(&mut self, span: Self::Span) -> LineColumn {
639 let loc = self.sess().source_map().lookup_char_pos(span.hi());
640 LineColumn { line: loc.line, column: loc.col.to_usize() }
643 fn before(&mut self, span: Self::Span) -> Self::Span {
647 fn after(&mut self, span: Self::Span) -> Self::Span {
651 fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
652 let self_loc = self.sess().source_map().lookup_char_pos(first.lo());
653 let other_loc = self.sess().source_map().lookup_char_pos(second.lo());
655 if self_loc.file.name != other_loc.file.name {
659 Some(first.to(second))
667 ) -> Option<Self::Span> {
668 let length = span.hi().to_usize() - span.lo().to_usize();
670 let start = match start {
671 Bound::Included(lo) => lo,
672 Bound::Excluded(lo) => lo.checked_add(1)?,
673 Bound::Unbounded => 0,
676 let end = match end {
677 Bound::Included(hi) => hi.checked_add(1)?,
678 Bound::Excluded(hi) => hi,
679 Bound::Unbounded => length,
682 // Bounds check the values, preventing addition overflow and OOB spans.
683 if start > u32::MAX as usize
684 || end > u32::MAX as usize
685 || (u32::MAX - start as u32) < span.lo().to_u32()
686 || (u32::MAX - end as u32) < span.lo().to_u32()
693 let new_lo = span.lo() + BytePos::from_usize(start);
694 let new_hi = span.lo() + BytePos::from_usize(end);
695 Some(span.with_lo(new_lo).with_hi(new_hi))
698 fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
699 span.with_ctxt(at.ctxt())
702 fn source_text(&mut self, span: Self::Span) -> Option<String> {
703 self.sess().source_map().span_to_snippet(span).ok()
705 /// Saves the provided span into the metadata of
706 /// *the crate we are currently compiling*, which must
707 /// be a proc-macro crate. This id can be passed to
708 /// `recover_proc_macro_span` when our current crate
709 /// is *run* as a proc-macro.
711 /// Let's suppose that we have two crates - `my_client`
712 /// and `my_proc_macro`. The `my_proc_macro` crate
713 /// contains a procedural macro `my_macro`, which
714 /// is implemented as: `quote! { "hello" }`
716 /// When we *compile* `my_proc_macro`, we will execute
717 /// the `quote` proc-macro. This will save the span of
718 /// "hello" into the metadata of `my_proc_macro`. As a result,
719 /// the body of `my_proc_macro` (after expansion) will end
720 /// up containing a call that looks like this:
721 /// `proc_macro::Ident::new("hello", proc_macro::Span::recover_proc_macro_span(0))`
723 /// where `0` is the id returned by this function.
724 /// When `my_proc_macro` *executes* (during the compilation of `my_client`),
725 /// the call to `recover_proc_macro_span` will load the corresponding
726 /// span from the metadata of `my_proc_macro` (which we have access to,
727 /// since we've loaded `my_proc_macro` from disk in order to execute it).
728 /// In this way, we have obtained a span pointing into `my_proc_macro`
729 fn save_span(&mut self, span: Self::Span) -> usize {
730 self.sess().save_proc_macro_span(span)
733 fn recover_proc_macro_span(&mut self, id: usize) -> Self::Span {
734 let (resolver, krate, def_site) = (&*self.ecx.resolver, self.krate, self.def_site);
735 *self.rebased_spans.entry(id).or_insert_with(|| {
736 // FIXME: `SyntaxContext` for spans from proc macro crates is lost during encoding,
737 // replace it with a def-site context until we are encoding it properly.
738 resolver.get_proc_macro_quoted_span(krate, id).with_ctxt(def_site.ctxt())
743 impl server::Symbol for Rustc<'_, '_> {
744 fn normalize_and_validate_ident(&mut self, string: &str) -> Result<Self::Symbol, ()> {
745 let sym = nfc_normalize(string);
746 if rustc_lexer::is_ident(sym.as_str()) { Ok(sym) } else { Err(()) }
750 impl server::Server for Rustc<'_, '_> {
751 fn globals(&mut self) -> ExpnGlobals<Self::Span> {
753 def_site: self.def_site,
754 call_site: self.call_site,
755 mixed_site: self.mixed_site,
759 fn intern_symbol(string: &str) -> Self::Symbol {
760 Symbol::intern(string)
763 fn with_symbol_string(symbol: &Self::Symbol, f: impl FnOnce(&str)) {