1 use errors::{Diagnostic, DiagnosticBuilder};
5 use proc_macro::bridge::{server, TokenTree};
6 use proc_macro::{Delimiter, Level, LineColumn, Spacing};
8 use rustc_data_structures::sync::Lrc;
12 use syntax::ext::base::ExtCtxt;
13 use syntax::parse::lexer::comments;
14 use syntax::parse::{self, token, ParseSess};
15 use syntax::tokenstream::{self, DelimSpan, IsJoint::*, TokenStream, TreeAndJoint};
16 use syntax_pos::hygiene::{SyntaxContext, Transparency};
17 use syntax_pos::symbol::{kw, sym, Symbol};
18 use syntax_pos::{BytePos, FileName, MultiSpan, Pos, SourceFile, Span};
20 trait FromInternal<T> {
21 fn from_internal(x: T) -> Self;
25 fn to_internal(self) -> T;
28 impl FromInternal<token::DelimToken> for Delimiter {
29 fn from_internal(delim: token::DelimToken) -> Delimiter {
31 token::Paren => Delimiter::Parenthesis,
32 token::Brace => Delimiter::Brace,
33 token::Bracket => Delimiter::Bracket,
34 token::NoDelim => Delimiter::None,
39 impl ToInternal<token::DelimToken> for Delimiter {
40 fn to_internal(self) -> token::DelimToken {
42 Delimiter::Parenthesis => token::Paren,
43 Delimiter::Brace => token::Brace,
44 Delimiter::Bracket => token::Bracket,
45 Delimiter::None => token::NoDelim,
50 impl FromInternal<(TreeAndJoint, &'_ ParseSess, &'_ mut Vec<Self>)>
51 for TokenTree<Group, Punct, Ident, Literal>
53 fn from_internal(((tree, is_joint), sess, stack): (TreeAndJoint, &ParseSess, &mut Vec<Self>))
55 use syntax::parse::token::*;
57 let joint = is_joint == Joint;
58 let Token { kind, span } = match tree {
59 tokenstream::TokenTree::Delimited(span, delim, tts) => {
60 let delimiter = Delimiter::from_internal(delim);
61 return TokenTree::Group(Group {
67 tokenstream::TokenTree::Token(token) => token,
71 ($ty:ident { $($field:ident $(: $value:expr)*),+ $(,)? }) => (
72 TokenTree::$ty(self::$ty {
73 $($field $(: $value)*,)*
77 ($ty:ident::$method:ident($($value:expr),*)) => (
78 TokenTree::$ty(self::$ty::$method($($value,)* span))
83 tt!(Punct::new($a, joint))
85 ($a:expr, $b:expr) => {{
86 stack.push(tt!(Punct::new($b, joint)));
87 tt!(Punct::new($a, true))
89 ($a:expr, $b:expr, $c:expr) => {{
90 stack.push(tt!(Punct::new($c, joint)));
91 stack.push(tt!(Punct::new($b, true)));
92 tt!(Punct::new($a, true))
100 EqEq => op!('=', '='),
104 AndAnd => op!('&', '&'),
105 OrOr => op!('|', '|'),
108 BinOp(Plus) => op!('+'),
109 BinOp(Minus) => op!('-'),
110 BinOp(Star) => op!('*'),
111 BinOp(Slash) => op!('/'),
112 BinOp(Percent) => op!('%'),
113 BinOp(Caret) => op!('^'),
114 BinOp(And) => op!('&'),
115 BinOp(Or) => op!('|'),
116 BinOp(Shl) => op!('<', '<'),
117 BinOp(Shr) => op!('>', '>'),
118 BinOpEq(Plus) => op!('+', '='),
119 BinOpEq(Minus) => op!('-', '='),
120 BinOpEq(Star) => op!('*', '='),
121 BinOpEq(Slash) => op!('/', '='),
122 BinOpEq(Percent) => op!('%', '='),
123 BinOpEq(Caret) => op!('^', '='),
124 BinOpEq(And) => op!('&', '='),
125 BinOpEq(Or) => op!('|', '='),
126 BinOpEq(Shl) => op!('<', '<', '='),
127 BinOpEq(Shr) => op!('>', '>', '='),
130 DotDot => op!('.', '.'),
131 DotDotDot => op!('.', '.', '.'),
132 DotDotEq => op!('.', '.', '='),
136 ModSep => op!(':', ':'),
137 RArrow => op!('-', '>'),
138 LArrow => op!('<', '-'),
139 FatArrow => op!('=', '>'),
142 Question => op!('?'),
143 SingleQuote => op!('\''),
145 Ident(name, false) if name == kw::DollarCrate => tt!(Ident::dollar_crate()),
146 Ident(name, is_raw) => tt!(Ident::new(name, is_raw)),
148 let ident = ast::Ident::new(name, span).without_first_quote();
149 stack.push(tt!(Ident::new(ident.name, false)));
150 tt!(Punct::new('\'', true))
152 Literal(lit) => tt!(Literal { lit }),
154 let style = comments::doc_comment_style(&c.as_str());
155 let stripped = comments::strip_doc_comment_decoration(&c.as_str());
156 let mut escaped = String::new();
157 for ch in stripped.chars() {
158 escaped.extend(ch.escape_debug());
161 Ident(sym::doc, false),
163 TokenKind::lit(token::Str, Symbol::intern(&escaped), None),
166 .map(|kind| tokenstream::TokenTree::token(span, kind))
168 stack.push(TokenTree::Group(Group {
169 delimiter: Delimiter::Bracket,
171 span: DelimSpan::from_single(span),
173 if style == ast::AttrStyle::Inner {
174 stack.push(tt!(Punct::new('!', false)));
176 tt!(Punct::new('#', false))
179 Interpolated(nt) => {
180 let stream = nt.to_tokenstream(sess, span);
181 TokenTree::Group(Group {
182 delimiter: Delimiter::None,
184 span: DelimSpan::from_single(span),
188 OpenDelim(..) | CloseDelim(..) => unreachable!(),
189 Whitespace | Comment | Shebang(..) | Eof => unreachable!(),
194 impl ToInternal<TokenStream> for TokenTree<Group, Punct, Ident, Literal> {
195 fn to_internal(self) -> TokenStream {
196 use syntax::parse::token::*;
198 let (ch, joint, span) = match self {
199 TokenTree::Punct(Punct { ch, joint, span }) => (ch, joint, span),
200 TokenTree::Group(Group {
205 return tokenstream::TokenTree::Delimited(
207 delimiter.to_internal(),
212 TokenTree::Ident(self::Ident { sym, is_raw, span }) => {
213 return tokenstream::TokenTree::token(span, Ident(sym, is_raw)).into();
215 TokenTree::Literal(self::Literal {
216 lit: token::Lit { kind: token::Integer, symbol, suffix },
218 }) if symbol.as_str().starts_with("-") => {
219 let minus = BinOp(BinOpToken::Minus);
220 let symbol = Symbol::intern(&symbol.as_str()[1..]);
221 let integer = TokenKind::lit(token::Integer, symbol, suffix);
222 let a = tokenstream::TokenTree::token(span, minus);
223 let b = tokenstream::TokenTree::token(span, integer);
224 return vec![a, b].into_iter().collect();
226 TokenTree::Literal(self::Literal {
227 lit: token::Lit { kind: token::Float, symbol, suffix },
229 }) if symbol.as_str().starts_with("-") => {
230 let minus = BinOp(BinOpToken::Minus);
231 let symbol = Symbol::intern(&symbol.as_str()[1..]);
232 let float = TokenKind::lit(token::Float, symbol, suffix);
233 let a = tokenstream::TokenTree::token(span, minus);
234 let b = tokenstream::TokenTree::token(span, float);
235 return vec![a, b].into_iter().collect();
237 TokenTree::Literal(self::Literal { lit, span }) => {
238 return tokenstream::TokenTree::token(span, Literal(lit)).into()
242 let kind = match ch {
252 '%' => BinOp(Percent),
268 let tree = tokenstream::TokenTree::token(span, kind);
269 TokenStream::new(vec![(tree, if joint { Joint } else { NonJoint })])
273 impl ToInternal<errors::Level> for Level {
274 fn to_internal(self) -> errors::Level {
276 Level::Error => errors::Level::Error,
277 Level::Warning => errors::Level::Warning,
278 Level::Note => errors::Level::Note,
279 Level::Help => errors::Level::Help,
280 _ => unreachable!("unknown proc_macro::Level variant: {:?}", self),
286 pub struct TokenStreamIter {
287 cursor: tokenstream::Cursor,
288 stack: Vec<TokenTree<Group, Punct, Ident, Literal>>,
293 delimiter: Delimiter,
298 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
301 // NB. not using `Spacing` here because it doesn't implement `Hash`.
307 fn new(ch: char, joint: bool, span: Span) -> Punct {
308 const LEGAL_CHARS: &[char] = &['=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^',
309 '&', '|', '@', '.', ',', ';', ':', '#', '$', '?', '\''];
310 if !LEGAL_CHARS.contains(&ch) {
311 panic!("unsupported character `{:?}`", ch)
313 Punct { ch, joint, span }
317 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
325 fn is_valid(string: &str) -> bool {
326 let mut chars = string.chars();
327 if let Some(start) = chars.next() {
328 (start == '_' || start.is_xid_start())
329 && chars.all(|cont| cont == '_' || cont.is_xid_continue())
334 fn new(sym: Symbol, is_raw: bool, span: Span) -> Ident {
335 let string = sym.as_str();
336 if !Self::is_valid(&string) {
337 panic!("`{:?}` is not a valid identifier", string)
339 // Get rid of gensyms to conservatively check rawness on the string contents only.
340 if is_raw && !sym.as_interned_str().as_symbol().can_be_raw() {
341 panic!("`{}` cannot be a raw identifier", string);
343 Ident { sym, is_raw, span }
345 fn dollar_crate(span: Span) -> Ident {
346 // `$crate` is accepted as an ident only if it comes from the compiler.
347 Ident { sym: kw::DollarCrate, is_raw: false, span }
351 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
352 #[derive(Clone, Debug)]
358 pub(crate) struct Rustc<'a> {
365 pub fn new(cx: &'a ExtCtxt<'_>) -> Self {
366 // No way to determine def location for a proc macro right now, so use call location.
367 let location = cx.current_expansion.mark.expn_info().unwrap().call_site;
368 let to_span = |transparency| {
370 SyntaxContext::empty()
371 .apply_mark_with_transparency(cx.current_expansion.mark, transparency),
376 def_site: to_span(Transparency::Opaque),
377 call_site: to_span(Transparency::Transparent),
381 fn lit(&mut self, kind: token::LitKind, symbol: Symbol, suffix: Option<Symbol>) -> Literal {
383 lit: token::Lit::new(kind, symbol, suffix),
384 span: server::Span::call_site(self),
389 impl server::Types for Rustc<'_> {
390 type TokenStream = TokenStream;
391 type TokenStreamBuilder = tokenstream::TokenStreamBuilder;
392 type TokenStreamIter = TokenStreamIter;
396 type Literal = Literal;
397 type SourceFile = Lrc<SourceFile>;
398 type MultiSpan = Vec<Span>;
399 type Diagnostic = Diagnostic;
403 impl server::TokenStream for Rustc<'_> {
404 fn new(&mut self) -> Self::TokenStream {
407 fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
410 fn from_str(&mut self, src: &str) -> Self::TokenStream {
411 parse::parse_stream_from_source_str(
412 FileName::proc_macro_source_code(src.clone()),
415 Some(self.call_site),
418 fn to_string(&mut self, stream: &Self::TokenStream) -> String {
423 tree: TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>,
424 ) -> Self::TokenStream {
427 fn into_iter(&mut self, stream: Self::TokenStream) -> Self::TokenStreamIter {
429 cursor: stream.trees(),
435 impl server::TokenStreamBuilder for Rustc<'_> {
436 fn new(&mut self) -> Self::TokenStreamBuilder {
437 tokenstream::TokenStreamBuilder::new()
439 fn push(&mut self, builder: &mut Self::TokenStreamBuilder, stream: Self::TokenStream) {
440 builder.push(stream);
442 fn build(&mut self, builder: Self::TokenStreamBuilder) -> Self::TokenStream {
447 impl server::TokenStreamIter for Rustc<'_> {
450 iter: &mut Self::TokenStreamIter,
451 ) -> Option<TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>> {
453 let tree = iter.stack.pop().or_else(|| {
454 let next = iter.cursor.next_with_joint()?;
455 Some(TokenTree::from_internal((next, self.sess, &mut iter.stack)))
457 // HACK: The condition "dummy span + group with empty delimiter" represents an AST
458 // fragment approximately converted into a token stream. This may happen, for
459 // example, with inputs to proc macro attributes, including derives. Such "groups"
460 // need to flattened during iteration over stream's token trees.
461 // Eventually this needs to be removed in favor of keeping original token trees
462 // and not doing the roundtrip through AST.
463 if let TokenTree::Group(ref group) = tree {
464 if group.delimiter == Delimiter::None && group.span.entire().is_dummy() {
465 iter.cursor.append(group.stream.clone());
474 impl server::Group for Rustc<'_> {
475 fn new(&mut self, delimiter: Delimiter, stream: Self::TokenStream) -> Self::Group {
479 span: DelimSpan::from_single(server::Span::call_site(self)),
482 fn delimiter(&mut self, group: &Self::Group) -> Delimiter {
485 fn stream(&mut self, group: &Self::Group) -> Self::TokenStream {
488 fn span(&mut self, group: &Self::Group) -> Self::Span {
491 fn span_open(&mut self, group: &Self::Group) -> Self::Span {
494 fn span_close(&mut self, group: &Self::Group) -> Self::Span {
497 fn set_span(&mut self, group: &mut Self::Group, span: Self::Span) {
498 group.span = DelimSpan::from_single(span);
502 impl server::Punct for Rustc<'_> {
503 fn new(&mut self, ch: char, spacing: Spacing) -> Self::Punct {
504 Punct::new(ch, spacing == Spacing::Joint, server::Span::call_site(self))
506 fn as_char(&mut self, punct: Self::Punct) -> char {
509 fn spacing(&mut self, punct: Self::Punct) -> Spacing {
516 fn span(&mut self, punct: Self::Punct) -> Self::Span {
519 fn with_span(&mut self, punct: Self::Punct, span: Self::Span) -> Self::Punct {
520 Punct { span, ..punct }
524 impl server::Ident for Rustc<'_> {
525 fn new(&mut self, string: &str, span: Self::Span, is_raw: bool) -> Self::Ident {
526 Ident::new(Symbol::intern(string), is_raw, span)
528 fn span(&mut self, ident: Self::Ident) -> Self::Span {
531 fn with_span(&mut self, ident: Self::Ident, span: Self::Span) -> Self::Ident {
532 Ident { span, ..ident }
536 impl server::Literal for Rustc<'_> {
537 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
538 fn debug(&mut self, literal: &Self::Literal) -> String {
539 format!("{:?}", literal)
541 fn integer(&mut self, n: &str) -> Self::Literal {
542 self.lit(token::Integer, Symbol::intern(n), None)
544 fn typed_integer(&mut self, n: &str, kind: &str) -> Self::Literal {
545 self.lit(token::Integer, Symbol::intern(n), Some(Symbol::intern(kind)))
547 fn float(&mut self, n: &str) -> Self::Literal {
548 self.lit(token::Float, Symbol::intern(n), None)
550 fn f32(&mut self, n: &str) -> Self::Literal {
551 self.lit(token::Float, Symbol::intern(n), Some(Symbol::intern("f32")))
553 fn f64(&mut self, n: &str) -> Self::Literal {
554 self.lit(token::Float, Symbol::intern(n), Some(Symbol::intern("f64")))
556 fn string(&mut self, string: &str) -> Self::Literal {
557 let mut escaped = String::new();
558 for ch in string.chars() {
559 escaped.extend(ch.escape_debug());
561 self.lit(token::Str, Symbol::intern(&escaped), None)
563 fn character(&mut self, ch: char) -> Self::Literal {
564 let mut escaped = String::new();
565 escaped.extend(ch.escape_unicode());
566 self.lit(token::Char, Symbol::intern(&escaped), None)
568 fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
572 .flat_map(ascii::escape_default)
573 .map(Into::<char>::into)
574 .collect::<String>();
575 self.lit(token::ByteStr, Symbol::intern(&string), None)
577 fn span(&mut self, literal: &Self::Literal) -> Self::Span {
580 fn set_span(&mut self, literal: &mut Self::Literal, span: Self::Span) {
585 literal: &Self::Literal,
588 ) -> Option<Self::Span> {
589 let span = literal.span;
590 let length = span.hi().to_usize() - span.lo().to_usize();
592 let start = match start {
593 Bound::Included(lo) => lo,
594 Bound::Excluded(lo) => lo + 1,
595 Bound::Unbounded => 0,
598 let end = match end {
599 Bound::Included(hi) => hi + 1,
600 Bound::Excluded(hi) => hi,
601 Bound::Unbounded => length,
604 // Bounds check the values, preventing addition overflow and OOB spans.
605 if start > u32::max_value() as usize
606 || end > u32::max_value() as usize
607 || (u32::max_value() - start as u32) < span.lo().to_u32()
608 || (u32::max_value() - end as u32) < span.lo().to_u32()
615 let new_lo = span.lo() + BytePos::from_usize(start);
616 let new_hi = span.lo() + BytePos::from_usize(end);
617 Some(span.with_lo(new_lo).with_hi(new_hi))
621 impl server::SourceFile for Rustc<'_> {
622 fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
623 Lrc::ptr_eq(file1, file2)
625 fn path(&mut self, file: &Self::SourceFile) -> String {
627 FileName::Real(ref path) => path
629 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
631 _ => file.name.to_string(),
634 fn is_real(&mut self, file: &Self::SourceFile) -> bool {
639 impl server::MultiSpan for Rustc<'_> {
640 fn new(&mut self) -> Self::MultiSpan {
643 fn push(&mut self, spans: &mut Self::MultiSpan, span: Self::Span) {
648 impl server::Diagnostic for Rustc<'_> {
649 fn new(&mut self, level: Level, msg: &str, spans: Self::MultiSpan) -> Self::Diagnostic {
650 let mut diag = Diagnostic::new(level.to_internal(), msg);
651 diag.set_span(MultiSpan::from_spans(spans));
656 diag: &mut Self::Diagnostic,
659 spans: Self::MultiSpan,
661 diag.sub(level.to_internal(), msg, MultiSpan::from_spans(spans), None);
663 fn emit(&mut self, diag: Self::Diagnostic) {
664 DiagnosticBuilder::new_diagnostic(&self.sess.span_diagnostic, diag).emit()
668 impl server::Span for Rustc<'_> {
669 fn debug(&mut self, span: Self::Span) -> String {
670 format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
672 fn def_site(&mut self) -> Self::Span {
675 fn call_site(&mut self) -> Self::Span {
678 fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
679 self.sess.source_map().lookup_char_pos(span.lo()).file
681 fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
682 span.ctxt().outer_expn_info().map(|i| i.call_site)
684 fn source(&mut self, span: Self::Span) -> Self::Span {
685 span.source_callsite()
687 fn start(&mut self, span: Self::Span) -> LineColumn {
688 let loc = self.sess.source_map().lookup_char_pos(span.lo());
691 column: loc.col.to_usize(),
694 fn end(&mut self, span: Self::Span) -> LineColumn {
695 let loc = self.sess.source_map().lookup_char_pos(span.hi());
698 column: loc.col.to_usize(),
701 fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
702 let self_loc = self.sess.source_map().lookup_char_pos(first.lo());
703 let other_loc = self.sess.source_map().lookup_char_pos(second.lo());
705 if self_loc.file.name != other_loc.file.name {
709 Some(first.to(second))
711 fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
712 span.with_ctxt(at.ctxt())
714 fn source_text(&mut self, span: Self::Span) -> Option<String> {
715 self.sess.source_map().span_to_snippet(span).ok()