]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_expand/src/proc_macro_server.rs
Rollup merge of #102607 - WaffleLapkin:docky_docky_slice_from_ptr_range, r=joshtriplett
[rust.git] / compiler / rustc_expand / src / proc_macro_server.rs
1 use crate::base::ExtCtxt;
2
3 use rustc_ast as ast;
4 use rustc_ast::token;
5 use rustc_ast::tokenstream::{self, Spacing::*, TokenStream};
6 use rustc_ast_pretty::pprust;
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_data_structures::sync::Lrc;
9 use rustc_errors::{MultiSpan, PResult};
10 use rustc_parse::lexer::nfc_normalize;
11 use rustc_parse::parse_stream_from_source_str;
12 use rustc_session::parse::ParseSess;
13 use rustc_span::def_id::CrateNum;
14 use rustc_span::symbol::{self, sym, Symbol};
15 use rustc_span::{BytePos, FileName, Pos, SourceFile, Span};
16
17 use pm::bridge::{
18     server, DelimSpan, Diagnostic, ExpnGlobals, Group, Ident, LitKind, Literal, Punct, TokenTree,
19 };
20 use pm::{Delimiter, Level, LineColumn};
21 use std::ops::Bound;
22
23 trait FromInternal<T> {
24     fn from_internal(x: T) -> Self;
25 }
26
27 trait ToInternal<T> {
28     fn to_internal(self) -> T;
29 }
30
31 impl FromInternal<token::Delimiter> for Delimiter {
32     fn from_internal(delim: token::Delimiter) -> Delimiter {
33         match delim {
34             token::Delimiter::Parenthesis => Delimiter::Parenthesis,
35             token::Delimiter::Brace => Delimiter::Brace,
36             token::Delimiter::Bracket => Delimiter::Bracket,
37             token::Delimiter::Invisible => Delimiter::None,
38         }
39     }
40 }
41
42 impl ToInternal<token::Delimiter> for Delimiter {
43     fn to_internal(self) -> token::Delimiter {
44         match self {
45             Delimiter::Parenthesis => token::Delimiter::Parenthesis,
46             Delimiter::Brace => token::Delimiter::Brace,
47             Delimiter::Bracket => token::Delimiter::Bracket,
48             Delimiter::None => token::Delimiter::Invisible,
49         }
50     }
51 }
52
53 impl FromInternal<token::LitKind> for LitKind {
54     fn from_internal(kind: token::LitKind) -> Self {
55         match kind {
56             token::Byte => LitKind::Byte,
57             token::Char => LitKind::Char,
58             token::Integer => LitKind::Integer,
59             token::Float => LitKind::Float,
60             token::Str => LitKind::Str,
61             token::StrRaw(n) => LitKind::StrRaw(n),
62             token::ByteStr => LitKind::ByteStr,
63             token::ByteStrRaw(n) => LitKind::ByteStrRaw(n),
64             token::Err => LitKind::Err,
65             token::Bool => unreachable!(),
66         }
67     }
68 }
69
70 impl ToInternal<token::LitKind> for LitKind {
71     fn to_internal(self) -> token::LitKind {
72         match self {
73             LitKind::Byte => token::Byte,
74             LitKind::Char => token::Char,
75             LitKind::Integer => token::Integer,
76             LitKind::Float => token::Float,
77             LitKind::Str => token::Str,
78             LitKind::StrRaw(n) => token::StrRaw(n),
79             LitKind::ByteStr => token::ByteStr,
80             LitKind::ByteStrRaw(n) => token::ByteStrRaw(n),
81             LitKind::Err => token::Err,
82         }
83     }
84 }
85
86 impl FromInternal<(TokenStream, &mut Rustc<'_, '_>)> for Vec<TokenTree<TokenStream, Span, Symbol>> {
87     fn from_internal((stream, rustc): (TokenStream, &mut Rustc<'_, '_>)) -> Self {
88         use rustc_ast::token::*;
89
90         // Estimate the capacity as `stream.len()` rounded up to the next power
91         // of two to limit the number of required reallocations.
92         let mut trees = Vec::with_capacity(stream.len().next_power_of_two());
93         let mut cursor = stream.into_trees();
94
95         while let Some(tree) = cursor.next() {
96             let (Token { kind, span }, joint) = match tree {
97                 tokenstream::TokenTree::Delimited(span, delim, tts) => {
98                     let delimiter = pm::Delimiter::from_internal(delim);
99                     trees.push(TokenTree::Group(Group {
100                         delimiter,
101                         stream: Some(tts),
102                         span: DelimSpan {
103                             open: span.open,
104                             close: span.close,
105                             entire: span.entire(),
106                         },
107                     }));
108                     continue;
109                 }
110                 tokenstream::TokenTree::Token(token, spacing) => (token, spacing == Joint),
111             };
112
113             // Split the operator into one or more `Punct`s, one per character.
114             // The final one inherits the jointness of the original token. Any
115             // before that get `joint = true`.
116             let mut op = |s: &str| {
117                 assert!(s.is_ascii());
118                 trees.extend(s.bytes().enumerate().map(|(idx, ch)| {
119                     let is_final = idx == s.len() - 1;
120                     TokenTree::Punct(Punct { ch, joint: if is_final { joint } else { true }, span })
121                 }));
122             };
123
124             match kind {
125                 Eq => op("="),
126                 Lt => op("<"),
127                 Le => op("<="),
128                 EqEq => op("=="),
129                 Ne => op("!="),
130                 Ge => op(">="),
131                 Gt => op(">"),
132                 AndAnd => op("&&"),
133                 OrOr => op("||"),
134                 Not => op("!"),
135                 Tilde => op("~"),
136                 BinOp(Plus) => op("+"),
137                 BinOp(Minus) => op("-"),
138                 BinOp(Star) => op("*"),
139                 BinOp(Slash) => op("/"),
140                 BinOp(Percent) => op("%"),
141                 BinOp(Caret) => op("^"),
142                 BinOp(And) => op("&"),
143                 BinOp(Or) => op("|"),
144                 BinOp(Shl) => op("<<"),
145                 BinOp(Shr) => op(">>"),
146                 BinOpEq(Plus) => op("+="),
147                 BinOpEq(Minus) => op("-="),
148                 BinOpEq(Star) => op("*="),
149                 BinOpEq(Slash) => op("/="),
150                 BinOpEq(Percent) => op("%="),
151                 BinOpEq(Caret) => op("^="),
152                 BinOpEq(And) => op("&="),
153                 BinOpEq(Or) => op("|="),
154                 BinOpEq(Shl) => op("<<="),
155                 BinOpEq(Shr) => op(">>="),
156                 At => op("@"),
157                 Dot => op("."),
158                 DotDot => op(".."),
159                 DotDotDot => op("..."),
160                 DotDotEq => op("..="),
161                 Comma => op(","),
162                 Semi => op(";"),
163                 Colon => op(":"),
164                 ModSep => op("::"),
165                 RArrow => op("->"),
166                 LArrow => op("<-"),
167                 FatArrow => op("=>"),
168                 Pound => op("#"),
169                 Dollar => op("$"),
170                 Question => op("?"),
171                 SingleQuote => op("'"),
172
173                 Ident(sym, is_raw) => trees.push(TokenTree::Ident(Ident { sym, is_raw, span })),
174                 Lifetime(name) => {
175                     let ident = symbol::Ident::new(name, span).without_first_quote();
176                     trees.extend([
177                         TokenTree::Punct(Punct { ch: b'\'', joint: true, span }),
178                         TokenTree::Ident(Ident { sym: ident.name, is_raw: false, span }),
179                     ]);
180                 }
181                 Literal(token::Lit { kind, symbol, suffix }) => {
182                     trees.push(TokenTree::Literal(self::Literal {
183                         kind: FromInternal::from_internal(kind),
184                         symbol,
185                         suffix,
186                         span,
187                     }));
188                 }
189                 DocComment(_, attr_style, data) => {
190                     let mut escaped = String::new();
191                     for ch in data.as_str().chars() {
192                         escaped.extend(ch.escape_debug());
193                     }
194                     let stream = [
195                         Ident(sym::doc, false),
196                         Eq,
197                         TokenKind::lit(token::Str, Symbol::intern(&escaped), None),
198                     ]
199                     .into_iter()
200                     .map(|kind| tokenstream::TokenTree::token_alone(kind, span))
201                     .collect();
202                     trees.push(TokenTree::Punct(Punct { ch: b'#', joint: false, span }));
203                     if attr_style == ast::AttrStyle::Inner {
204                         trees.push(TokenTree::Punct(Punct { ch: b'!', joint: false, span }));
205                     }
206                     trees.push(TokenTree::Group(Group {
207                         delimiter: pm::Delimiter::Bracket,
208                         stream: Some(stream),
209                         span: DelimSpan::from_single(span),
210                     }));
211                 }
212
213                 Interpolated(nt) if let NtIdent(ident, is_raw) = *nt => {
214                     trees.push(TokenTree::Ident(Ident { sym: ident.name, is_raw, span: ident.span }))
215                 }
216
217                 Interpolated(nt) => {
218                     let stream = TokenStream::from_nonterminal_ast(&nt);
219                     // A hack used to pass AST fragments to attribute and derive
220                     // macros as a single nonterminal token instead of a token
221                     // stream.  Such token needs to be "unwrapped" and not
222                     // represented as a delimited group.
223                     // FIXME: It needs to be removed, but there are some
224                     // compatibility issues (see #73345).
225                     if crate::base::nt_pretty_printing_compatibility_hack(&nt, rustc.sess()) {
226                         trees.extend(Self::from_internal((stream, rustc)));
227                     } else {
228                         trees.push(TokenTree::Group(Group {
229                             delimiter: pm::Delimiter::None,
230                             stream: Some(stream),
231                             span: DelimSpan::from_single(span),
232                         }))
233                     }
234                 }
235
236                 OpenDelim(..) | CloseDelim(..) => unreachable!(),
237                 Eof => unreachable!(),
238             }
239         }
240         trees
241     }
242 }
243
244 impl ToInternal<TokenStream> for (TokenTree<TokenStream, Span, Symbol>, &mut Rustc<'_, '_>) {
245     fn to_internal(self) -> TokenStream {
246         use rustc_ast::token::*;
247
248         let (tree, rustc) = self;
249         let (ch, joint, span) = match tree {
250             TokenTree::Punct(Punct { ch, joint, span }) => (ch, joint, span),
251             TokenTree::Group(Group { delimiter, stream, span: DelimSpan { open, close, .. } }) => {
252                 return tokenstream::TokenStream::delimited(
253                     tokenstream::DelimSpan { open, close },
254                     delimiter.to_internal(),
255                     stream.unwrap_or_default(),
256                 );
257             }
258             TokenTree::Ident(self::Ident { sym, is_raw, span }) => {
259                 rustc.sess().symbol_gallery.insert(sym, span);
260                 return tokenstream::TokenStream::token_alone(Ident(sym, is_raw), span);
261             }
262             TokenTree::Literal(self::Literal {
263                 kind: self::LitKind::Integer,
264                 symbol,
265                 suffix,
266                 span,
267             }) if symbol.as_str().starts_with('-') => {
268                 let minus = BinOp(BinOpToken::Minus);
269                 let symbol = Symbol::intern(&symbol.as_str()[1..]);
270                 let integer = TokenKind::lit(token::Integer, symbol, suffix);
271                 let a = tokenstream::TokenTree::token_alone(minus, span);
272                 let b = tokenstream::TokenTree::token_alone(integer, span);
273                 return [a, b].into_iter().collect();
274             }
275             TokenTree::Literal(self::Literal {
276                 kind: self::LitKind::Float,
277                 symbol,
278                 suffix,
279                 span,
280             }) if symbol.as_str().starts_with('-') => {
281                 let minus = BinOp(BinOpToken::Minus);
282                 let symbol = Symbol::intern(&symbol.as_str()[1..]);
283                 let float = TokenKind::lit(token::Float, symbol, suffix);
284                 let a = tokenstream::TokenTree::token_alone(minus, span);
285                 let b = tokenstream::TokenTree::token_alone(float, span);
286                 return [a, b].into_iter().collect();
287             }
288             TokenTree::Literal(self::Literal { kind, symbol, suffix, span }) => {
289                 return tokenstream::TokenStream::token_alone(
290                     TokenKind::lit(kind.to_internal(), symbol, suffix),
291                     span,
292                 );
293             }
294         };
295
296         let kind = match ch {
297             b'=' => Eq,
298             b'<' => Lt,
299             b'>' => Gt,
300             b'!' => Not,
301             b'~' => Tilde,
302             b'+' => BinOp(Plus),
303             b'-' => BinOp(Minus),
304             b'*' => BinOp(Star),
305             b'/' => BinOp(Slash),
306             b'%' => BinOp(Percent),
307             b'^' => BinOp(Caret),
308             b'&' => BinOp(And),
309             b'|' => BinOp(Or),
310             b'@' => At,
311             b'.' => Dot,
312             b',' => Comma,
313             b';' => Semi,
314             b':' => Colon,
315             b'#' => Pound,
316             b'$' => Dollar,
317             b'?' => Question,
318             b'\'' => SingleQuote,
319             _ => unreachable!(),
320         };
321
322         if joint {
323             tokenstream::TokenStream::token_joint(kind, span)
324         } else {
325             tokenstream::TokenStream::token_alone(kind, span)
326         }
327     }
328 }
329
330 impl ToInternal<rustc_errors::Level> for Level {
331     fn to_internal(self) -> rustc_errors::Level {
332         match self {
333             Level::Error => rustc_errors::Level::Error { lint: false },
334             Level::Warning => rustc_errors::Level::Warning(None),
335             Level::Note => rustc_errors::Level::Note,
336             Level::Help => rustc_errors::Level::Help,
337             _ => unreachable!("unknown proc_macro::Level variant: {:?}", self),
338         }
339     }
340 }
341
342 pub struct FreeFunctions;
343
344 pub(crate) struct Rustc<'a, 'b> {
345     ecx: &'a mut ExtCtxt<'b>,
346     def_site: Span,
347     call_site: Span,
348     mixed_site: Span,
349     krate: CrateNum,
350     rebased_spans: FxHashMap<usize, Span>,
351 }
352
353 impl<'a, 'b> Rustc<'a, 'b> {
354     pub fn new(ecx: &'a mut ExtCtxt<'b>) -> Self {
355         let expn_data = ecx.current_expansion.id.expn_data();
356         Rustc {
357             def_site: ecx.with_def_site_ctxt(expn_data.def_site),
358             call_site: ecx.with_call_site_ctxt(expn_data.call_site),
359             mixed_site: ecx.with_mixed_site_ctxt(expn_data.call_site),
360             krate: expn_data.macro_def_id.unwrap().krate,
361             rebased_spans: FxHashMap::default(),
362             ecx,
363         }
364     }
365
366     fn sess(&self) -> &ParseSess {
367         self.ecx.parse_sess()
368     }
369 }
370
371 impl server::Types for Rustc<'_, '_> {
372     type FreeFunctions = FreeFunctions;
373     type TokenStream = TokenStream;
374     type SourceFile = Lrc<SourceFile>;
375     type Span = Span;
376     type Symbol = Symbol;
377 }
378
379 impl server::FreeFunctions for Rustc<'_, '_> {
380     fn track_env_var(&mut self, var: &str, value: Option<&str>) {
381         self.sess()
382             .env_depinfo
383             .borrow_mut()
384             .insert((Symbol::intern(var), value.map(Symbol::intern)));
385     }
386
387     fn track_path(&mut self, path: &str) {
388         self.sess().file_depinfo.borrow_mut().insert(Symbol::intern(path));
389     }
390
391     fn literal_from_str(&mut self, s: &str) -> Result<Literal<Self::Span, Self::Symbol>, ()> {
392         let name = FileName::proc_macro_source_code(s);
393         let mut parser = rustc_parse::new_parser_from_source_str(self.sess(), name, s.to_owned());
394
395         let first_span = parser.token.span.data();
396         let minus_present = parser.eat(&token::BinOp(token::Minus));
397
398         let lit_span = parser.token.span.data();
399         let token::Literal(mut lit) = parser.token.kind else {
400             return Err(());
401         };
402
403         // Check no comment or whitespace surrounding the (possibly negative)
404         // literal, or more tokens after it.
405         if (lit_span.hi.0 - first_span.lo.0) as usize != s.len() {
406             return Err(());
407         }
408
409         if minus_present {
410             // If minus is present, check no comment or whitespace in between it
411             // and the literal token.
412             if first_span.hi.0 != lit_span.lo.0 {
413                 return Err(());
414             }
415
416             // Check literal is a kind we allow to be negated in a proc macro token.
417             match lit.kind {
418                 token::LitKind::Bool
419                 | token::LitKind::Byte
420                 | token::LitKind::Char
421                 | token::LitKind::Str
422                 | token::LitKind::StrRaw(_)
423                 | token::LitKind::ByteStr
424                 | token::LitKind::ByteStrRaw(_)
425                 | token::LitKind::Err => return Err(()),
426                 token::LitKind::Integer | token::LitKind::Float => {}
427             }
428
429             // Synthesize a new symbol that includes the minus sign.
430             let symbol = Symbol::intern(&s[..1 + lit.symbol.as_str().len()]);
431             lit = token::Lit::new(lit.kind, symbol, lit.suffix);
432         }
433         let token::Lit { kind, symbol, suffix } = lit;
434         Ok(Literal {
435             kind: FromInternal::from_internal(kind),
436             symbol,
437             suffix,
438             span: self.call_site,
439         })
440     }
441
442     fn emit_diagnostic(&mut self, diagnostic: Diagnostic<Self::Span>) {
443         let mut diag =
444             rustc_errors::Diagnostic::new(diagnostic.level.to_internal(), diagnostic.message);
445         diag.set_span(MultiSpan::from_spans(diagnostic.spans));
446         for child in diagnostic.children {
447             diag.sub(
448                 child.level.to_internal(),
449                 child.message,
450                 MultiSpan::from_spans(child.spans),
451                 None,
452             );
453         }
454         self.sess().span_diagnostic.emit_diagnostic(&mut diag);
455     }
456 }
457
458 impl server::TokenStream for Rustc<'_, '_> {
459     fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
460         stream.is_empty()
461     }
462
463     fn from_str(&mut self, src: &str) -> Self::TokenStream {
464         parse_stream_from_source_str(
465             FileName::proc_macro_source_code(src),
466             src.to_string(),
467             self.sess(),
468             Some(self.call_site),
469         )
470     }
471
472     fn to_string(&mut self, stream: &Self::TokenStream) -> String {
473         pprust::tts_to_string(stream)
474     }
475
476     fn expand_expr(&mut self, stream: &Self::TokenStream) -> Result<Self::TokenStream, ()> {
477         // Parse the expression from our tokenstream.
478         let expr: PResult<'_, _> = try {
479             let mut p = rustc_parse::stream_to_parser(
480                 self.sess(),
481                 stream.clone(),
482                 Some("proc_macro expand expr"),
483             );
484             let expr = p.parse_expr()?;
485             if p.token != token::Eof {
486                 p.unexpected()?;
487             }
488             expr
489         };
490         let expr = expr.map_err(|mut err| {
491             err.emit();
492         })?;
493
494         // Perform eager expansion on the expression.
495         let expr = self
496             .ecx
497             .expander()
498             .fully_expand_fragment(crate::expand::AstFragment::Expr(expr))
499             .make_expr();
500
501         // NOTE: For now, limit `expand_expr` to exclusively expand to literals.
502         // This may be relaxed in the future.
503         // We don't use `TokenStream::from_ast` as the tokenstream currently cannot
504         // be recovered in the general case.
505         match &expr.kind {
506             ast::ExprKind::Lit(l) if l.token_lit.kind == token::Bool => {
507                 Ok(tokenstream::TokenStream::token_alone(
508                     token::Ident(l.token_lit.symbol, false),
509                     l.span,
510                 ))
511             }
512             ast::ExprKind::Lit(l) => {
513                 Ok(tokenstream::TokenStream::token_alone(token::Literal(l.token_lit), l.span))
514             }
515             ast::ExprKind::Unary(ast::UnOp::Neg, e) => match &e.kind {
516                 ast::ExprKind::Lit(l) => match l.token_lit {
517                     token::Lit { kind: token::Integer | token::Float, .. } => {
518                         Ok(Self::TokenStream::from_iter([
519                             // FIXME: The span of the `-` token is lost when
520                             // parsing, so we cannot faithfully recover it here.
521                             tokenstream::TokenTree::token_alone(token::BinOp(token::Minus), e.span),
522                             tokenstream::TokenTree::token_alone(
523                                 token::Literal(l.token_lit),
524                                 l.span,
525                             ),
526                         ]))
527                     }
528                     _ => Err(()),
529                 },
530                 _ => Err(()),
531             },
532             _ => Err(()),
533         }
534     }
535
536     fn from_token_tree(
537         &mut self,
538         tree: TokenTree<Self::TokenStream, Self::Span, Self::Symbol>,
539     ) -> Self::TokenStream {
540         (tree, &mut *self).to_internal()
541     }
542
543     fn concat_trees(
544         &mut self,
545         base: Option<Self::TokenStream>,
546         trees: Vec<TokenTree<Self::TokenStream, Self::Span, Self::Symbol>>,
547     ) -> Self::TokenStream {
548         let mut builder = tokenstream::TokenStreamBuilder::new();
549         if let Some(base) = base {
550             builder.push(base);
551         }
552         for tree in trees {
553             builder.push((tree, &mut *self).to_internal());
554         }
555         builder.build()
556     }
557
558     fn concat_streams(
559         &mut self,
560         base: Option<Self::TokenStream>,
561         streams: Vec<Self::TokenStream>,
562     ) -> Self::TokenStream {
563         let mut builder = tokenstream::TokenStreamBuilder::new();
564         if let Some(base) = base {
565             builder.push(base);
566         }
567         for stream in streams {
568             builder.push(stream);
569         }
570         builder.build()
571     }
572
573     fn into_trees(
574         &mut self,
575         stream: Self::TokenStream,
576     ) -> Vec<TokenTree<Self::TokenStream, Self::Span, Self::Symbol>> {
577         FromInternal::from_internal((stream, self))
578     }
579 }
580
581 impl server::SourceFile for Rustc<'_, '_> {
582     fn eq(&mut self, file1: &Self::SourceFile, file2: &Self::SourceFile) -> bool {
583         Lrc::ptr_eq(file1, file2)
584     }
585
586     fn path(&mut self, file: &Self::SourceFile) -> String {
587         match file.name {
588             FileName::Real(ref name) => name
589                 .local_path()
590                 .expect("attempting to get a file path in an imported file in `proc_macro::SourceFile::path`")
591                 .to_str()
592                 .expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
593                 .to_string(),
594             _ => file.name.prefer_local().to_string(),
595         }
596     }
597
598     fn is_real(&mut self, file: &Self::SourceFile) -> bool {
599         file.is_real_file()
600     }
601 }
602
603 impl server::Span for Rustc<'_, '_> {
604     fn debug(&mut self, span: Self::Span) -> String {
605         if self.ecx.ecfg.span_debug {
606             format!("{:?}", span)
607         } else {
608             format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
609         }
610     }
611
612     fn source_file(&mut self, span: Self::Span) -> Self::SourceFile {
613         self.sess().source_map().lookup_char_pos(span.lo()).file
614     }
615
616     fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
617         span.parent_callsite()
618     }
619
620     fn source(&mut self, span: Self::Span) -> Self::Span {
621         span.source_callsite()
622     }
623
624     fn start(&mut self, span: Self::Span) -> LineColumn {
625         let loc = self.sess().source_map().lookup_char_pos(span.lo());
626         LineColumn { line: loc.line, column: loc.col.to_usize() }
627     }
628
629     fn end(&mut self, span: Self::Span) -> LineColumn {
630         let loc = self.sess().source_map().lookup_char_pos(span.hi());
631         LineColumn { line: loc.line, column: loc.col.to_usize() }
632     }
633
634     fn before(&mut self, span: Self::Span) -> Self::Span {
635         span.shrink_to_lo()
636     }
637
638     fn after(&mut self, span: Self::Span) -> Self::Span {
639         span.shrink_to_hi()
640     }
641
642     fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
643         let self_loc = self.sess().source_map().lookup_char_pos(first.lo());
644         let other_loc = self.sess().source_map().lookup_char_pos(second.lo());
645
646         if self_loc.file.name != other_loc.file.name {
647             return None;
648         }
649
650         Some(first.to(second))
651     }
652
653     fn subspan(
654         &mut self,
655         span: Self::Span,
656         start: Bound<usize>,
657         end: Bound<usize>,
658     ) -> Option<Self::Span> {
659         let length = span.hi().to_usize() - span.lo().to_usize();
660
661         let start = match start {
662             Bound::Included(lo) => lo,
663             Bound::Excluded(lo) => lo.checked_add(1)?,
664             Bound::Unbounded => 0,
665         };
666
667         let end = match end {
668             Bound::Included(hi) => hi.checked_add(1)?,
669             Bound::Excluded(hi) => hi,
670             Bound::Unbounded => length,
671         };
672
673         // Bounds check the values, preventing addition overflow and OOB spans.
674         if start > u32::MAX as usize
675             || end > u32::MAX as usize
676             || (u32::MAX - start as u32) < span.lo().to_u32()
677             || (u32::MAX - end as u32) < span.lo().to_u32()
678             || start >= end
679             || end > length
680         {
681             return None;
682         }
683
684         let new_lo = span.lo() + BytePos::from_usize(start);
685         let new_hi = span.lo() + BytePos::from_usize(end);
686         Some(span.with_lo(new_lo).with_hi(new_hi))
687     }
688
689     fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span {
690         span.with_ctxt(at.ctxt())
691     }
692
693     fn source_text(&mut self, span: Self::Span) -> Option<String> {
694         self.sess().source_map().span_to_snippet(span).ok()
695     }
696     /// Saves the provided span into the metadata of
697     /// *the crate we are currently compiling*, which must
698     /// be a proc-macro crate. This id can be passed to
699     /// `recover_proc_macro_span` when our current crate
700     /// is *run* as a proc-macro.
701     ///
702     /// Let's suppose that we have two crates - `my_client`
703     /// and `my_proc_macro`. The `my_proc_macro` crate
704     /// contains a procedural macro `my_macro`, which
705     /// is implemented as: `quote! { "hello" }`
706     ///
707     /// When we *compile* `my_proc_macro`, we will execute
708     /// the `quote` proc-macro. This will save the span of
709     /// "hello" into the metadata of `my_proc_macro`. As a result,
710     /// the body of `my_proc_macro` (after expansion) will end
711     /// up containing a call that looks like this:
712     /// `proc_macro::Ident::new("hello", proc_macro::Span::recover_proc_macro_span(0))`
713     ///
714     /// where `0` is the id returned by this function.
715     /// When `my_proc_macro` *executes* (during the compilation of `my_client`),
716     /// the call to `recover_proc_macro_span` will load the corresponding
717     /// span from the metadata of `my_proc_macro` (which we have access to,
718     /// since we've loaded `my_proc_macro` from disk in order to execute it).
719     /// In this way, we have obtained a span pointing into `my_proc_macro`
720     fn save_span(&mut self, span: Self::Span) -> usize {
721         self.sess().save_proc_macro_span(span)
722     }
723
724     fn recover_proc_macro_span(&mut self, id: usize) -> Self::Span {
725         let (resolver, krate, def_site) = (&*self.ecx.resolver, self.krate, self.def_site);
726         *self.rebased_spans.entry(id).or_insert_with(|| {
727             // FIXME: `SyntaxContext` for spans from proc macro crates is lost during encoding,
728             // replace it with a def-site context until we are encoding it properly.
729             resolver.get_proc_macro_quoted_span(krate, id).with_ctxt(def_site.ctxt())
730         })
731     }
732 }
733
734 impl server::Symbol for Rustc<'_, '_> {
735     fn normalize_and_validate_ident(&mut self, string: &str) -> Result<Self::Symbol, ()> {
736         let sym = nfc_normalize(string);
737         if rustc_lexer::is_ident(sym.as_str()) { Ok(sym) } else { Err(()) }
738     }
739 }
740
741 impl server::Server for Rustc<'_, '_> {
742     fn globals(&mut self) -> ExpnGlobals<Self::Span> {
743         ExpnGlobals {
744             def_site: self.def_site,
745             call_site: self.call_site,
746             mixed_site: self.mixed_site,
747         }
748     }
749
750     fn intern_symbol(string: &str) -> Self::Symbol {
751         Symbol::intern(string)
752     }
753
754     fn with_symbol_string(symbol: &Self::Symbol, f: impl FnOnce(&str)) {
755         f(&symbol.as_str())
756     }
757 }