2 use crate::ext::base::ExtCtxt;
3 use crate::parse::{self, token, ParseSess};
4 use crate::parse::lexer::comments;
5 use crate::tokenstream::{self, DelimSpan, IsJoint::*, TokenStream, TreeAndJoint};
7 use errors::{Diagnostic, DiagnosticBuilder};
8 use rustc_data_structures::sync::Lrc;
9 use syntax_pos::{BytePos, FileName, MultiSpan, Pos, SourceFile, Span};
10 use syntax_pos::hygiene::{SyntaxContext, Transparency};
11 use syntax_pos::symbol::{kw, sym, Symbol};
13 use proc_macro::{Delimiter, Level, LineColumn, Spacing};
14 use proc_macro::bridge::{server, TokenTree};
15 use std::{ascii, panic};
18 trait FromInternal<T> {
19 fn from_internal(x: T) -> Self;
23 fn to_internal(self) -> T;
26 impl FromInternal<token::DelimToken> for Delimiter {
27 fn from_internal(delim: token::DelimToken) -> Delimiter {
29 token::Paren => Delimiter::Parenthesis,
30 token::Brace => Delimiter::Brace,
31 token::Bracket => Delimiter::Bracket,
32 token::NoDelim => Delimiter::None,
37 impl ToInternal<token::DelimToken> for Delimiter {
38 fn to_internal(self) -> token::DelimToken {
40 Delimiter::Parenthesis => token::Paren,
41 Delimiter::Brace => token::Brace,
42 Delimiter::Bracket => token::Bracket,
43 Delimiter::None => token::NoDelim,
48 impl FromInternal<(TreeAndJoint, &'_ ParseSess, &'_ mut Vec<Self>)>
49 for TokenTree<Group, Punct, Ident, Literal>
51 fn from_internal(((tree, is_joint), sess, stack): (TreeAndJoint, &ParseSess, &mut Vec<Self>))
53 use crate::parse::token::*;
55 let joint = is_joint == Joint;
56 let Token { kind, span } = match tree {
57 tokenstream::TokenTree::Delimited(span, delim, tts) => {
58 let delimiter = Delimiter::from_internal(delim);
59 return TokenTree::Group(Group {
65 tokenstream::TokenTree::Token(token) => token,
69 ($ty:ident { $($field:ident $(: $value:expr)*),+ $(,)? }) => (
70 TokenTree::$ty(self::$ty {
71 $($field $(: $value)*,)+
75 ($ty:ident::$method:ident($($value:expr),*)) => (
76 TokenTree::$ty(self::$ty::$method($($value,)* span))
81 tt!(Punct::new($a, joint))
83 ($a:expr, $b:expr) => {{
84 stack.push(tt!(Punct::new($b, joint)));
85 tt!(Punct::new($a, true))
87 ($a:expr, $b:expr, $c:expr) => {{
88 stack.push(tt!(Punct::new($c, joint)));
89 stack.push(tt!(Punct::new($b, true)));
90 tt!(Punct::new($a, true))
98 EqEq => op!('=', '='),
102 AndAnd => op!('&', '&'),
103 OrOr => op!('|', '|'),
106 BinOp(Plus) => op!('+'),
107 BinOp(Minus) => op!('-'),
108 BinOp(Star) => op!('*'),
109 BinOp(Slash) => op!('/'),
110 BinOp(Percent) => op!('%'),
111 BinOp(Caret) => op!('^'),
112 BinOp(And) => op!('&'),
113 BinOp(Or) => op!('|'),
114 BinOp(Shl) => op!('<', '<'),
115 BinOp(Shr) => op!('>', '>'),
116 BinOpEq(Plus) => op!('+', '='),
117 BinOpEq(Minus) => op!('-', '='),
118 BinOpEq(Star) => op!('*', '='),
119 BinOpEq(Slash) => op!('/', '='),
120 BinOpEq(Percent) => op!('%', '='),
121 BinOpEq(Caret) => op!('^', '='),
122 BinOpEq(And) => op!('&', '='),
123 BinOpEq(Or) => op!('|', '='),
124 BinOpEq(Shl) => op!('<', '<', '='),
125 BinOpEq(Shr) => op!('>', '>', '='),
128 DotDot => op!('.', '.'),
129 DotDotDot => op!('.', '.', '.'),
130 DotDotEq => op!('.', '.', '='),
134 ModSep => op!(':', ':'),
135 RArrow => op!('-', '>'),
136 LArrow => op!('<', '-'),
137 FatArrow => op!('=', '>'),
140 Question => op!('?'),
141 SingleQuote => op!('\''),
143 Ident(name, false) if name == kw::DollarCrate => tt!(Ident::dollar_crate()),
144 Ident(name, is_raw) => tt!(Ident::new(name, is_raw)),
146 let ident = ast::Ident::new(name, span).without_first_quote();
147 stack.push(tt!(Ident::new(ident.name, false)));
148 tt!(Punct::new('\'', true))
150 Literal(lit) => tt!(Literal { lit }),
152 let style = comments::doc_comment_style(&c.as_str());
153 let stripped = comments::strip_doc_comment_decoration(&c.as_str());
154 let mut escaped = String::new();
155 for ch in stripped.chars() {
156 escaped.extend(ch.escape_debug());
159 Ident(sym::doc, false),
161 TokenKind::lit(token::Str, Symbol::intern(&escaped), None),
164 .map(|kind| tokenstream::TokenTree::token(kind, span))
166 stack.push(TokenTree::Group(Group {
167 delimiter: Delimiter::Bracket,
169 span: DelimSpan::from_single(span),
171 if style == ast::AttrStyle::Inner {
172 stack.push(tt!(Punct::new('!', false)));
174 tt!(Punct::new('#', false))
177 Interpolated(nt) => {
178 let stream = nt.to_tokenstream(sess, span);
179 TokenTree::Group(Group {
180 delimiter: Delimiter::None,
182 span: DelimSpan::from_single(span),
186 OpenDelim(..) | CloseDelim(..) => unreachable!(),
187 Whitespace | Comment | Shebang(..) | Eof => unreachable!(),
192 impl ToInternal<TokenStream> for TokenTree<Group, Punct, Ident, Literal> {
193 fn to_internal(self) -> TokenStream {
194 use crate::parse::token::*;
196 let (ch, joint, span) = match self {
197 TokenTree::Punct(Punct { ch, joint, span }) => (ch, joint, span),
198 TokenTree::Group(Group {
203 return tokenstream::TokenTree::Delimited(
205 delimiter.to_internal(),
210 TokenTree::Ident(self::Ident { sym, is_raw, span }) => {
211 return tokenstream::TokenTree::token(Ident(sym, is_raw), span).into();
213 TokenTree::Literal(self::Literal {
214 lit: token::Lit { kind: token::Integer, symbol, suffix },
216 }) if symbol.as_str().starts_with("-") => {
217 let minus = BinOp(BinOpToken::Minus);
218 let symbol = Symbol::intern(&symbol.as_str()[1..]);
219 let integer = TokenKind::lit(token::Integer, symbol, suffix);
220 let a = tokenstream::TokenTree::token(minus, span);
221 let b = tokenstream::TokenTree::token(integer, span);
222 return vec![a, b].into_iter().collect();
224 TokenTree::Literal(self::Literal {
225 lit: token::Lit { kind: token::Float, symbol, suffix },
227 }) if symbol.as_str().starts_with("-") => {
228 let minus = BinOp(BinOpToken::Minus);
229 let symbol = Symbol::intern(&symbol.as_str()[1..]);
230 let float = TokenKind::lit(token::Float, symbol, suffix);
231 let a = tokenstream::TokenTree::token(minus, span);
232 let b = tokenstream::TokenTree::token(float, span);
233 return vec![a, b].into_iter().collect();
235 TokenTree::Literal(self::Literal { lit, span }) => {
236 return tokenstream::TokenTree::token(Literal(lit), span).into()
240 let kind = match ch {
250 '%' => BinOp(Percent),
266 let tree = tokenstream::TokenTree::token(kind, span);
267 TokenStream::new(vec![(tree, if joint { Joint } else { NonJoint })])
271 impl ToInternal<errors::Level> for Level {
272 fn to_internal(self) -> errors::Level {
274 Level::Error => errors::Level::Error,
275 Level::Warning => errors::Level::Warning,
276 Level::Note => errors::Level::Note,
277 Level::Help => errors::Level::Help,
278 _ => unreachable!("unknown proc_macro::Level variant: {:?}", self),
284 pub struct TokenStreamIter {
285 cursor: tokenstream::Cursor,
286 stack: Vec<TokenTree<Group, Punct, Ident, Literal>>,
291 delimiter: Delimiter,
296 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
299 // NB. not using `Spacing` here because it doesn't implement `Hash`.
305 fn new(ch: char, joint: bool, span: Span) -> Punct {
306 const LEGAL_CHARS: &[char] = &['=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^',
307 '&', '|', '@', '.', ',', ';', ':', '#', '$', '?', '\''];
308 if !LEGAL_CHARS.contains(&ch) {
309 panic!("unsupported character `{:?}`", ch)
311 Punct { ch, joint, span }
315 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
323 fn is_valid(string: &str) -> bool {
324 let mut chars = string.chars();
325 if let Some(start) = chars.next() {
326 (start == '_' || start.is_xid_start())
327 && chars.all(|cont| cont == '_' || cont.is_xid_continue())
332 fn new(sym: Symbol, is_raw: bool, span: Span) -> Ident {
333 let string = sym.as_str();
334 if !Self::is_valid(&string) {
335 panic!("`{:?}` is not a valid identifier", string)
337 // Get rid of gensyms to conservatively check rawness on the string contents only.
338 if is_raw && !sym.as_interned_str().as_symbol().can_be_raw() {
339 panic!("`{}` cannot be a raw identifier", string);
341 Ident { sym, is_raw, span }
343 fn dollar_crate(span: Span) -> Ident {
344 // `$crate` is accepted as an ident only if it comes from the compiler.
345 Ident { sym: kw::DollarCrate, is_raw: false, span }
349 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
350 #[derive(Clone, Debug)]
356 pub(crate) struct Rustc<'a> {
363 pub fn new(cx: &'a ExtCtxt<'_>) -> Self {
364 // No way to determine def location for a proc macro right now, so use call location.
365 let location = cx.current_expansion.id.expn_info().unwrap().call_site;
366 let to_span = |transparency| {
368 SyntaxContext::empty()
369 .apply_mark_with_transparency(cx.current_expansion.id, transparency),
374 def_site: to_span(Transparency::Opaque),
375 call_site: to_span(Transparency::Transparent),
379 fn lit(&mut self, kind: token::LitKind, symbol: Symbol, suffix: Option<Symbol>) -> Literal {
381 lit: token::Lit::new(kind, symbol, suffix),
382 span: server::Span::call_site(self),
387 impl server::Types for Rustc<'_> {
388 type TokenStream = TokenStream;
389 type TokenStreamBuilder = tokenstream::TokenStreamBuilder;
390 type TokenStreamIter = TokenStreamIter;
394 type Literal = Literal;
395 type SourceFile = Lrc<SourceFile>;
396 type MultiSpan = Vec<Span>;
397 type Diagnostic = Diagnostic;
401 impl server::TokenStream for Rustc<'_> {
402 fn new(&mut self) -> Self::TokenStream {
405 fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
408 fn from_str(&mut self, src: &str) -> Self::TokenStream {
409 parse::parse_stream_from_source_str(
410 FileName::proc_macro_source_code(src),
413 Some(self.call_site),
416 fn to_string(&mut self, stream: &Self::TokenStream) -> String {
421 tree: TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>,
422 ) -> Self::TokenStream {
425 fn into_iter(&mut self, stream: Self::TokenStream) -> Self::TokenStreamIter {
427 cursor: stream.trees(),
433 impl server::TokenStreamBuilder for Rustc<'_> {
434 fn new(&mut self) -> Self::TokenStreamBuilder {
435 tokenstream::TokenStreamBuilder::new()
437 fn push(&mut self, builder: &mut Self::TokenStreamBuilder, stream: Self::TokenStream) {
438 builder.push(stream);
440 fn build(&mut self, builder: Self::TokenStreamBuilder) -> Self::TokenStream {
445 impl server::TokenStreamIter for Rustc<'_> {
448 iter: &mut Self::TokenStreamIter,
449 ) -> Option<TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>> {
451 let tree = iter.stack.pop().or_else(|| {
452 let next = iter.cursor.next_with_joint()?;
453 Some(TokenTree::from_internal((next, self.sess, &mut iter.stack)))
455 // HACK: The condition "dummy span + group with empty delimiter" represents an AST
456 // fragment approximately converted into a token stream. This may happen, for
457 // example, with inputs to proc macro attributes, including derives. Such "groups"
458 // need to flattened during iteration over stream's token trees.
459 // Eventually this needs to be removed in favor of keeping original token trees
460 // and not doing the roundtrip through AST.
461 if let TokenTree::Group(ref group) = tree {
462 if group.delimiter == Delimiter::None && group.span.entire().is_dummy() {
463 iter.cursor.append(group.stream.clone());
472 impl server::Group for Rustc<'_> {
473 fn new(&mut self, delimiter: Delimiter, stream: Self::TokenStream) -> Self::Group {
477 span: DelimSpan::from_single(server::Span::call_site(self)),
480 fn delimiter(&mut self, group: &Self::Group) -> Delimiter {
483 fn stream(&mut self, group: &Self::Group) -> Self::TokenStream {
486 fn span(&mut self, group: &Self::Group) -> Self::Span {
489 fn span_open(&mut self, group: &Self::Group) -> Self::Span {
492 fn span_close(&mut self, group: &Self::Group) -> Self::Span {
495 fn set_span(&mut self, group: &mut Self::Group, span: Self::Span) {
496 group.span = DelimSpan::from_single(span);
500 impl server::Punct for Rustc<'_> {
501 fn new(&mut self, ch: char, spacing: Spacing) -> Self::Punct {
502 Punct::new(ch, spacing == Spacing::Joint, server::Span::call_site(self))
504 fn as_char(&mut self, punct: Self::Punct) -> char {
507 fn spacing(&mut self, punct: Self::Punct) -> Spacing {
514 fn span(&mut self, punct: Self::Punct) -> Self::Span {
517 fn with_span(&mut self, punct: Self::Punct, span: Self::Span) -> Self::Punct {
518 Punct { span, ..punct }
522 impl server::Ident for Rustc<'_> {
523 fn new(&mut self, string: &str, span: Self::Span, is_raw: bool) -> Self::Ident {
524 Ident::new(Symbol::intern(string), is_raw, span)
526 fn span(&mut self, ident: Self::Ident) -> Self::Span {
529 fn with_span(&mut self, ident: Self::Ident, span: Self::Span) -> Self::Ident {
530 Ident { span, ..ident }
534 impl server::Literal for Rustc<'_> {
535 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
536 fn debug(&mut self, literal: &Self::Literal) -> String {
537 format!("{:?}", literal)
539 fn integer(&mut self, n: &str) -> Self::Literal {
540 self.lit(token::Integer, Symbol::intern(n), None)
542 fn typed_integer(&mut self, n: &str, kind: &str) -> Self::Literal {
543 self.lit(token::Integer, Symbol::intern(n), Some(Symbol::intern(kind)))
545 fn float(&mut self, n: &str) -> Self::Literal {
546 self.lit(token::Float, Symbol::intern(n), None)
548 fn f32(&mut self, n: &str) -> Self::Literal {
549 self.lit(token::Float, Symbol::intern(n), Some(sym::f32))
551 fn f64(&mut self, n: &str) -> Self::Literal {
552 self.lit(token::Float, Symbol::intern(n), Some(sym::f64))
554 fn string(&mut self, string: &str) -> Self::Literal {
555 let mut escaped = String::new();
556 for ch in string.chars() {
557 escaped.extend(ch.escape_debug());
559 self.lit(token::Str, Symbol::intern(&escaped), None)
561 fn character(&mut self, ch: char) -> Self::Literal {
562 let mut escaped = String::new();
563 escaped.extend(ch.escape_unicode());
564 self.lit(token::Char, Symbol::intern(&escaped), None)
566 fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
570 .flat_map(ascii::escape_default)
571 .map(Into::<char>::into)
572 .collect::<String>();
573 self.lit(token::ByteStr, Symbol::intern(&string), None)
575 fn span(&mut self, literal: &Self::Literal) -> Self::Span {
578 fn set_span(&mut self, literal: &mut Self::Literal, span: Self::Span) {
583 literal: &Self::Literal,
586 ) -> Option<Self::Span> {
587 let span = literal.span;
588 let length = span.hi().to_usize() - span.lo().to_usize();
590 let start = match start {
591 Bound::Included(lo) => lo,
592 Bound::Excluded(lo) => lo + 1,
593 Bound::Unbounded => 0,
596 let end = match end {
597 Bound::Included(hi) => hi + 1,
598 Bound::Excluded(hi) => hi,
599 Bound::Unbounded => length,
602 // Bounds check the values, preventing addition overflow and OOB spans.
603 if start > u32::max_value() as usize
604 || end > u32::max_value() as usize
605 || (u32::max_value() - start as u32) < span.lo().to_u32()
606 || (u32::max_value() - end as u32) < span.lo().to_u32()
613 let new_lo = span.lo() + BytePos::from_usize(start);
614 let new_hi = span.lo() + BytePos::from_usize(end);
615 Some(span.with_lo(new_lo).with_hi(new_hi))
619 impl server::SourceFile for Rustc<'_> {
620 fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
621 Lrc::ptr_eq(file1, file2)
623 fn path(&mut self, file: &Self::SourceFile) -> String {
625 FileName::Real(ref path) => path
627 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
629 _ => file.name.to_string(),
632 fn is_real(&mut self, file: &Self::SourceFile) -> bool {
637 impl server::MultiSpan for Rustc<'_> {
638 fn new(&mut self) -> Self::MultiSpan {
641 fn push(&mut self, spans: &mut Self::MultiSpan, span: Self::Span) {
646 impl server::Diagnostic for Rustc<'_> {
647 fn new(&mut self, level: Level, msg: &str, spans: Self::MultiSpan) -> Self::Diagnostic {
648 let mut diag = Diagnostic::new(level.to_internal(), msg);
649 diag.set_span(MultiSpan::from_spans(spans));
654 diag: &mut Self::Diagnostic,
657 spans: Self::MultiSpan,
659 diag.sub(level.to_internal(), msg, MultiSpan::from_spans(spans), None);
661 fn emit(&mut self, diag: Self::Diagnostic) {
662 DiagnosticBuilder::new_diagnostic(&self.sess.span_diagnostic, diag).emit()
666 impl server::Span for Rustc<'_> {
667 fn debug(&mut self, span: Self::Span) -> String {
668 format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
670 fn def_site(&mut self) -> Self::Span {
673 fn call_site(&mut self) -> Self::Span {
676 fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
677 self.sess.source_map().lookup_char_pos(span.lo()).file
679 fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
680 span.ctxt().outer_expn_info().map(|i| i.call_site)
682 fn source(&mut self, span: Self::Span) -> Self::Span {
683 span.source_callsite()
685 fn start(&mut self, span: Self::Span) -> LineColumn {
686 let loc = self.sess.source_map().lookup_char_pos(span.lo());
689 column: loc.col.to_usize(),
692 fn end(&mut self, span: Self::Span) -> LineColumn {
693 let loc = self.sess.source_map().lookup_char_pos(span.hi());
696 column: loc.col.to_usize(),
699 fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
700 let self_loc = self.sess.source_map().lookup_char_pos(first.lo());
701 let other_loc = self.sess.source_map().lookup_char_pos(second.lo());
703 if self_loc.file.name != other_loc.file.name {
707 Some(first.to(second))
709 fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
710 span.with_ctxt(at.ctxt())
712 fn source_text(&mut self, span: Self::Span) -> Option<String> {
713 self.sess.source_map().span_to_snippet(span).ok()