1 use crate::base::ExtCtxt;
3 use rustc_parse::{nt_to_tokenstream, parse_stream_from_source_str};
5 use syntax::print::pprust;
6 use syntax::sess::ParseSess;
8 use syntax::tokenstream::{self, DelimSpan, IsJoint::*, TokenStream, TreeAndJoint};
9 use syntax::util::comments;
10 use syntax_pos::symbol::{kw, sym, Symbol};
11 use syntax_pos::{BytePos, FileName, MultiSpan, Pos, SourceFile, Span};
13 use errors::Diagnostic;
14 use rustc_data_structures::sync::Lrc;
16 use pm::bridge::{server, TokenTree};
17 use pm::{Delimiter, Level, LineColumn, Spacing};
19 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>
55 ((tree, is_joint), sess, stack): (TreeAndJoint, &ParseSess, &mut Vec<Self>),
59 let joint = is_joint == Joint;
60 let Token { kind, span } = match tree {
61 tokenstream::TokenTree::Delimited(span, delim, tts) => {
62 let delimiter = Delimiter::from_internal(delim);
63 return TokenTree::Group(Group { delimiter, stream: tts.into(), span });
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(&nt, sess, span);
179 TokenTree::Group(Group {
180 delimiter: Delimiter::None,
182 span: DelimSpan::from_single(span),
186 OpenDelim(..) | CloseDelim(..) => unreachable!(),
187 Whitespace | Comment | Shebang(..) | Unknown(..) | Eof => unreachable!(),
192 impl ToInternal<TokenStream> for TokenTree<Group, Punct, Ident, Literal> {
193 fn to_internal(self) -> TokenStream {
194 use syntax::token::*;
196 let (ch, joint, span) = match self {
197 TokenTree::Punct(Punct { ch, joint, span }) => (ch, joint, span),
198 TokenTree::Group(Group { delimiter, stream, span }) => {
199 return tokenstream::TokenTree::Delimited(
201 delimiter.to_internal(),
206 TokenTree::Ident(self::Ident { sym, is_raw, span }) => {
207 return tokenstream::TokenTree::token(Ident(sym, is_raw), span).into();
209 TokenTree::Literal(self::Literal {
210 lit: token::Lit { kind: token::Integer, symbol, suffix },
212 }) if symbol.as_str().starts_with("-") => {
213 let minus = BinOp(BinOpToken::Minus);
214 let symbol = Symbol::intern(&symbol.as_str()[1..]);
215 let integer = TokenKind::lit(token::Integer, symbol, suffix);
216 let a = tokenstream::TokenTree::token(minus, span);
217 let b = tokenstream::TokenTree::token(integer, span);
218 return vec![a, b].into_iter().collect();
220 TokenTree::Literal(self::Literal {
221 lit: token::Lit { kind: token::Float, symbol, suffix },
223 }) if symbol.as_str().starts_with("-") => {
224 let minus = BinOp(BinOpToken::Minus);
225 let symbol = Symbol::intern(&symbol.as_str()[1..]);
226 let float = TokenKind::lit(token::Float, symbol, suffix);
227 let a = tokenstream::TokenTree::token(minus, span);
228 let b = tokenstream::TokenTree::token(float, span);
229 return vec![a, b].into_iter().collect();
231 TokenTree::Literal(self::Literal { lit, span }) => {
232 return tokenstream::TokenTree::token(Literal(lit), span).into();
236 let kind = match ch {
246 '%' => BinOp(Percent),
262 let tree = tokenstream::TokenTree::token(kind, span);
263 TokenStream::new(vec![(tree, if joint { Joint } else { NonJoint })])
267 impl ToInternal<errors::Level> for Level {
268 fn to_internal(self) -> errors::Level {
270 Level::Error => errors::Level::Error,
271 Level::Warning => errors::Level::Warning,
272 Level::Note => errors::Level::Note,
273 Level::Help => errors::Level::Help,
274 _ => unreachable!("unknown proc_macro::Level variant: {:?}", self),
280 pub struct TokenStreamIter {
281 cursor: tokenstream::Cursor,
282 stack: Vec<TokenTree<Group, Punct, Ident, Literal>>,
287 delimiter: Delimiter,
292 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
295 // NB. not using `Spacing` here because it doesn't implement `Hash`.
301 fn new(ch: char, joint: bool, span: Span) -> Punct {
302 const LEGAL_CHARS: &[char] = &[
303 '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
304 ':', '#', '$', '?', '\'',
306 if !LEGAL_CHARS.contains(&ch) {
307 panic!("unsupported character `{:?}`", ch)
309 Punct { ch, joint, span }
313 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
321 fn is_valid(string: &str) -> bool {
322 let mut chars = string.chars();
323 if let Some(start) = chars.next() {
324 rustc_lexer::is_id_start(start) && chars.all(rustc_lexer::is_id_continue)
329 fn new(sym: Symbol, is_raw: bool, span: Span) -> Ident {
330 let string = sym.as_str();
331 if !Self::is_valid(&string) {
332 panic!("`{:?}` is not a valid identifier", string)
334 if is_raw && !sym.can_be_raw() {
335 panic!("`{}` cannot be a raw identifier", string);
337 Ident { sym, is_raw, span }
339 fn dollar_crate(span: Span) -> Ident {
340 // `$crate` is accepted as an ident only if it comes from the compiler.
341 Ident { sym: kw::DollarCrate, is_raw: false, span }
345 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
346 #[derive(Clone, Debug)]
352 pub(crate) struct Rustc<'a> {
360 pub fn new(cx: &'a ExtCtxt<'_>) -> Self {
361 let expn_data = cx.current_expansion.id.expn_data();
364 def_site: cx.with_def_site_ctxt(expn_data.def_site),
365 call_site: cx.with_call_site_ctxt(expn_data.call_site),
366 mixed_site: cx.with_mixed_site_ctxt(expn_data.call_site),
370 fn lit(&mut self, kind: token::LitKind, symbol: Symbol, suffix: Option<Symbol>) -> Literal {
371 Literal { lit: token::Lit::new(kind, symbol, suffix), span: server::Span::call_site(self) }
375 impl server::Types for Rustc<'_> {
376 type TokenStream = TokenStream;
377 type TokenStreamBuilder = tokenstream::TokenStreamBuilder;
378 type TokenStreamIter = TokenStreamIter;
382 type Literal = Literal;
383 type SourceFile = Lrc<SourceFile>;
384 type MultiSpan = Vec<Span>;
385 type Diagnostic = Diagnostic;
389 impl server::TokenStream for Rustc<'_> {
390 fn new(&mut self) -> Self::TokenStream {
391 TokenStream::default()
393 fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
396 fn from_str(&mut self, src: &str) -> Self::TokenStream {
397 parse_stream_from_source_str(
398 FileName::proc_macro_source_code(src),
401 Some(self.call_site),
404 fn to_string(&mut self, stream: &Self::TokenStream) -> String {
405 pprust::tts_to_string(stream.clone())
409 tree: TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>,
410 ) -> Self::TokenStream {
413 fn into_iter(&mut self, stream: Self::TokenStream) -> Self::TokenStreamIter {
414 TokenStreamIter { cursor: stream.trees(), stack: vec![] }
418 impl server::TokenStreamBuilder for Rustc<'_> {
419 fn new(&mut self) -> Self::TokenStreamBuilder {
420 tokenstream::TokenStreamBuilder::new()
422 fn push(&mut self, builder: &mut Self::TokenStreamBuilder, stream: Self::TokenStream) {
423 builder.push(stream);
425 fn build(&mut self, builder: Self::TokenStreamBuilder) -> Self::TokenStream {
430 impl server::TokenStreamIter for Rustc<'_> {
433 iter: &mut Self::TokenStreamIter,
434 ) -> Option<TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>> {
436 let tree = iter.stack.pop().or_else(|| {
437 let next = iter.cursor.next_with_joint()?;
438 Some(TokenTree::from_internal((next, self.sess, &mut iter.stack)))
440 // HACK: The condition "dummy span + group with empty delimiter" represents an AST
441 // fragment approximately converted into a token stream. This may happen, for
442 // example, with inputs to proc macro attributes, including derives. Such "groups"
443 // need to flattened during iteration over stream's token trees.
444 // Eventually this needs to be removed in favor of keeping original token trees
445 // and not doing the roundtrip through AST.
446 if let TokenTree::Group(ref group) = tree {
447 if group.delimiter == Delimiter::None && group.span.entire().is_dummy() {
448 iter.cursor.append(group.stream.clone());
457 impl server::Group for Rustc<'_> {
458 fn new(&mut self, delimiter: Delimiter, stream: Self::TokenStream) -> Self::Group {
459 Group { delimiter, stream, span: DelimSpan::from_single(server::Span::call_site(self)) }
461 fn delimiter(&mut self, group: &Self::Group) -> Delimiter {
464 fn stream(&mut self, group: &Self::Group) -> Self::TokenStream {
467 fn span(&mut self, group: &Self::Group) -> Self::Span {
470 fn span_open(&mut self, group: &Self::Group) -> Self::Span {
473 fn span_close(&mut self, group: &Self::Group) -> Self::Span {
476 fn set_span(&mut self, group: &mut Self::Group, span: Self::Span) {
477 group.span = DelimSpan::from_single(span);
481 impl server::Punct for Rustc<'_> {
482 fn new(&mut self, ch: char, spacing: Spacing) -> Self::Punct {
483 Punct::new(ch, spacing == Spacing::Joint, server::Span::call_site(self))
485 fn as_char(&mut self, punct: Self::Punct) -> char {
488 fn spacing(&mut self, punct: Self::Punct) -> Spacing {
489 if punct.joint { Spacing::Joint } else { Spacing::Alone }
491 fn span(&mut self, punct: Self::Punct) -> Self::Span {
494 fn with_span(&mut self, punct: Self::Punct, span: Self::Span) -> Self::Punct {
495 Punct { span, ..punct }
499 impl server::Ident for Rustc<'_> {
500 fn new(&mut self, string: &str, span: Self::Span, is_raw: bool) -> Self::Ident {
501 Ident::new(Symbol::intern(string), is_raw, span)
503 fn span(&mut self, ident: Self::Ident) -> Self::Span {
506 fn with_span(&mut self, ident: Self::Ident, span: Self::Span) -> Self::Ident {
507 Ident { span, ..ident }
511 impl server::Literal for Rustc<'_> {
512 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
513 fn debug(&mut self, literal: &Self::Literal) -> String {
514 format!("{:?}", literal)
516 fn integer(&mut self, n: &str) -> Self::Literal {
517 self.lit(token::Integer, Symbol::intern(n), None)
519 fn typed_integer(&mut self, n: &str, kind: &str) -> Self::Literal {
520 self.lit(token::Integer, Symbol::intern(n), Some(Symbol::intern(kind)))
522 fn float(&mut self, n: &str) -> Self::Literal {
523 self.lit(token::Float, Symbol::intern(n), None)
525 fn f32(&mut self, n: &str) -> Self::Literal {
526 self.lit(token::Float, Symbol::intern(n), Some(sym::f32))
528 fn f64(&mut self, n: &str) -> Self::Literal {
529 self.lit(token::Float, Symbol::intern(n), Some(sym::f64))
531 fn string(&mut self, string: &str) -> Self::Literal {
532 let mut escaped = String::new();
533 for ch in string.chars() {
534 escaped.extend(ch.escape_debug());
536 self.lit(token::Str, Symbol::intern(&escaped), None)
538 fn character(&mut self, ch: char) -> Self::Literal {
539 let mut escaped = String::new();
540 escaped.extend(ch.escape_unicode());
541 self.lit(token::Char, Symbol::intern(&escaped), None)
543 fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
547 .flat_map(ascii::escape_default)
548 .map(Into::<char>::into)
549 .collect::<String>();
550 self.lit(token::ByteStr, Symbol::intern(&string), None)
552 fn span(&mut self, literal: &Self::Literal) -> Self::Span {
555 fn set_span(&mut self, literal: &mut Self::Literal, span: Self::Span) {
560 literal: &Self::Literal,
563 ) -> Option<Self::Span> {
564 let span = literal.span;
565 let length = span.hi().to_usize() - span.lo().to_usize();
567 let start = match start {
568 Bound::Included(lo) => lo,
569 Bound::Excluded(lo) => lo + 1,
570 Bound::Unbounded => 0,
573 let end = match end {
574 Bound::Included(hi) => hi + 1,
575 Bound::Excluded(hi) => hi,
576 Bound::Unbounded => length,
579 // Bounds check the values, preventing addition overflow and OOB spans.
580 if start > u32::max_value() as usize
581 || end > u32::max_value() as usize
582 || (u32::max_value() - start as u32) < span.lo().to_u32()
583 || (u32::max_value() - end as u32) < span.lo().to_u32()
590 let new_lo = span.lo() + BytePos::from_usize(start);
591 let new_hi = span.lo() + BytePos::from_usize(end);
592 Some(span.with_lo(new_lo).with_hi(new_hi))
596 impl server::SourceFile for Rustc<'_> {
597 fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
598 Lrc::ptr_eq(file1, file2)
600 fn path(&mut self, file: &Self::SourceFile) -> String {
602 FileName::Real(ref path) => path
604 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
606 _ => file.name.to_string(),
609 fn is_real(&mut self, file: &Self::SourceFile) -> bool {
614 impl server::MultiSpan for Rustc<'_> {
615 fn new(&mut self) -> Self::MultiSpan {
618 fn push(&mut self, spans: &mut Self::MultiSpan, span: Self::Span) {
623 impl server::Diagnostic for Rustc<'_> {
624 fn new(&mut self, level: Level, msg: &str, spans: Self::MultiSpan) -> Self::Diagnostic {
625 let mut diag = Diagnostic::new(level.to_internal(), msg);
626 diag.set_span(MultiSpan::from_spans(spans));
631 diag: &mut Self::Diagnostic,
634 spans: Self::MultiSpan,
636 diag.sub(level.to_internal(), msg, MultiSpan::from_spans(spans), None);
638 fn emit(&mut self, diag: Self::Diagnostic) {
639 self.sess.span_diagnostic.emit_diagnostic(&diag);
643 impl server::Span for Rustc<'_> {
644 fn debug(&mut self, span: Self::Span) -> String {
645 format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
647 fn def_site(&mut self) -> Self::Span {
650 fn call_site(&mut self) -> Self::Span {
653 fn mixed_site(&mut self) -> Self::Span {
656 fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
657 self.sess.source_map().lookup_char_pos(span.lo()).file
659 fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
662 fn source(&mut self, span: Self::Span) -> Self::Span {
663 span.source_callsite()
665 fn start(&mut self, span: Self::Span) -> LineColumn {
666 let loc = self.sess.source_map().lookup_char_pos(span.lo());
667 LineColumn { line: loc.line, column: loc.col.to_usize() }
669 fn end(&mut self, span: Self::Span) -> LineColumn {
670 let loc = self.sess.source_map().lookup_char_pos(span.hi());
671 LineColumn { line: loc.line, column: loc.col.to_usize() }
673 fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
674 let self_loc = self.sess.source_map().lookup_char_pos(first.lo());
675 let other_loc = self.sess.source_map().lookup_char_pos(second.lo());
677 if self_loc.file.name != other_loc.file.name {
681 Some(first.to(second))
683 fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
684 span.with_ctxt(at.ctxt())
686 fn source_text(&mut self, span: Self::Span) -> Option<String> {
687 self.sess.source_map().span_to_snippet(span).ok()