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