1 use crate::base::ExtCtxt;
3 use rustc_parse::{parse_stream_from_source_str, nt_to_tokenstream};
5 use syntax::util::comments;
6 use syntax::print::pprust;
7 use syntax::sess::ParseSess;
9 use syntax::tokenstream::{self, DelimSpan, IsJoint::*, TokenStream, TreeAndJoint};
10 use syntax_pos::{BytePos, FileName, MultiSpan, Pos, SourceFile, Span};
11 use syntax_pos::symbol::{kw, sym, Symbol};
13 use errors::Diagnostic;
14 use rustc_data_structures::sync::Lrc;
16 use pm::{Delimiter, Level, LineColumn, Spacing};
17 use pm::bridge::{server, TokenTree};
18 use std::{ascii, panic};
21 trait FromInternal<T> {
22 fn from_internal(x: T) -> Self;
26 fn to_internal(self) -> T;
29 impl FromInternal<token::DelimToken> for Delimiter {
30 fn from_internal(delim: token::DelimToken) -> Delimiter {
32 token::Paren => Delimiter::Parenthesis,
33 token::Brace => Delimiter::Brace,
34 token::Bracket => Delimiter::Bracket,
35 token::NoDelim => Delimiter::None,
40 impl ToInternal<token::DelimToken> for Delimiter {
41 fn to_internal(self) -> token::DelimToken {
43 Delimiter::Parenthesis => token::Paren,
44 Delimiter::Brace => token::Brace,
45 Delimiter::Bracket => token::Bracket,
46 Delimiter::None => token::NoDelim,
51 impl FromInternal<(TreeAndJoint, &'_ ParseSess, &'_ mut Vec<Self>)>
52 for TokenTree<Group, Punct, Ident, Literal>
54 fn from_internal(((tree, is_joint), sess, stack): (TreeAndJoint, &ParseSess, &mut Vec<Self>))
58 let joint = is_joint == Joint;
59 let Token { kind, span } = match tree {
60 tokenstream::TokenTree::Delimited(span, delim, tts) => {
61 let delimiter = Delimiter::from_internal(delim);
62 return TokenTree::Group(Group {
68 tokenstream::TokenTree::Token(token) => token,
72 ($ty:ident { $($field:ident $(: $value:expr)*),+ $(,)? }) => (
73 TokenTree::$ty(self::$ty {
74 $($field $(: $value)*,)+
78 ($ty:ident::$method:ident($($value:expr),*)) => (
79 TokenTree::$ty(self::$ty::$method($($value,)* span))
84 tt!(Punct::new($a, joint))
86 ($a:expr, $b:expr) => {{
87 stack.push(tt!(Punct::new($b, joint)));
88 tt!(Punct::new($a, true))
90 ($a:expr, $b:expr, $c:expr) => {{
91 stack.push(tt!(Punct::new($c, joint)));
92 stack.push(tt!(Punct::new($b, true)));
93 tt!(Punct::new($a, true))
101 EqEq => op!('=', '='),
105 AndAnd => op!('&', '&'),
106 OrOr => op!('|', '|'),
109 BinOp(Plus) => op!('+'),
110 BinOp(Minus) => op!('-'),
111 BinOp(Star) => op!('*'),
112 BinOp(Slash) => op!('/'),
113 BinOp(Percent) => op!('%'),
114 BinOp(Caret) => op!('^'),
115 BinOp(And) => op!('&'),
116 BinOp(Or) => op!('|'),
117 BinOp(Shl) => op!('<', '<'),
118 BinOp(Shr) => op!('>', '>'),
119 BinOpEq(Plus) => op!('+', '='),
120 BinOpEq(Minus) => op!('-', '='),
121 BinOpEq(Star) => op!('*', '='),
122 BinOpEq(Slash) => op!('/', '='),
123 BinOpEq(Percent) => op!('%', '='),
124 BinOpEq(Caret) => op!('^', '='),
125 BinOpEq(And) => op!('&', '='),
126 BinOpEq(Or) => op!('|', '='),
127 BinOpEq(Shl) => op!('<', '<', '='),
128 BinOpEq(Shr) => op!('>', '>', '='),
131 DotDot => op!('.', '.'),
132 DotDotDot => op!('.', '.', '.'),
133 DotDotEq => op!('.', '.', '='),
137 ModSep => op!(':', ':'),
138 RArrow => op!('-', '>'),
139 LArrow => op!('<', '-'),
140 FatArrow => op!('=', '>'),
143 Question => op!('?'),
144 SingleQuote => op!('\''),
146 Ident(name, false) if name == kw::DollarCrate => tt!(Ident::dollar_crate()),
147 Ident(name, is_raw) => tt!(Ident::new(name, is_raw)),
149 let ident = ast::Ident::new(name, span).without_first_quote();
150 stack.push(tt!(Ident::new(ident.name, false)));
151 tt!(Punct::new('\'', true))
153 Literal(lit) => tt!(Literal { lit }),
155 let style = comments::doc_comment_style(&c.as_str());
156 let stripped = comments::strip_doc_comment_decoration(&c.as_str());
157 let mut escaped = String::new();
158 for ch in stripped.chars() {
159 escaped.extend(ch.escape_debug());
162 Ident(sym::doc, false),
164 TokenKind::lit(token::Str, Symbol::intern(&escaped), None),
167 .map(|kind| tokenstream::TokenTree::token(kind, span))
169 stack.push(TokenTree::Group(Group {
170 delimiter: Delimiter::Bracket,
172 span: DelimSpan::from_single(span),
174 if style == ast::AttrStyle::Inner {
175 stack.push(tt!(Punct::new('!', false)));
177 tt!(Punct::new('#', false))
180 Interpolated(nt) => {
181 let stream = nt_to_tokenstream(&nt, sess, span);
182 TokenTree::Group(Group {
183 delimiter: Delimiter::None,
185 span: DelimSpan::from_single(span),
189 OpenDelim(..) | CloseDelim(..) => unreachable!(),
190 Whitespace | Comment | Shebang(..) | Unknown(..) | Eof => unreachable!(),
195 impl ToInternal<TokenStream> for TokenTree<Group, Punct, Ident, Literal> {
196 fn to_internal(self) -> TokenStream {
197 use syntax::token::*;
199 let (ch, joint, span) = match self {
200 TokenTree::Punct(Punct { ch, joint, span }) => (ch, joint, span),
201 TokenTree::Group(Group {
206 return tokenstream::TokenTree::Delimited(
208 delimiter.to_internal(),
213 TokenTree::Ident(self::Ident { sym, is_raw, span }) => {
214 return tokenstream::TokenTree::token(Ident(sym, is_raw), span).into();
216 TokenTree::Literal(self::Literal {
217 lit: token::Lit { kind: token::Integer, symbol, suffix },
219 }) if symbol.as_str().starts_with("-") => {
220 let minus = BinOp(BinOpToken::Minus);
221 let symbol = Symbol::intern(&symbol.as_str()[1..]);
222 let integer = TokenKind::lit(token::Integer, symbol, suffix);
223 let a = tokenstream::TokenTree::token(minus, span);
224 let b = tokenstream::TokenTree::token(integer, span);
225 return vec![a, b].into_iter().collect();
227 TokenTree::Literal(self::Literal {
228 lit: token::Lit { kind: token::Float, symbol, suffix },
230 }) if symbol.as_str().starts_with("-") => {
231 let minus = BinOp(BinOpToken::Minus);
232 let symbol = Symbol::intern(&symbol.as_str()[1..]);
233 let float = TokenKind::lit(token::Float, symbol, suffix);
234 let a = tokenstream::TokenTree::token(minus, span);
235 let b = tokenstream::TokenTree::token(float, span);
236 return vec![a, b].into_iter().collect();
238 TokenTree::Literal(self::Literal { lit, span }) => {
239 return tokenstream::TokenTree::token(Literal(lit), span).into()
243 let kind = match ch {
253 '%' => BinOp(Percent),
269 let tree = tokenstream::TokenTree::token(kind, span);
270 TokenStream::new(vec![(tree, if joint { Joint } else { NonJoint })])
274 impl ToInternal<errors::Level> for Level {
275 fn to_internal(self) -> errors::Level {
277 Level::Error => errors::Level::Error,
278 Level::Warning => errors::Level::Warning,
279 Level::Note => errors::Level::Note,
280 Level::Help => errors::Level::Help,
281 _ => unreachable!("unknown proc_macro::Level variant: {:?}", self),
287 pub struct TokenStreamIter {
288 cursor: tokenstream::Cursor,
289 stack: Vec<TokenTree<Group, Punct, Ident, Literal>>,
294 delimiter: Delimiter,
299 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
302 // NB. not using `Spacing` here because it doesn't implement `Hash`.
308 fn new(ch: char, joint: bool, span: Span) -> Punct {
309 const LEGAL_CHARS: &[char] = &['=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^',
310 '&', '|', '@', '.', ',', ';', ':', '#', '$', '?', '\''];
311 if !LEGAL_CHARS.contains(&ch) {
312 panic!("unsupported character `{:?}`", ch)
314 Punct { ch, joint, span }
318 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
326 fn is_valid(string: &str) -> bool {
327 let mut chars = string.chars();
328 if let Some(start) = chars.next() {
329 rustc_lexer::is_id_start(start) && chars.all(rustc_lexer::is_id_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 if is_raw && !sym.can_be_raw() {
340 panic!("`{}` cannot be a raw identifier", string);
342 Ident { sym, is_raw, span }
344 fn dollar_crate(span: Span) -> Ident {
345 // `$crate` is accepted as an ident only if it comes from the compiler.
346 Ident { sym: kw::DollarCrate, is_raw: false, span }
350 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
351 #[derive(Clone, Debug)]
357 pub(crate) struct Rustc<'a> {
365 pub fn new(cx: &'a ExtCtxt<'_>) -> Self {
366 let expn_data = cx.current_expansion.id.expn_data();
369 def_site: cx.with_def_site_ctxt(expn_data.def_site),
370 call_site: cx.with_call_site_ctxt(expn_data.call_site),
371 mixed_site: cx.with_mixed_site_ctxt(expn_data.call_site),
375 fn lit(&mut self, kind: token::LitKind, symbol: Symbol, suffix: Option<Symbol>) -> Literal {
377 lit: token::Lit::new(kind, symbol, suffix),
378 span: server::Span::call_site(self),
383 impl server::Types for Rustc<'_> {
384 type TokenStream = TokenStream;
385 type TokenStreamBuilder = tokenstream::TokenStreamBuilder;
386 type TokenStreamIter = TokenStreamIter;
390 type Literal = Literal;
391 type SourceFile = Lrc<SourceFile>;
392 type MultiSpan = Vec<Span>;
393 type Diagnostic = Diagnostic;
397 impl server::TokenStream for Rustc<'_> {
398 fn new(&mut self) -> Self::TokenStream {
399 TokenStream::default()
401 fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
404 fn from_str(&mut self, src: &str) -> Self::TokenStream {
405 parse_stream_from_source_str(
406 FileName::proc_macro_source_code(src),
409 Some(self.call_site),
412 fn to_string(&mut self, stream: &Self::TokenStream) -> String {
413 pprust::tts_to_string(stream.clone())
417 tree: TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>,
418 ) -> Self::TokenStream {
421 fn into_iter(&mut self, stream: Self::TokenStream) -> Self::TokenStreamIter {
423 cursor: stream.trees(),
429 impl server::TokenStreamBuilder for Rustc<'_> {
430 fn new(&mut self) -> Self::TokenStreamBuilder {
431 tokenstream::TokenStreamBuilder::new()
433 fn push(&mut self, builder: &mut Self::TokenStreamBuilder, stream: Self::TokenStream) {
434 builder.push(stream);
436 fn build(&mut self, builder: Self::TokenStreamBuilder) -> Self::TokenStream {
441 impl server::TokenStreamIter for Rustc<'_> {
444 iter: &mut Self::TokenStreamIter,
445 ) -> Option<TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>> {
447 let tree = iter.stack.pop().or_else(|| {
448 let next = iter.cursor.next_with_joint()?;
449 Some(TokenTree::from_internal((next, self.sess, &mut iter.stack)))
451 // HACK: The condition "dummy span + group with empty delimiter" represents an AST
452 // fragment approximately converted into a token stream. This may happen, for
453 // example, with inputs to proc macro attributes, including derives. Such "groups"
454 // need to flattened during iteration over stream's token trees.
455 // Eventually this needs to be removed in favor of keeping original token trees
456 // and not doing the roundtrip through AST.
457 if let TokenTree::Group(ref group) = tree {
458 if group.delimiter == Delimiter::None && group.span.entire().is_dummy() {
459 iter.cursor.append(group.stream.clone());
468 impl server::Group for Rustc<'_> {
469 fn new(&mut self, delimiter: Delimiter, stream: Self::TokenStream) -> Self::Group {
473 span: DelimSpan::from_single(server::Span::call_site(self)),
476 fn delimiter(&mut self, group: &Self::Group) -> Delimiter {
479 fn stream(&mut self, group: &Self::Group) -> Self::TokenStream {
482 fn span(&mut self, group: &Self::Group) -> Self::Span {
485 fn span_open(&mut self, group: &Self::Group) -> Self::Span {
488 fn span_close(&mut self, group: &Self::Group) -> Self::Span {
491 fn set_span(&mut self, group: &mut Self::Group, span: Self::Span) {
492 group.span = DelimSpan::from_single(span);
496 impl server::Punct for Rustc<'_> {
497 fn new(&mut self, ch: char, spacing: Spacing) -> Self::Punct {
498 Punct::new(ch, spacing == Spacing::Joint, server::Span::call_site(self))
500 fn as_char(&mut self, punct: Self::Punct) -> char {
503 fn spacing(&mut self, punct: Self::Punct) -> Spacing {
510 fn span(&mut self, punct: Self::Punct) -> Self::Span {
513 fn with_span(&mut self, punct: Self::Punct, span: Self::Span) -> Self::Punct {
514 Punct { span, ..punct }
518 impl server::Ident for Rustc<'_> {
519 fn new(&mut self, string: &str, span: Self::Span, is_raw: bool) -> Self::Ident {
520 Ident::new(Symbol::intern(string), is_raw, span)
522 fn span(&mut self, ident: Self::Ident) -> Self::Span {
525 fn with_span(&mut self, ident: Self::Ident, span: Self::Span) -> Self::Ident {
526 Ident { span, ..ident }
530 impl server::Literal for Rustc<'_> {
531 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
532 fn debug(&mut self, literal: &Self::Literal) -> String {
533 format!("{:?}", literal)
535 fn integer(&mut self, n: &str) -> Self::Literal {
536 self.lit(token::Integer, Symbol::intern(n), None)
538 fn typed_integer(&mut self, n: &str, kind: &str) -> Self::Literal {
539 self.lit(token::Integer, Symbol::intern(n), Some(Symbol::intern(kind)))
541 fn float(&mut self, n: &str) -> Self::Literal {
542 self.lit(token::Float, Symbol::intern(n), None)
544 fn f32(&mut self, n: &str) -> Self::Literal {
545 self.lit(token::Float, Symbol::intern(n), Some(sym::f32))
547 fn f64(&mut self, n: &str) -> Self::Literal {
548 self.lit(token::Float, Symbol::intern(n), Some(sym::f64))
550 fn string(&mut self, string: &str) -> Self::Literal {
551 let mut escaped = String::new();
552 for ch in string.chars() {
553 escaped.extend(ch.escape_debug());
555 self.lit(token::Str, Symbol::intern(&escaped), None)
557 fn character(&mut self, ch: char) -> Self::Literal {
558 let mut escaped = String::new();
559 escaped.extend(ch.escape_unicode());
560 self.lit(token::Char, Symbol::intern(&escaped), None)
562 fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
566 .flat_map(ascii::escape_default)
567 .map(Into::<char>::into)
568 .collect::<String>();
569 self.lit(token::ByteStr, Symbol::intern(&string), None)
571 fn span(&mut self, literal: &Self::Literal) -> Self::Span {
574 fn set_span(&mut self, literal: &mut Self::Literal, span: Self::Span) {
579 literal: &Self::Literal,
582 ) -> Option<Self::Span> {
583 let span = literal.span;
584 let length = span.hi().to_usize() - span.lo().to_usize();
586 let start = match start {
587 Bound::Included(lo) => lo,
588 Bound::Excluded(lo) => lo + 1,
589 Bound::Unbounded => 0,
592 let end = match end {
593 Bound::Included(hi) => hi + 1,
594 Bound::Excluded(hi) => hi,
595 Bound::Unbounded => length,
598 // Bounds check the values, preventing addition overflow and OOB spans.
599 if start > u32::max_value() as usize
600 || end > u32::max_value() as usize
601 || (u32::max_value() - start as u32) < span.lo().to_u32()
602 || (u32::max_value() - end as u32) < span.lo().to_u32()
609 let new_lo = span.lo() + BytePos::from_usize(start);
610 let new_hi = span.lo() + BytePos::from_usize(end);
611 Some(span.with_lo(new_lo).with_hi(new_hi))
615 impl server::SourceFile for Rustc<'_> {
616 fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
617 Lrc::ptr_eq(file1, file2)
619 fn path(&mut self, file: &Self::SourceFile) -> String {
621 FileName::Real(ref path) => path
623 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
625 _ => file.name.to_string(),
628 fn is_real(&mut self, file: &Self::SourceFile) -> bool {
633 impl server::MultiSpan for Rustc<'_> {
634 fn new(&mut self) -> Self::MultiSpan {
637 fn push(&mut self, spans: &mut Self::MultiSpan, span: Self::Span) {
642 impl server::Diagnostic for Rustc<'_> {
643 fn new(&mut self, level: Level, msg: &str, spans: Self::MultiSpan) -> Self::Diagnostic {
644 let mut diag = Diagnostic::new(level.to_internal(), msg);
645 diag.set_span(MultiSpan::from_spans(spans));
650 diag: &mut Self::Diagnostic,
653 spans: Self::MultiSpan,
655 diag.sub(level.to_internal(), msg, MultiSpan::from_spans(spans), None);
657 fn emit(&mut self, diag: Self::Diagnostic) {
658 self.sess.span_diagnostic.emit_diagnostic(&diag);
662 impl server::Span for Rustc<'_> {
663 fn debug(&mut self, span: Self::Span) -> String {
664 format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
666 fn def_site(&mut self) -> Self::Span {
669 fn call_site(&mut self) -> Self::Span {
672 fn mixed_site(&mut self) -> Self::Span {
675 fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
676 self.sess.source_map().lookup_char_pos(span.lo()).file
678 fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
681 fn source(&mut self, span: Self::Span) -> Self::Span {
682 span.source_callsite()
684 fn start(&mut self, span: Self::Span) -> LineColumn {
685 let loc = self.sess.source_map().lookup_char_pos(span.lo());
688 column: loc.col.to_usize(),
691 fn end(&mut self, span: Self::Span) -> LineColumn {
692 let loc = self.sess.source_map().lookup_char_pos(span.hi());
695 column: loc.col.to_usize(),
698 fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
699 let self_loc = self.sess.source_map().lookup_char_pos(first.lo());
700 let other_loc = self.sess.source_map().lookup_char_pos(second.lo());
702 if self_loc.file.name != other_loc.file.name {
706 Some(first.to(second))
708 fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
709 span.with_ctxt(at.ctxt())
711 fn source_text(&mut self, span: Self::Span) -> Option<String> {
712 self.sess.source_map().span_to_snippet(span).ok()