]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_expand/src/proc_macro_server.rs
Merge commit 'cb7915b00c235e9b5861564f3be78dba330980ee' into clippyup
[rust.git] / compiler / rustc_expand / src / proc_macro_server.rs
1 use crate::base::{ExtCtxt, ResolverExpand};
2
3 use rustc_ast as ast;
4 use rustc_ast::token::{self, Nonterminal, NtIdent};
5 use rustc_ast::tokenstream::{self, CanSynthesizeMissingTokens};
6 use rustc_ast::tokenstream::{DelimSpan, Spacing::*, TokenStream, TreeAndSpacing};
7 use rustc_ast_pretty::pprust;
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc_data_structures::sync::Lrc;
10 use rustc_errors::Diagnostic;
11 use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT;
12 use rustc_lint_defs::BuiltinLintDiagnostics;
13 use rustc_parse::lexer::nfc_normalize;
14 use rustc_parse::{nt_to_tokenstream, parse_stream_from_source_str};
15 use rustc_session::parse::ParseSess;
16 use rustc_span::def_id::CrateNum;
17 use rustc_span::hygiene::ExpnKind;
18 use rustc_span::symbol::{self, kw, sym, Symbol};
19 use rustc_span::{BytePos, FileName, MultiSpan, Pos, RealFileName, SourceFile, Span};
20
21 use pm::bridge::{server, TokenTree};
22 use pm::{Delimiter, Level, LineColumn, Spacing};
23 use std::ops::Bound;
24 use std::{ascii, panic};
25
26 trait FromInternal<T> {
27     fn from_internal(x: T) -> Self;
28 }
29
30 trait ToInternal<T> {
31     fn to_internal(self) -> T;
32 }
33
34 impl FromInternal<token::DelimToken> for Delimiter {
35     fn from_internal(delim: token::DelimToken) -> Delimiter {
36         match delim {
37             token::Paren => Delimiter::Parenthesis,
38             token::Brace => Delimiter::Brace,
39             token::Bracket => Delimiter::Bracket,
40             token::NoDelim => Delimiter::None,
41         }
42     }
43 }
44
45 impl ToInternal<token::DelimToken> for Delimiter {
46     fn to_internal(self) -> token::DelimToken {
47         match self {
48             Delimiter::Parenthesis => token::Paren,
49             Delimiter::Brace => token::Brace,
50             Delimiter::Bracket => token::Bracket,
51             Delimiter::None => token::NoDelim,
52         }
53     }
54 }
55
56 impl FromInternal<(TreeAndSpacing, &'_ mut Vec<Self>, &mut Rustc<'_>)>
57     for TokenTree<Group, Punct, Ident, Literal>
58 {
59     fn from_internal(
60         ((tree, spacing), stack, rustc): (TreeAndSpacing, &mut Vec<Self>, &mut Rustc<'_>),
61     ) -> Self {
62         use rustc_ast::token::*;
63
64         let joint = spacing == Joint;
65         let Token { kind, span } = match tree {
66             tokenstream::TokenTree::Delimited(span, delim, tts) => {
67                 let delimiter = Delimiter::from_internal(delim);
68                 return TokenTree::Group(Group { delimiter, stream: tts, span, flatten: false });
69             }
70             tokenstream::TokenTree::Token(token) => token,
71         };
72
73         macro_rules! tt {
74             ($ty:ident { $($field:ident $(: $value:expr)*),+ $(,)? }) => (
75                 TokenTree::$ty(self::$ty {
76                     $($field $(: $value)*,)+
77                     span,
78                 })
79             );
80             ($ty:ident::$method:ident($($value:expr),*)) => (
81                 TokenTree::$ty(self::$ty::$method($($value,)* span))
82             );
83         }
84         macro_rules! op {
85             ($a:expr) => {
86                 tt!(Punct::new($a, joint))
87             };
88             ($a:expr, $b:expr) => {{
89                 stack.push(tt!(Punct::new($b, joint)));
90                 tt!(Punct::new($a, true))
91             }};
92             ($a:expr, $b:expr, $c:expr) => {{
93                 stack.push(tt!(Punct::new($c, joint)));
94                 stack.push(tt!(Punct::new($b, true)));
95                 tt!(Punct::new($a, true))
96             }};
97         }
98
99         match kind {
100             Eq => op!('='),
101             Lt => op!('<'),
102             Le => op!('<', '='),
103             EqEq => op!('=', '='),
104             Ne => op!('!', '='),
105             Ge => op!('>', '='),
106             Gt => op!('>'),
107             AndAnd => op!('&', '&'),
108             OrOr => op!('|', '|'),
109             Not => op!('!'),
110             Tilde => op!('~'),
111             BinOp(Plus) => op!('+'),
112             BinOp(Minus) => op!('-'),
113             BinOp(Star) => op!('*'),
114             BinOp(Slash) => op!('/'),
115             BinOp(Percent) => op!('%'),
116             BinOp(Caret) => op!('^'),
117             BinOp(And) => op!('&'),
118             BinOp(Or) => op!('|'),
119             BinOp(Shl) => op!('<', '<'),
120             BinOp(Shr) => op!('>', '>'),
121             BinOpEq(Plus) => op!('+', '='),
122             BinOpEq(Minus) => op!('-', '='),
123             BinOpEq(Star) => op!('*', '='),
124             BinOpEq(Slash) => op!('/', '='),
125             BinOpEq(Percent) => op!('%', '='),
126             BinOpEq(Caret) => op!('^', '='),
127             BinOpEq(And) => op!('&', '='),
128             BinOpEq(Or) => op!('|', '='),
129             BinOpEq(Shl) => op!('<', '<', '='),
130             BinOpEq(Shr) => op!('>', '>', '='),
131             At => op!('@'),
132             Dot => op!('.'),
133             DotDot => op!('.', '.'),
134             DotDotDot => op!('.', '.', '.'),
135             DotDotEq => op!('.', '.', '='),
136             Comma => op!(','),
137             Semi => op!(';'),
138             Colon => op!(':'),
139             ModSep => op!(':', ':'),
140             RArrow => op!('-', '>'),
141             LArrow => op!('<', '-'),
142             FatArrow => op!('=', '>'),
143             Pound => op!('#'),
144             Dollar => op!('$'),
145             Question => op!('?'),
146             SingleQuote => op!('\''),
147
148             Ident(name, false) if name == kw::DollarCrate => tt!(Ident::dollar_crate()),
149             Ident(name, is_raw) => tt!(Ident::new(rustc.sess, name, is_raw)),
150             Lifetime(name) => {
151                 let ident = symbol::Ident::new(name, span).without_first_quote();
152                 stack.push(tt!(Ident::new(rustc.sess, ident.name, false)));
153                 tt!(Punct::new('\'', true))
154             }
155             Literal(lit) => tt!(Literal { lit }),
156             DocComment(_, attr_style, data) => {
157                 let mut escaped = String::new();
158                 for ch in data.as_str().chars() {
159                     escaped.extend(ch.escape_debug());
160                 }
161                 let stream = vec![
162                     Ident(sym::doc, false),
163                     Eq,
164                     TokenKind::lit(token::Str, Symbol::intern(&escaped), None),
165                 ]
166                 .into_iter()
167                 .map(|kind| tokenstream::TokenTree::token(kind, span))
168                 .collect();
169                 stack.push(TokenTree::Group(Group {
170                     delimiter: Delimiter::Bracket,
171                     stream,
172                     span: DelimSpan::from_single(span),
173                     flatten: false,
174                 }));
175                 if attr_style == ast::AttrStyle::Inner {
176                     stack.push(tt!(Punct::new('!', false)));
177                 }
178                 tt!(Punct::new('#', false))
179             }
180
181             Interpolated(nt)
182                 if let Some((name, is_raw)) = ident_name_compatibility_hack(&nt, span, rustc) =>
183             {
184                 TokenTree::Ident(Ident::new(rustc.sess, name.name, is_raw, name.span))
185             }
186             Interpolated(nt) => {
187                 let stream = nt_to_tokenstream(&nt, rustc.sess, CanSynthesizeMissingTokens::No);
188                 TokenTree::Group(Group {
189                     delimiter: Delimiter::None,
190                     stream,
191                     span: DelimSpan::from_single(span),
192                     flatten: crate::base::pretty_printing_compatibility_hack(&nt, rustc.sess),
193                 })
194             }
195
196             OpenDelim(..) | CloseDelim(..) => unreachable!(),
197             Eof => unreachable!(),
198         }
199     }
200 }
201
202 impl ToInternal<TokenStream> for TokenTree<Group, Punct, Ident, Literal> {
203     fn to_internal(self) -> TokenStream {
204         use rustc_ast::token::*;
205
206         let (ch, joint, span) = match self {
207             TokenTree::Punct(Punct { ch, joint, span }) => (ch, joint, span),
208             TokenTree::Group(Group { delimiter, stream, span, .. }) => {
209                 return tokenstream::TokenTree::Delimited(span, delimiter.to_internal(), stream)
210                     .into();
211             }
212             TokenTree::Ident(self::Ident { sym, is_raw, span }) => {
213                 return tokenstream::TokenTree::token(Ident(sym, is_raw), span).into();
214             }
215             TokenTree::Literal(self::Literal {
216                 lit: token::Lit { kind: token::Integer, symbol, suffix },
217                 span,
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(minus, span);
223                 let b = tokenstream::TokenTree::token(integer, span);
224                 return vec![a, b].into_iter().collect();
225             }
226             TokenTree::Literal(self::Literal {
227                 lit: token::Lit { kind: token::Float, symbol, suffix },
228                 span,
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(minus, span);
234                 let b = tokenstream::TokenTree::token(float, span);
235                 return vec![a, b].into_iter().collect();
236             }
237             TokenTree::Literal(self::Literal { lit, span }) => {
238                 return tokenstream::TokenTree::token(Literal(lit), span).into();
239             }
240         };
241
242         let kind = match ch {
243             '=' => Eq,
244             '<' => Lt,
245             '>' => Gt,
246             '!' => Not,
247             '~' => Tilde,
248             '+' => BinOp(Plus),
249             '-' => BinOp(Minus),
250             '*' => BinOp(Star),
251             '/' => BinOp(Slash),
252             '%' => BinOp(Percent),
253             '^' => BinOp(Caret),
254             '&' => BinOp(And),
255             '|' => BinOp(Or),
256             '@' => At,
257             '.' => Dot,
258             ',' => Comma,
259             ';' => Semi,
260             ':' => Colon,
261             '#' => Pound,
262             '$' => Dollar,
263             '?' => Question,
264             '\'' => SingleQuote,
265             _ => unreachable!(),
266         };
267
268         let tree = tokenstream::TokenTree::token(kind, span);
269         TokenStream::new(vec![(tree, if joint { Joint } else { Alone })])
270     }
271 }
272
273 impl ToInternal<rustc_errors::Level> for Level {
274     fn to_internal(self) -> rustc_errors::Level {
275         match self {
276             Level::Error => rustc_errors::Level::Error,
277             Level::Warning => rustc_errors::Level::Warning,
278             Level::Note => rustc_errors::Level::Note,
279             Level::Help => rustc_errors::Level::Help,
280             _ => unreachable!("unknown proc_macro::Level variant: {:?}", self),
281         }
282     }
283 }
284
285 pub struct FreeFunctions;
286
287 #[derive(Clone)]
288 pub struct TokenStreamIter {
289     cursor: tokenstream::Cursor,
290     stack: Vec<TokenTree<Group, Punct, Ident, Literal>>,
291 }
292
293 #[derive(Clone)]
294 pub struct Group {
295     delimiter: Delimiter,
296     stream: TokenStream,
297     span: DelimSpan,
298     /// A hack used to pass AST fragments to attribute and derive macros
299     /// as a single nonterminal token instead of a token stream.
300     /// FIXME: It needs to be removed, but there are some compatibility issues (see #73345).
301     flatten: bool,
302 }
303
304 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
305 pub struct Punct {
306     ch: char,
307     // NB. not using `Spacing` here because it doesn't implement `Hash`.
308     joint: bool,
309     span: Span,
310 }
311
312 impl Punct {
313     fn new(ch: char, joint: bool, span: Span) -> Punct {
314         const LEGAL_CHARS: &[char] = &[
315             '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
316             ':', '#', '$', '?', '\'',
317         ];
318         if !LEGAL_CHARS.contains(&ch) {
319             panic!("unsupported character `{:?}`", ch)
320         }
321         Punct { ch, joint, span }
322     }
323 }
324
325 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
326 pub struct Ident {
327     sym: Symbol,
328     is_raw: bool,
329     span: Span,
330 }
331
332 impl Ident {
333     fn new(sess: &ParseSess, sym: Symbol, is_raw: bool, span: Span) -> Ident {
334         let sym = nfc_normalize(&sym.as_str());
335         let string = sym.as_str();
336         if !rustc_lexer::is_ident(&string) {
337             panic!("`{:?}` is not a valid identifier", string)
338         }
339         if is_raw && !sym.can_be_raw() {
340             panic!("`{}` cannot be a raw identifier", string);
341         }
342         sess.symbol_gallery.insert(sym, span);
343         Ident { sym, is_raw, span }
344     }
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 }
348     }
349 }
350
351 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
352 #[derive(Clone, Debug)]
353 pub struct Literal {
354     lit: token::Lit,
355     span: Span,
356 }
357
358 pub(crate) struct Rustc<'a> {
359     resolver: &'a dyn ResolverExpand,
360     sess: &'a ParseSess,
361     def_site: Span,
362     call_site: Span,
363     mixed_site: Span,
364     span_debug: bool,
365     krate: CrateNum,
366     rebased_spans: FxHashMap<usize, Span>,
367 }
368
369 impl<'a> Rustc<'a> {
370     pub fn new(cx: &'a ExtCtxt<'_>) -> Self {
371         let expn_data = cx.current_expansion.id.expn_data();
372         Rustc {
373             resolver: cx.resolver,
374             sess: cx.parse_sess(),
375             def_site: cx.with_def_site_ctxt(expn_data.def_site),
376             call_site: cx.with_call_site_ctxt(expn_data.call_site),
377             mixed_site: cx.with_mixed_site_ctxt(expn_data.call_site),
378             span_debug: cx.ecfg.span_debug,
379             krate: expn_data.macro_def_id.unwrap().krate,
380             rebased_spans: FxHashMap::default(),
381         }
382     }
383
384     fn lit(&mut self, kind: token::LitKind, symbol: Symbol, suffix: Option<Symbol>) -> Literal {
385         Literal { lit: token::Lit::new(kind, symbol, suffix), span: server::Span::call_site(self) }
386     }
387 }
388
389 impl server::Types for Rustc<'_> {
390     type FreeFunctions = FreeFunctions;
391     type TokenStream = TokenStream;
392     type TokenStreamBuilder = tokenstream::TokenStreamBuilder;
393     type TokenStreamIter = TokenStreamIter;
394     type Group = Group;
395     type Punct = Punct;
396     type Ident = Ident;
397     type Literal = Literal;
398     type SourceFile = Lrc<SourceFile>;
399     type MultiSpan = Vec<Span>;
400     type Diagnostic = Diagnostic;
401     type Span = Span;
402 }
403
404 impl server::FreeFunctions for Rustc<'_> {
405     fn track_env_var(&mut self, var: &str, value: Option<&str>) {
406         self.sess.env_depinfo.borrow_mut().insert((Symbol::intern(var), value.map(Symbol::intern)));
407     }
408
409     fn track_path(&mut self, path: &str) {
410         self.sess.file_depinfo.borrow_mut().insert(Symbol::intern(path));
411     }
412 }
413
414 impl server::TokenStream for Rustc<'_> {
415     fn new(&mut self) -> Self::TokenStream {
416         TokenStream::default()
417     }
418     fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
419         stream.is_empty()
420     }
421     fn from_str(&mut self, src: &str) -> Self::TokenStream {
422         parse_stream_from_source_str(
423             FileName::proc_macro_source_code(src),
424             src.to_string(),
425             self.sess,
426             Some(self.call_site),
427         )
428     }
429     fn to_string(&mut self, stream: &Self::TokenStream) -> String {
430         pprust::tts_to_string(stream)
431     }
432     fn from_token_tree(
433         &mut self,
434         tree: TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>,
435     ) -> Self::TokenStream {
436         tree.to_internal()
437     }
438     fn into_iter(&mut self, stream: Self::TokenStream) -> Self::TokenStreamIter {
439         TokenStreamIter { cursor: stream.trees(), stack: vec![] }
440     }
441 }
442
443 impl server::TokenStreamBuilder for Rustc<'_> {
444     fn new(&mut self) -> Self::TokenStreamBuilder {
445         tokenstream::TokenStreamBuilder::new()
446     }
447     fn push(&mut self, builder: &mut Self::TokenStreamBuilder, stream: Self::TokenStream) {
448         builder.push(stream);
449     }
450     fn build(&mut self, builder: Self::TokenStreamBuilder) -> Self::TokenStream {
451         builder.build()
452     }
453 }
454
455 impl server::TokenStreamIter for Rustc<'_> {
456     fn next(
457         &mut self,
458         iter: &mut Self::TokenStreamIter,
459     ) -> Option<TokenTree<Self::Group, Self::Punct, Self::Ident, Self::Literal>> {
460         loop {
461             let tree = iter.stack.pop().or_else(|| {
462                 let next = iter.cursor.next_with_spacing()?;
463                 Some(TokenTree::from_internal((next, &mut iter.stack, self)))
464             })?;
465             // A hack used to pass AST fragments to attribute and derive macros
466             // as a single nonterminal token instead of a token stream.
467             // Such token needs to be "unwrapped" and not represented as a delimited group.
468             // FIXME: It needs to be removed, but there are some compatibility issues (see #73345).
469             if let TokenTree::Group(ref group) = tree {
470                 if group.flatten {
471                     iter.cursor.append(group.stream.clone());
472                     continue;
473                 }
474             }
475             return Some(tree);
476         }
477     }
478 }
479
480 impl server::Group for Rustc<'_> {
481     fn new(&mut self, delimiter: Delimiter, stream: Self::TokenStream) -> Self::Group {
482         Group {
483             delimiter,
484             stream,
485             span: DelimSpan::from_single(server::Span::call_site(self)),
486             flatten: false,
487         }
488     }
489     fn delimiter(&mut self, group: &Self::Group) -> Delimiter {
490         group.delimiter
491     }
492     fn stream(&mut self, group: &Self::Group) -> Self::TokenStream {
493         group.stream.clone()
494     }
495     fn span(&mut self, group: &Self::Group) -> Self::Span {
496         group.span.entire()
497     }
498     fn span_open(&mut self, group: &Self::Group) -> Self::Span {
499         group.span.open
500     }
501     fn span_close(&mut self, group: &Self::Group) -> Self::Span {
502         group.span.close
503     }
504     fn set_span(&mut self, group: &mut Self::Group, span: Self::Span) {
505         group.span = DelimSpan::from_single(span);
506     }
507 }
508
509 impl server::Punct for Rustc<'_> {
510     fn new(&mut self, ch: char, spacing: Spacing) -> Self::Punct {
511         Punct::new(ch, spacing == Spacing::Joint, server::Span::call_site(self))
512     }
513     fn as_char(&mut self, punct: Self::Punct) -> char {
514         punct.ch
515     }
516     fn spacing(&mut self, punct: Self::Punct) -> Spacing {
517         if punct.joint { Spacing::Joint } else { Spacing::Alone }
518     }
519     fn span(&mut self, punct: Self::Punct) -> Self::Span {
520         punct.span
521     }
522     fn with_span(&mut self, punct: Self::Punct, span: Self::Span) -> Self::Punct {
523         Punct { span, ..punct }
524     }
525 }
526
527 impl server::Ident for Rustc<'_> {
528     fn new(&mut self, string: &str, span: Self::Span, is_raw: bool) -> Self::Ident {
529         Ident::new(self.sess, Symbol::intern(string), is_raw, span)
530     }
531     fn span(&mut self, ident: Self::Ident) -> Self::Span {
532         ident.span
533     }
534     fn with_span(&mut self, ident: Self::Ident, span: Self::Span) -> Self::Ident {
535         Ident { span, ..ident }
536     }
537 }
538
539 impl server::Literal for Rustc<'_> {
540     fn from_str(&mut self, s: &str) -> Result<Self::Literal, ()> {
541         let name = FileName::proc_macro_source_code(s);
542         let mut parser = rustc_parse::new_parser_from_source_str(self.sess, name, s.to_owned());
543
544         let first_span = parser.token.span.data();
545         let minus_present = parser.eat(&token::BinOp(token::Minus));
546
547         let lit_span = parser.token.span.data();
548         let mut lit = match parser.token.kind {
549             token::Literal(lit) => lit,
550             _ => return Err(()),
551         };
552
553         // Check no comment or whitespace surrounding the (possibly negative)
554         // literal, or more tokens after it.
555         if (lit_span.hi.0 - first_span.lo.0) as usize != s.len() {
556             return Err(());
557         }
558
559         if minus_present {
560             // If minus is present, check no comment or whitespace in between it
561             // and the literal token.
562             if first_span.hi.0 != lit_span.lo.0 {
563                 return Err(());
564             }
565
566             // Check literal is a kind we allow to be negated in a proc macro token.
567             match lit.kind {
568                 token::LitKind::Bool
569                 | token::LitKind::Byte
570                 | token::LitKind::Char
571                 | token::LitKind::Str
572                 | token::LitKind::StrRaw(_)
573                 | token::LitKind::ByteStr
574                 | token::LitKind::ByteStrRaw(_)
575                 | token::LitKind::Err => return Err(()),
576                 token::LitKind::Integer | token::LitKind::Float => {}
577             }
578
579             // Synthesize a new symbol that includes the minus sign.
580             let symbol = Symbol::intern(&s[..1 + lit.symbol.as_str().len()]);
581             lit = token::Lit::new(lit.kind, symbol, lit.suffix);
582         }
583
584         Ok(Literal { lit, span: self.call_site })
585     }
586     fn to_string(&mut self, literal: &Self::Literal) -> String {
587         literal.lit.to_string()
588     }
589     fn debug_kind(&mut self, literal: &Self::Literal) -> String {
590         format!("{:?}", literal.lit.kind)
591     }
592     fn symbol(&mut self, literal: &Self::Literal) -> String {
593         literal.lit.symbol.to_string()
594     }
595     fn suffix(&mut self, literal: &Self::Literal) -> Option<String> {
596         literal.lit.suffix.as_ref().map(Symbol::to_string)
597     }
598     fn integer(&mut self, n: &str) -> Self::Literal {
599         self.lit(token::Integer, Symbol::intern(n), None)
600     }
601     fn typed_integer(&mut self, n: &str, kind: &str) -> Self::Literal {
602         self.lit(token::Integer, Symbol::intern(n), Some(Symbol::intern(kind)))
603     }
604     fn float(&mut self, n: &str) -> Self::Literal {
605         self.lit(token::Float, Symbol::intern(n), None)
606     }
607     fn f32(&mut self, n: &str) -> Self::Literal {
608         self.lit(token::Float, Symbol::intern(n), Some(sym::f32))
609     }
610     fn f64(&mut self, n: &str) -> Self::Literal {
611         self.lit(token::Float, Symbol::intern(n), Some(sym::f64))
612     }
613     fn string(&mut self, string: &str) -> Self::Literal {
614         let mut escaped = String::new();
615         for ch in string.chars() {
616             escaped.extend(ch.escape_debug());
617         }
618         self.lit(token::Str, Symbol::intern(&escaped), None)
619     }
620     fn character(&mut self, ch: char) -> Self::Literal {
621         let mut escaped = String::new();
622         escaped.extend(ch.escape_unicode());
623         self.lit(token::Char, Symbol::intern(&escaped), None)
624     }
625     fn byte_string(&mut self, bytes: &[u8]) -> Self::Literal {
626         let string = bytes
627             .iter()
628             .cloned()
629             .flat_map(ascii::escape_default)
630             .map(Into::<char>::into)
631             .collect::<String>();
632         self.lit(token::ByteStr, Symbol::intern(&string), None)
633     }
634     fn span(&mut self, literal: &Self::Literal) -> Self::Span {
635         literal.span
636     }
637     fn set_span(&mut self, literal: &mut Self::Literal, span: Self::Span) {
638         literal.span = span;
639     }
640     fn subspan(
641         &mut self,
642         literal: &Self::Literal,
643         start: Bound<usize>,
644         end: Bound<usize>,
645     ) -> Option<Self::Span> {
646         let span = literal.span;
647         let length = span.hi().to_usize() - span.lo().to_usize();
648
649         let start = match start {
650             Bound::Included(lo) => lo,
651             Bound::Excluded(lo) => lo.checked_add(1)?,
652             Bound::Unbounded => 0,
653         };
654
655         let end = match end {
656             Bound::Included(hi) => hi.checked_add(1)?,
657             Bound::Excluded(hi) => hi,
658             Bound::Unbounded => length,
659         };
660
661         // Bounds check the values, preventing addition overflow and OOB spans.
662         if start > u32::MAX as usize
663             || end > u32::MAX as usize
664             || (u32::MAX - start as u32) < span.lo().to_u32()
665             || (u32::MAX - end as u32) < span.lo().to_u32()
666             || start >= end
667             || end > length
668         {
669             return None;
670         }
671
672         let new_lo = span.lo() + BytePos::from_usize(start);
673         let new_hi = span.lo() + BytePos::from_usize(end);
674         Some(span.with_lo(new_lo).with_hi(new_hi))
675     }
676 }
677
678 impl server::SourceFile for Rustc<'_> {
679     fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
680         Lrc::ptr_eq(file1, file2)
681     }
682     fn path(&mut self, file: &Self::SourceFile) -> String {
683         match file.name {
684             FileName::Real(ref name) => name
685                 .local_path()
686                 .expect("attempting to get a file path in an imported file in `proc_macro::SourceFile::path`")
687                 .to_str()
688                 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
689                 .to_string(),
690             _ => file.name.prefer_local().to_string(),
691         }
692     }
693     fn is_real(&mut self, file: &Self::SourceFile) -> bool {
694         file.is_real_file()
695     }
696 }
697
698 impl server::MultiSpan for Rustc<'_> {
699     fn new(&mut self) -> Self::MultiSpan {
700         vec![]
701     }
702     fn push(&mut self, spans: &mut Self::MultiSpan, span: Self::Span) {
703         spans.push(span)
704     }
705 }
706
707 impl server::Diagnostic for Rustc<'_> {
708     fn new(&mut self, level: Level, msg: &str, spans: Self::MultiSpan) -> Self::Diagnostic {
709         let mut diag = Diagnostic::new(level.to_internal(), msg);
710         diag.set_span(MultiSpan::from_spans(spans));
711         diag
712     }
713     fn sub(
714         &mut self,
715         diag: &mut Self::Diagnostic,
716         level: Level,
717         msg: &str,
718         spans: Self::MultiSpan,
719     ) {
720         diag.sub(level.to_internal(), msg, MultiSpan::from_spans(spans), None);
721     }
722     fn emit(&mut self, diag: Self::Diagnostic) {
723         self.sess.span_diagnostic.emit_diagnostic(&diag);
724     }
725 }
726
727 impl server::Span for Rustc<'_> {
728     fn debug(&mut self, span: Self::Span) -> String {
729         if self.span_debug {
730             format!("{:?}", span)
731         } else {
732             format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
733         }
734     }
735     fn def_site(&mut self) -> Self::Span {
736         self.def_site
737     }
738     fn call_site(&mut self) -> Self::Span {
739         self.call_site
740     }
741     fn mixed_site(&mut self) -> Self::Span {
742         self.mixed_site
743     }
744     fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
745         self.sess.source_map().lookup_char_pos(span.lo()).file
746     }
747     fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
748         span.parent_callsite()
749     }
750     fn source(&mut self, span: Self::Span) -> Self::Span {
751         span.source_callsite()
752     }
753     fn start(&mut self, span: Self::Span) -> LineColumn {
754         let loc = self.sess.source_map().lookup_char_pos(span.lo());
755         LineColumn { line: loc.line, column: loc.col.to_usize() }
756     }
757     fn end(&mut self, span: Self::Span) -> LineColumn {
758         let loc = self.sess.source_map().lookup_char_pos(span.hi());
759         LineColumn { line: loc.line, column: loc.col.to_usize() }
760     }
761     fn before(&mut self, span: Self::Span) -> Self::Span {
762         span.shrink_to_lo()
763     }
764     fn after(&mut self, span: Self::Span) -> Self::Span {
765         span.shrink_to_hi()
766     }
767     fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
768         let self_loc = self.sess.source_map().lookup_char_pos(first.lo());
769         let other_loc = self.sess.source_map().lookup_char_pos(second.lo());
770
771         if self_loc.file.name != other_loc.file.name {
772             return None;
773         }
774
775         Some(first.to(second))
776     }
777     fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
778         span.with_ctxt(at.ctxt())
779     }
780     fn source_text(&mut self, span: Self::Span) -> Option<String> {
781         self.sess.source_map().span_to_snippet(span).ok()
782     }
783     /// Saves the provided span into the metadata of
784     /// *the crate we are currently compiling*, which must
785     /// be a proc-macro crate. This id can be passed to
786     /// `recover_proc_macro_span` when our current crate
787     /// is *run* as a proc-macro.
788     ///
789     /// Let's suppose that we have two crates - `my_client`
790     /// and `my_proc_macro`. The `my_proc_macro` crate
791     /// contains a procedural macro `my_macro`, which
792     /// is implemented as: `quote! { "hello" }`
793     ///
794     /// When we *compile* `my_proc_macro`, we will execute
795     /// the `quote` proc-macro. This will save the span of
796     /// "hello" into the metadata of `my_proc_macro`. As a result,
797     /// the body of `my_proc_macro` (after expansion) will end
798     /// up containg a call that looks like this:
799     /// `proc_macro::Ident::new("hello", proc_macro::Span::recover_proc_macro_span(0))`
800     ///
801     /// where `0` is the id returned by this function.
802     /// When `my_proc_macro` *executes* (during the compilation of `my_client`),
803     /// the call to `recover_proc_macro_span` will load the corresponding
804     /// span from the metadata of `my_proc_macro` (which we have access to,
805     /// since we've loaded `my_proc_macro` from disk in order to execute it).
806     /// In this way, we have obtained a span pointing into `my_proc_macro`
807     fn save_span(&mut self, span: Self::Span) -> usize {
808         self.sess.save_proc_macro_span(span)
809     }
810     fn recover_proc_macro_span(&mut self, id: usize) -> Self::Span {
811         let (resolver, krate, def_site) = (self.resolver, self.krate, self.def_site);
812         *self.rebased_spans.entry(id).or_insert_with(|| {
813             // FIXME: `SyntaxContext` for spans from proc macro crates is lost during encoding,
814             // replace it with a def-site context until we are encoding it properly.
815             resolver.get_proc_macro_quoted_span(krate, id).with_ctxt(def_site.ctxt())
816         })
817     }
818 }
819
820 // See issue #74616 for details
821 fn ident_name_compatibility_hack(
822     nt: &Nonterminal,
823     orig_span: Span,
824     rustc: &mut Rustc<'_>,
825 ) -> Option<(rustc_span::symbol::Ident, bool)> {
826     if let NtIdent(ident, is_raw) = nt {
827         if let ExpnKind::Macro(_, macro_name) = orig_span.ctxt().outer_expn_data().kind {
828             let source_map = rustc.sess.source_map();
829             let filename = source_map.span_to_filename(orig_span);
830             if let FileName::Real(RealFileName::LocalPath(path)) = filename {
831                 let matches_prefix = |prefix, filename| {
832                     // Check for a path that ends with 'prefix*/src/<filename>'
833                     let mut iter = path.components().rev();
834                     iter.next().and_then(|p| p.as_os_str().to_str()) == Some(filename)
835                         && iter.next().and_then(|p| p.as_os_str().to_str()) == Some("src")
836                         && iter
837                             .next()
838                             .and_then(|p| p.as_os_str().to_str())
839                             .map_or(false, |p| p.starts_with(prefix))
840                 };
841
842                 let time_macros_impl =
843                     macro_name == sym::impl_macros && matches_prefix("time-macros-impl", "lib.rs");
844                 let js_sys = macro_name == sym::arrays && matches_prefix("js-sys", "lib.rs");
845                 if time_macros_impl || js_sys {
846                     let snippet = source_map.span_to_snippet(orig_span);
847                     if snippet.as_deref() == Ok("$name") {
848                         if time_macros_impl {
849                             rustc.sess.buffer_lint_with_diagnostic(
850                                 &PROC_MACRO_BACK_COMPAT,
851                                 orig_span,
852                                 ast::CRATE_NODE_ID,
853                                 "using an old version of `time-macros-impl`",
854                                 BuiltinLintDiagnostics::ProcMacroBackCompat(
855                                 "the `time-macros-impl` crate will stop compiling in futures version of Rust. \
856                                 Please update to the latest version of the `time` crate to avoid breakage".to_string())
857                             );
858                             return Some((*ident, *is_raw));
859                         }
860                         if js_sys {
861                             if let Some(c) = path
862                                 .components()
863                                 .flat_map(|c| c.as_os_str().to_str())
864                                 .find(|c| c.starts_with("js-sys"))
865                             {
866                                 let mut version = c.trim_start_matches("js-sys-").split('.');
867                                 if version.next() == Some("0")
868                                     && version.next() == Some("3")
869                                     && version
870                                         .next()
871                                         .and_then(|c| c.parse::<u32>().ok())
872                                         .map_or(false, |v| v < 40)
873                                 {
874                                     rustc.sess.buffer_lint_with_diagnostic(
875                                         &PROC_MACRO_BACK_COMPAT,
876                                         orig_span,
877                                         ast::CRATE_NODE_ID,
878                                         "using an old version of `js-sys`",
879                                         BuiltinLintDiagnostics::ProcMacroBackCompat(
880                                         "older versions of the `js-sys` crate will stop compiling in future versions of Rust; \
881                                         please update to `js-sys` v0.3.40 or above".to_string())
882                                     );
883                                     return Some((*ident, *is_raw));
884                                 }
885                             }
886                         }
887                     }
888                 }
889
890                 if macro_name == sym::tuple_from_req && matches_prefix("actix-web", "extract.rs") {
891                     let snippet = source_map.span_to_snippet(orig_span);
892                     if snippet.as_deref() == Ok("$T") {
893                         if let FileName::Real(RealFileName::LocalPath(macro_path)) =
894                             source_map.span_to_filename(rustc.def_site)
895                         {
896                             if macro_path.to_string_lossy().contains("pin-project-internal-0.") {
897                                 rustc.sess.buffer_lint_with_diagnostic(
898                                     &PROC_MACRO_BACK_COMPAT,
899                                     orig_span,
900                                     ast::CRATE_NODE_ID,
901                                     "using an old version of `actix-web`",
902                                     BuiltinLintDiagnostics::ProcMacroBackCompat(
903                                     "the version of `actix-web` you are using might stop compiling in future versions of Rust; \
904                                     please update to the latest version of the `actix-web` crate to avoid breakage".to_string())
905                                 );
906                                 return Some((*ident, *is_raw));
907                             }
908                         }
909                     }
910                 }
911             }
912         }
913     }
914     None
915 }