]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_span/src/hygiene.rs
Rollup merge of #85663 - fee1-dead:document-arc-from, r=m-ou-se
[rust.git] / compiler / rustc_span / src / hygiene.rs
1 //! Machinery for hygienic macros.
2 //!
3 //! Inspired by Matthew Flatt et al., “Macros That Work Together: Compile-Time Bindings, Partial
4 //! Expansion, and Definition Contexts,” *Journal of Functional Programming* 22, no. 2
5 //! (March 1, 2012): 181–216, <https://doi.org/10.1017/S0956796812000093>.
6
7 // Hygiene data is stored in a global variable and accessed via TLS, which
8 // means that accesses are somewhat expensive. (`HygieneData::with`
9 // encapsulates a single access.) Therefore, on hot code paths it is worth
10 // ensuring that multiple HygieneData accesses are combined into a single
11 // `HygieneData::with`.
12 //
13 // This explains why `HygieneData`, `SyntaxContext` and `ExpnId` have interfaces
14 // with a certain amount of redundancy in them. For example,
15 // `SyntaxContext::outer_expn_data` combines `SyntaxContext::outer` and
16 // `ExpnId::expn_data` so that two `HygieneData` accesses can be performed within
17 // a single `HygieneData::with` call.
18 //
19 // It also explains why many functions appear in `HygieneData` and again in
20 // `SyntaxContext` or `ExpnId`. For example, `HygieneData::outer` and
21 // `SyntaxContext::outer` do the same thing, but the former is for use within a
22 // `HygieneData::with` call while the latter is for use outside such a call.
23 // When modifying this file it is important to understand this distinction,
24 // because getting it wrong can lead to nested `HygieneData::with` calls that
25 // trigger runtime aborts. (Fortunately these are obvious and easy to fix.)
26
27 use crate::edition::Edition;
28 use crate::symbol::{kw, sym, Symbol};
29 use crate::SESSION_GLOBALS;
30 use crate::{BytePos, CachingSourceMapView, ExpnIdCache, SourceFile, Span, DUMMY_SP};
31
32 use crate::def_id::{CrateNum, DefId, DefPathHash, CRATE_DEF_INDEX, LOCAL_CRATE};
33 use rustc_data_structures::fingerprint::Fingerprint;
34 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
35 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
36 use rustc_data_structures::sync::{Lock, Lrc};
37 use rustc_macros::HashStable_Generic;
38 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
39 use std::fmt;
40 use std::hash::Hash;
41 use std::thread::LocalKey;
42 use tracing::*;
43
44 /// A `SyntaxContext` represents a chain of pairs `(ExpnId, Transparency)` named "marks".
45 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
46 pub struct SyntaxContext(u32);
47
48 #[derive(Debug, Encodable, Decodable, Clone)]
49 pub struct SyntaxContextData {
50     outer_expn: ExpnId,
51     outer_transparency: Transparency,
52     parent: SyntaxContext,
53     /// This context, but with all transparent and semi-transparent expansions filtered away.
54     opaque: SyntaxContext,
55     /// This context, but with all transparent expansions filtered away.
56     opaque_and_semitransparent: SyntaxContext,
57     /// Name of the crate to which `$crate` with this context would resolve.
58     dollar_crate_name: Symbol,
59 }
60
61 /// A unique ID associated with a macro invocation and expansion.
62 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
63 pub struct ExpnId(u32);
64
65 /// A property of a macro expansion that determines how identifiers
66 /// produced by that expansion are resolved.
67 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Hash, Debug, Encodable, Decodable)]
68 #[derive(HashStable_Generic)]
69 pub enum Transparency {
70     /// Identifier produced by a transparent expansion is always resolved at call-site.
71     /// Call-site spans in procedural macros, hygiene opt-out in `macro` should use this.
72     Transparent,
73     /// Identifier produced by a semi-transparent expansion may be resolved
74     /// either at call-site or at definition-site.
75     /// If it's a local variable, label or `$crate` then it's resolved at def-site.
76     /// Otherwise it's resolved at call-site.
77     /// `macro_rules` macros behave like this, built-in macros currently behave like this too,
78     /// but that's an implementation detail.
79     SemiTransparent,
80     /// Identifier produced by an opaque expansion is always resolved at definition-site.
81     /// Def-site spans in procedural macros, identifiers from `macro` by default use this.
82     Opaque,
83 }
84
85 impl ExpnId {
86     pub fn fresh(expn_data: Option<ExpnData>) -> Self {
87         let has_data = expn_data.is_some();
88         let expn_id = HygieneData::with(|data| data.fresh_expn(expn_data));
89         if has_data {
90             update_disambiguator(expn_id);
91         }
92         expn_id
93     }
94
95     /// The ID of the theoretical expansion that generates freshly parsed, unexpanded AST.
96     #[inline]
97     pub fn root() -> Self {
98         ExpnId(0)
99     }
100
101     #[inline]
102     pub fn as_u32(self) -> u32 {
103         self.0
104     }
105
106     #[inline]
107     pub fn from_u32(raw: u32) -> ExpnId {
108         ExpnId(raw)
109     }
110
111     #[inline]
112     pub fn expn_data(self) -> ExpnData {
113         HygieneData::with(|data| data.expn_data(self).clone())
114     }
115
116     #[inline]
117     pub fn set_expn_data(self, mut expn_data: ExpnData) {
118         HygieneData::with(|data| {
119             let old_expn_data = &mut data.expn_data[self.0 as usize];
120             assert!(old_expn_data.is_none(), "expansion data is reset for an expansion ID");
121             assert_eq!(expn_data.orig_id, None);
122             expn_data.orig_id = Some(self.as_u32());
123             *old_expn_data = Some(expn_data);
124         });
125         update_disambiguator(self)
126     }
127
128     pub fn is_descendant_of(self, ancestor: ExpnId) -> bool {
129         HygieneData::with(|data| data.is_descendant_of(self, ancestor))
130     }
131
132     /// `expn_id.outer_expn_is_descendant_of(ctxt)` is equivalent to but faster than
133     /// `expn_id.is_descendant_of(ctxt.outer_expn())`.
134     pub fn outer_expn_is_descendant_of(self, ctxt: SyntaxContext) -> bool {
135         HygieneData::with(|data| data.is_descendant_of(self, data.outer_expn(ctxt)))
136     }
137
138     /// Returns span for the macro which originally caused this expansion to happen.
139     ///
140     /// Stops backtracing at include! boundary.
141     pub fn expansion_cause(mut self) -> Option<Span> {
142         let mut last_macro = None;
143         loop {
144             let expn_data = self.expn_data();
145             // Stop going up the backtrace once include! is encountered
146             if expn_data.is_root()
147                 || matches!(
148                     expn_data.kind,
149                     ExpnKind::Macro { kind: MacroKind::Bang, name: sym::include, proc_macro: _ }
150                 )
151             {
152                 break;
153             }
154             self = expn_data.call_site.ctxt().outer_expn();
155             last_macro = Some(expn_data.call_site);
156         }
157         last_macro
158     }
159 }
160
161 #[derive(Debug)]
162 pub struct HygieneData {
163     /// Each expansion should have an associated expansion data, but sometimes there's a delay
164     /// between creation of an expansion ID and obtaining its data (e.g. macros are collected
165     /// first and then resolved later), so we use an `Option` here.
166     expn_data: Vec<Option<ExpnData>>,
167     syntax_context_data: Vec<SyntaxContextData>,
168     syntax_context_map: FxHashMap<(SyntaxContext, ExpnId, Transparency), SyntaxContext>,
169     /// Maps the `Fingerprint` of an `ExpnData` to the next disambiguator value.
170     /// This is used by `update_disambiguator` to keep track of which `ExpnData`s
171     /// would have collisions without a disambiguator.
172     /// The keys of this map are always computed with `ExpnData.disambiguator`
173     /// set to 0.
174     expn_data_disambiguators: FxHashMap<Fingerprint, u32>,
175 }
176
177 impl HygieneData {
178     crate fn new(edition: Edition) -> Self {
179         let mut root_data = ExpnData::default(
180             ExpnKind::Root,
181             DUMMY_SP,
182             edition,
183             Some(DefId::local(CRATE_DEF_INDEX)),
184         );
185         root_data.orig_id = Some(0);
186
187         HygieneData {
188             expn_data: vec![Some(root_data)],
189             syntax_context_data: vec![SyntaxContextData {
190                 outer_expn: ExpnId::root(),
191                 outer_transparency: Transparency::Opaque,
192                 parent: SyntaxContext(0),
193                 opaque: SyntaxContext(0),
194                 opaque_and_semitransparent: SyntaxContext(0),
195                 dollar_crate_name: kw::DollarCrate,
196             }],
197             syntax_context_map: FxHashMap::default(),
198             expn_data_disambiguators: FxHashMap::default(),
199         }
200     }
201
202     pub fn with<T, F: FnOnce(&mut HygieneData) -> T>(f: F) -> T {
203         SESSION_GLOBALS.with(|session_globals| f(&mut *session_globals.hygiene_data.borrow_mut()))
204     }
205
206     fn fresh_expn(&mut self, mut expn_data: Option<ExpnData>) -> ExpnId {
207         let raw_id = self.expn_data.len() as u32;
208         if let Some(data) = expn_data.as_mut() {
209             assert_eq!(data.orig_id, None);
210             data.orig_id = Some(raw_id);
211         }
212         self.expn_data.push(expn_data);
213         ExpnId(raw_id)
214     }
215
216     fn expn_data(&self, expn_id: ExpnId) -> &ExpnData {
217         self.expn_data[expn_id.0 as usize].as_ref().expect("no expansion data for an expansion ID")
218     }
219
220     fn is_descendant_of(&self, mut expn_id: ExpnId, ancestor: ExpnId) -> bool {
221         while expn_id != ancestor {
222             if expn_id == ExpnId::root() {
223                 return false;
224             }
225             expn_id = self.expn_data(expn_id).parent;
226         }
227         true
228     }
229
230     fn normalize_to_macros_2_0(&self, ctxt: SyntaxContext) -> SyntaxContext {
231         self.syntax_context_data[ctxt.0 as usize].opaque
232     }
233
234     fn normalize_to_macro_rules(&self, ctxt: SyntaxContext) -> SyntaxContext {
235         self.syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent
236     }
237
238     fn outer_expn(&self, ctxt: SyntaxContext) -> ExpnId {
239         self.syntax_context_data[ctxt.0 as usize].outer_expn
240     }
241
242     fn outer_mark(&self, ctxt: SyntaxContext) -> (ExpnId, Transparency) {
243         let data = &self.syntax_context_data[ctxt.0 as usize];
244         (data.outer_expn, data.outer_transparency)
245     }
246
247     fn parent_ctxt(&self, ctxt: SyntaxContext) -> SyntaxContext {
248         self.syntax_context_data[ctxt.0 as usize].parent
249     }
250
251     fn remove_mark(&self, ctxt: &mut SyntaxContext) -> (ExpnId, Transparency) {
252         let outer_mark = self.outer_mark(*ctxt);
253         *ctxt = self.parent_ctxt(*ctxt);
254         outer_mark
255     }
256
257     fn marks(&self, mut ctxt: SyntaxContext) -> Vec<(ExpnId, Transparency)> {
258         let mut marks = Vec::new();
259         while ctxt != SyntaxContext::root() {
260             debug!("marks: getting parent of {:?}", ctxt);
261             marks.push(self.outer_mark(ctxt));
262             ctxt = self.parent_ctxt(ctxt);
263         }
264         marks.reverse();
265         marks
266     }
267
268     fn walk_chain(&self, mut span: Span, to: SyntaxContext) -> Span {
269         debug!("walk_chain({:?}, {:?})", span, to);
270         debug!("walk_chain: span ctxt = {:?}", span.ctxt());
271         while span.from_expansion() && span.ctxt() != to {
272             let outer_expn = self.outer_expn(span.ctxt());
273             debug!("walk_chain({:?}): outer_expn={:?}", span, outer_expn);
274             let expn_data = self.expn_data(outer_expn);
275             debug!("walk_chain({:?}): expn_data={:?}", span, expn_data);
276             span = expn_data.call_site;
277         }
278         span
279     }
280
281     fn adjust(&self, ctxt: &mut SyntaxContext, expn_id: ExpnId) -> Option<ExpnId> {
282         let mut scope = None;
283         while !self.is_descendant_of(expn_id, self.outer_expn(*ctxt)) {
284             scope = Some(self.remove_mark(ctxt).0);
285         }
286         scope
287     }
288
289     fn apply_mark(
290         &mut self,
291         ctxt: SyntaxContext,
292         expn_id: ExpnId,
293         transparency: Transparency,
294     ) -> SyntaxContext {
295         assert_ne!(expn_id, ExpnId::root());
296         if transparency == Transparency::Opaque {
297             return self.apply_mark_internal(ctxt, expn_id, transparency);
298         }
299
300         let call_site_ctxt = self.expn_data(expn_id).call_site.ctxt();
301         let mut call_site_ctxt = if transparency == Transparency::SemiTransparent {
302             self.normalize_to_macros_2_0(call_site_ctxt)
303         } else {
304             self.normalize_to_macro_rules(call_site_ctxt)
305         };
306
307         if call_site_ctxt == SyntaxContext::root() {
308             return self.apply_mark_internal(ctxt, expn_id, transparency);
309         }
310
311         // Otherwise, `expn_id` is a macros 1.0 definition and the call site is in a
312         // macros 2.0 expansion, i.e., a macros 1.0 invocation is in a macros 2.0 definition.
313         //
314         // In this case, the tokens from the macros 1.0 definition inherit the hygiene
315         // at their invocation. That is, we pretend that the macros 1.0 definition
316         // was defined at its invocation (i.e., inside the macros 2.0 definition)
317         // so that the macros 2.0 definition remains hygienic.
318         //
319         // See the example at `test/ui/hygiene/legacy_interaction.rs`.
320         for (expn_id, transparency) in self.marks(ctxt) {
321             call_site_ctxt = self.apply_mark_internal(call_site_ctxt, expn_id, transparency);
322         }
323         self.apply_mark_internal(call_site_ctxt, expn_id, transparency)
324     }
325
326     fn apply_mark_internal(
327         &mut self,
328         ctxt: SyntaxContext,
329         expn_id: ExpnId,
330         transparency: Transparency,
331     ) -> SyntaxContext {
332         let syntax_context_data = &mut self.syntax_context_data;
333         let mut opaque = syntax_context_data[ctxt.0 as usize].opaque;
334         let mut opaque_and_semitransparent =
335             syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent;
336
337         if transparency >= Transparency::Opaque {
338             let parent = opaque;
339             opaque = *self
340                 .syntax_context_map
341                 .entry((parent, expn_id, transparency))
342                 .or_insert_with(|| {
343                     let new_opaque = SyntaxContext(syntax_context_data.len() as u32);
344                     syntax_context_data.push(SyntaxContextData {
345                         outer_expn: expn_id,
346                         outer_transparency: transparency,
347                         parent,
348                         opaque: new_opaque,
349                         opaque_and_semitransparent: new_opaque,
350                         dollar_crate_name: kw::DollarCrate,
351                     });
352                     new_opaque
353                 });
354         }
355
356         if transparency >= Transparency::SemiTransparent {
357             let parent = opaque_and_semitransparent;
358             opaque_and_semitransparent = *self
359                 .syntax_context_map
360                 .entry((parent, expn_id, transparency))
361                 .or_insert_with(|| {
362                     let new_opaque_and_semitransparent =
363                         SyntaxContext(syntax_context_data.len() as u32);
364                     syntax_context_data.push(SyntaxContextData {
365                         outer_expn: expn_id,
366                         outer_transparency: transparency,
367                         parent,
368                         opaque,
369                         opaque_and_semitransparent: new_opaque_and_semitransparent,
370                         dollar_crate_name: kw::DollarCrate,
371                     });
372                     new_opaque_and_semitransparent
373                 });
374         }
375
376         let parent = ctxt;
377         *self.syntax_context_map.entry((parent, expn_id, transparency)).or_insert_with(|| {
378             let new_opaque_and_semitransparent_and_transparent =
379                 SyntaxContext(syntax_context_data.len() as u32);
380             syntax_context_data.push(SyntaxContextData {
381                 outer_expn: expn_id,
382                 outer_transparency: transparency,
383                 parent,
384                 opaque,
385                 opaque_and_semitransparent,
386                 dollar_crate_name: kw::DollarCrate,
387             });
388             new_opaque_and_semitransparent_and_transparent
389         })
390     }
391 }
392
393 pub fn clear_syntax_context_map() {
394     HygieneData::with(|data| data.syntax_context_map = FxHashMap::default());
395 }
396
397 pub fn walk_chain(span: Span, to: SyntaxContext) -> Span {
398     HygieneData::with(|data| data.walk_chain(span, to))
399 }
400
401 pub fn update_dollar_crate_names(mut get_name: impl FnMut(SyntaxContext) -> Symbol) {
402     // The new contexts that need updating are at the end of the list and have `$crate` as a name.
403     let (len, to_update) = HygieneData::with(|data| {
404         (
405             data.syntax_context_data.len(),
406             data.syntax_context_data
407                 .iter()
408                 .rev()
409                 .take_while(|scdata| scdata.dollar_crate_name == kw::DollarCrate)
410                 .count(),
411         )
412     });
413     // The callback must be called from outside of the `HygieneData` lock,
414     // since it will try to acquire it too.
415     let range_to_update = len - to_update..len;
416     let names: Vec<_> =
417         range_to_update.clone().map(|idx| get_name(SyntaxContext::from_u32(idx as u32))).collect();
418     HygieneData::with(|data| {
419         range_to_update.zip(names).for_each(|(idx, name)| {
420             data.syntax_context_data[idx].dollar_crate_name = name;
421         })
422     })
423 }
424
425 pub fn debug_hygiene_data(verbose: bool) -> String {
426     HygieneData::with(|data| {
427         if verbose {
428             format!("{:#?}", data)
429         } else {
430             let mut s = String::from("");
431             s.push_str("Expansions:");
432             data.expn_data.iter().enumerate().for_each(|(id, expn_info)| {
433                 let expn_info = expn_info.as_ref().expect("no expansion data for an expansion ID");
434                 s.push_str(&format!(
435                     "\n{}: parent: {:?}, call_site_ctxt: {:?}, def_site_ctxt: {:?}, kind: {:?}",
436                     id,
437                     expn_info.parent,
438                     expn_info.call_site.ctxt(),
439                     expn_info.def_site.ctxt(),
440                     expn_info.kind,
441                 ));
442             });
443             s.push_str("\n\nSyntaxContexts:");
444             data.syntax_context_data.iter().enumerate().for_each(|(id, ctxt)| {
445                 s.push_str(&format!(
446                     "\n#{}: parent: {:?}, outer_mark: ({:?}, {:?})",
447                     id, ctxt.parent, ctxt.outer_expn, ctxt.outer_transparency,
448                 ));
449             });
450             s
451         }
452     })
453 }
454
455 impl SyntaxContext {
456     #[inline]
457     pub const fn root() -> Self {
458         SyntaxContext(0)
459     }
460
461     #[inline]
462     crate fn as_u32(self) -> u32 {
463         self.0
464     }
465
466     #[inline]
467     crate fn from_u32(raw: u32) -> SyntaxContext {
468         SyntaxContext(raw)
469     }
470
471     /// Extend a syntax context with a given expansion and transparency.
472     crate fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> SyntaxContext {
473         HygieneData::with(|data| data.apply_mark(self, expn_id, transparency))
474     }
475
476     /// Pulls a single mark off of the syntax context. This effectively moves the
477     /// context up one macro definition level. That is, if we have a nested macro
478     /// definition as follows:
479     ///
480     /// ```rust
481     /// macro_rules! f {
482     ///    macro_rules! g {
483     ///        ...
484     ///    }
485     /// }
486     /// ```
487     ///
488     /// and we have a SyntaxContext that is referring to something declared by an invocation
489     /// of g (call it g1), calling remove_mark will result in the SyntaxContext for the
490     /// invocation of f that created g1.
491     /// Returns the mark that was removed.
492     pub fn remove_mark(&mut self) -> ExpnId {
493         HygieneData::with(|data| data.remove_mark(self).0)
494     }
495
496     pub fn marks(self) -> Vec<(ExpnId, Transparency)> {
497         HygieneData::with(|data| data.marks(self))
498     }
499
500     /// Adjust this context for resolution in a scope created by the given expansion.
501     /// For example, consider the following three resolutions of `f`:
502     ///
503     /// ```rust
504     /// mod foo { pub fn f() {} } // `f`'s `SyntaxContext` is empty.
505     /// m!(f);
506     /// macro m($f:ident) {
507     ///     mod bar {
508     ///         pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
509     ///         pub fn $f() {} // `$f`'s `SyntaxContext` is empty.
510     ///     }
511     ///     foo::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
512     ///     //^ Since `mod foo` is outside this expansion, `adjust` removes the mark from `f`,
513     ///     //| and it resolves to `::foo::f`.
514     ///     bar::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
515     ///     //^ Since `mod bar` not outside this expansion, `adjust` does not change `f`,
516     ///     //| and it resolves to `::bar::f`.
517     ///     bar::$f(); // `f`'s `SyntaxContext` is empty.
518     ///     //^ Since `mod bar` is not outside this expansion, `adjust` does not change `$f`,
519     ///     //| and it resolves to `::bar::$f`.
520     /// }
521     /// ```
522     /// This returns the expansion whose definition scope we use to privacy check the resolution,
523     /// or `None` if we privacy check as usual (i.e., not w.r.t. a macro definition scope).
524     pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
525         HygieneData::with(|data| data.adjust(self, expn_id))
526     }
527
528     /// Like `SyntaxContext::adjust`, but also normalizes `self` to macros 2.0.
529     pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
530         HygieneData::with(|data| {
531             *self = data.normalize_to_macros_2_0(*self);
532             data.adjust(self, expn_id)
533         })
534     }
535
536     /// Adjust this context for resolution in a scope created by the given expansion
537     /// via a glob import with the given `SyntaxContext`.
538     /// For example:
539     ///
540     /// ```rust
541     /// m!(f);
542     /// macro m($i:ident) {
543     ///     mod foo {
544     ///         pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
545     ///         pub fn $i() {} // `$i`'s `SyntaxContext` is empty.
546     ///     }
547     ///     n(f);
548     ///     macro n($j:ident) {
549     ///         use foo::*;
550     ///         f(); // `f`'s `SyntaxContext` has a mark from `m` and a mark from `n`
551     ///         //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::f`.
552     ///         $i(); // `$i`'s `SyntaxContext` has a mark from `n`
553     ///         //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::$i`.
554     ///         $j(); // `$j`'s `SyntaxContext` has a mark from `m`
555     ///         //^ This cannot be glob-adjusted, so this is a resolution error.
556     ///     }
557     /// }
558     /// ```
559     /// This returns `None` if the context cannot be glob-adjusted.
560     /// Otherwise, it returns the scope to use when privacy checking (see `adjust` for details).
561     pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
562         HygieneData::with(|data| {
563             let mut scope = None;
564             let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
565             while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
566                 scope = Some(data.remove_mark(&mut glob_ctxt).0);
567                 if data.remove_mark(self).0 != scope.unwrap() {
568                     return None;
569                 }
570             }
571             if data.adjust(self, expn_id).is_some() {
572                 return None;
573             }
574             Some(scope)
575         })
576     }
577
578     /// Undo `glob_adjust` if possible:
579     ///
580     /// ```rust
581     /// if let Some(privacy_checking_scope) = self.reverse_glob_adjust(expansion, glob_ctxt) {
582     ///     assert!(self.glob_adjust(expansion, glob_ctxt) == Some(privacy_checking_scope));
583     /// }
584     /// ```
585     pub fn reverse_glob_adjust(
586         &mut self,
587         expn_id: ExpnId,
588         glob_span: Span,
589     ) -> Option<Option<ExpnId>> {
590         HygieneData::with(|data| {
591             if data.adjust(self, expn_id).is_some() {
592                 return None;
593             }
594
595             let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
596             let mut marks = Vec::new();
597             while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
598                 marks.push(data.remove_mark(&mut glob_ctxt));
599             }
600
601             let scope = marks.last().map(|mark| mark.0);
602             while let Some((expn_id, transparency)) = marks.pop() {
603                 *self = data.apply_mark(*self, expn_id, transparency);
604             }
605             Some(scope)
606         })
607     }
608
609     pub fn hygienic_eq(self, other: SyntaxContext, expn_id: ExpnId) -> bool {
610         HygieneData::with(|data| {
611             let mut self_normalized = data.normalize_to_macros_2_0(self);
612             data.adjust(&mut self_normalized, expn_id);
613             self_normalized == data.normalize_to_macros_2_0(other)
614         })
615     }
616
617     #[inline]
618     pub fn normalize_to_macros_2_0(self) -> SyntaxContext {
619         HygieneData::with(|data| data.normalize_to_macros_2_0(self))
620     }
621
622     #[inline]
623     pub fn normalize_to_macro_rules(self) -> SyntaxContext {
624         HygieneData::with(|data| data.normalize_to_macro_rules(self))
625     }
626
627     #[inline]
628     pub fn outer_expn(self) -> ExpnId {
629         HygieneData::with(|data| data.outer_expn(self))
630     }
631
632     /// `ctxt.outer_expn_data()` is equivalent to but faster than
633     /// `ctxt.outer_expn().expn_data()`.
634     #[inline]
635     pub fn outer_expn_data(self) -> ExpnData {
636         HygieneData::with(|data| data.expn_data(data.outer_expn(self)).clone())
637     }
638
639     #[inline]
640     pub fn outer_mark(self) -> (ExpnId, Transparency) {
641         HygieneData::with(|data| data.outer_mark(self))
642     }
643
644     pub fn dollar_crate_name(self) -> Symbol {
645         HygieneData::with(|data| data.syntax_context_data[self.0 as usize].dollar_crate_name)
646     }
647
648     pub fn edition(self) -> Edition {
649         self.outer_expn_data().edition
650     }
651 }
652
653 impl fmt::Debug for SyntaxContext {
654     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
655         write!(f, "#{}", self.0)
656     }
657 }
658
659 impl Span {
660     /// Creates a fresh expansion with given properties.
661     /// Expansions are normally created by macros, but in some cases expansions are created for
662     /// other compiler-generated code to set per-span properties like allowed unstable features.
663     /// The returned span belongs to the created expansion and has the new properties,
664     /// but its location is inherited from the current span.
665     pub fn fresh_expansion(self, expn_data: ExpnData) -> Span {
666         self.fresh_expansion_with_transparency(expn_data, Transparency::Transparent)
667     }
668
669     pub fn fresh_expansion_with_transparency(
670         self,
671         expn_data: ExpnData,
672         transparency: Transparency,
673     ) -> Span {
674         let expn_id = ExpnId::fresh(Some(expn_data));
675         HygieneData::with(|data| {
676             self.with_ctxt(data.apply_mark(SyntaxContext::root(), expn_id, transparency))
677         })
678     }
679
680     /// Reuses the span but adds information like the kind of the desugaring and features that are
681     /// allowed inside this span.
682     pub fn mark_with_reason(
683         self,
684         allow_internal_unstable: Option<Lrc<[Symbol]>>,
685         reason: DesugaringKind,
686         edition: Edition,
687     ) -> Span {
688         self.fresh_expansion(ExpnData {
689             allow_internal_unstable,
690             ..ExpnData::default(ExpnKind::Desugaring(reason), self, edition, None)
691         })
692     }
693 }
694
695 /// A subset of properties from both macro definition and macro call available through global data.
696 /// Avoid using this if you have access to the original definition or call structures.
697 #[derive(Clone, Debug, Encodable, Decodable, HashStable_Generic)]
698 pub struct ExpnData {
699     // --- The part unique to each expansion.
700     /// The kind of this expansion - macro or compiler desugaring.
701     pub kind: ExpnKind,
702     /// The expansion that produced this expansion.
703     pub parent: ExpnId,
704     /// The location of the actual macro invocation or syntax sugar , e.g.
705     /// `let x = foo!();` or `if let Some(y) = x {}`
706     ///
707     /// This may recursively refer to other macro invocations, e.g., if
708     /// `foo!()` invoked `bar!()` internally, and there was an
709     /// expression inside `bar!`; the call_site of the expression in
710     /// the expansion would point to the `bar!` invocation; that
711     /// call_site span would have its own ExpnData, with the call_site
712     /// pointing to the `foo!` invocation.
713     pub call_site: Span,
714
715     // --- The part specific to the macro/desugaring definition.
716     // --- It may be reasonable to share this part between expansions with the same definition,
717     // --- but such sharing is known to bring some minor inconveniences without also bringing
718     // --- noticeable perf improvements (PR #62898).
719     /// The span of the macro definition (possibly dummy).
720     /// This span serves only informational purpose and is not used for resolution.
721     pub def_site: Span,
722     /// List of `#[unstable]`/feature-gated features that the macro is allowed to use
723     /// internally without forcing the whole crate to opt-in
724     /// to them.
725     pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
726     /// Whether the macro is allowed to use `unsafe` internally
727     /// even if the user crate has `#![forbid(unsafe_code)]`.
728     pub allow_internal_unsafe: bool,
729     /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`)
730     /// for a given macro.
731     pub local_inner_macros: bool,
732     /// Edition of the crate in which the macro is defined.
733     pub edition: Edition,
734     /// The `DefId` of the macro being invoked,
735     /// if this `ExpnData` corresponds to a macro invocation
736     pub macro_def_id: Option<DefId>,
737     /// The crate that originally created this `ExpnData`. During
738     /// metadata serialization, we only encode `ExpnData`s that were
739     /// created locally - when our serialized metadata is decoded,
740     /// foreign `ExpnId`s will have their `ExpnData` looked up
741     /// from the crate specified by `Crate
742     krate: CrateNum,
743     /// The raw that this `ExpnData` had in its original crate.
744     /// An `ExpnData` can be created before being assigned an `ExpnId`,
745     /// so this might be `None` until `set_expn_data` is called
746     // This is used only for serialization/deserialization purposes:
747     // two `ExpnData`s that differ only in their `orig_id` should
748     // be considered equivalent.
749     #[stable_hasher(ignore)]
750     orig_id: Option<u32>,
751
752     /// Used to force two `ExpnData`s to have different `Fingerprint`s.
753     /// Due to macro expansion, it's possible to end up with two `ExpnId`s
754     /// that have identical `ExpnData`s. This violates the contract of `HashStable`
755     /// - the two `ExpnId`s are not equal, but their `Fingerprint`s are equal
756     /// (since the numerical `ExpnId` value is not considered by the `HashStable`
757     /// implementation).
758     ///
759     /// The `disambiguator` field is set by `update_disambiguator` when two distinct
760     /// `ExpnId`s would end up with the same `Fingerprint`. Since `ExpnData` includes
761     /// a `krate` field, this value only needs to be unique within a single crate.
762     disambiguator: u32,
763 }
764
765 // These would require special handling of `orig_id`.
766 impl !PartialEq for ExpnData {}
767 impl !Hash for ExpnData {}
768
769 impl ExpnData {
770     pub fn new(
771         kind: ExpnKind,
772         parent: ExpnId,
773         call_site: Span,
774         def_site: Span,
775         allow_internal_unstable: Option<Lrc<[Symbol]>>,
776         allow_internal_unsafe: bool,
777         local_inner_macros: bool,
778         edition: Edition,
779         macro_def_id: Option<DefId>,
780     ) -> ExpnData {
781         ExpnData {
782             kind,
783             parent,
784             call_site,
785             def_site,
786             allow_internal_unstable,
787             allow_internal_unsafe,
788             local_inner_macros,
789             edition,
790             macro_def_id,
791             krate: LOCAL_CRATE,
792             orig_id: None,
793             disambiguator: 0,
794         }
795     }
796
797     /// Constructs expansion data with default properties.
798     pub fn default(
799         kind: ExpnKind,
800         call_site: Span,
801         edition: Edition,
802         macro_def_id: Option<DefId>,
803     ) -> ExpnData {
804         ExpnData {
805             kind,
806             parent: ExpnId::root(),
807             call_site,
808             def_site: DUMMY_SP,
809             allow_internal_unstable: None,
810             allow_internal_unsafe: false,
811             local_inner_macros: false,
812             edition,
813             macro_def_id,
814             krate: LOCAL_CRATE,
815             orig_id: None,
816             disambiguator: 0,
817         }
818     }
819
820     pub fn allow_unstable(
821         kind: ExpnKind,
822         call_site: Span,
823         edition: Edition,
824         allow_internal_unstable: Lrc<[Symbol]>,
825         macro_def_id: Option<DefId>,
826     ) -> ExpnData {
827         ExpnData {
828             allow_internal_unstable: Some(allow_internal_unstable),
829             ..ExpnData::default(kind, call_site, edition, macro_def_id)
830         }
831     }
832
833     #[inline]
834     pub fn is_root(&self) -> bool {
835         matches!(self.kind, ExpnKind::Root)
836     }
837 }
838
839 /// Expansion kind.
840 #[derive(Clone, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
841 pub enum ExpnKind {
842     /// No expansion, aka root expansion. Only `ExpnId::root()` has this kind.
843     Root,
844     /// Expansion produced by a macro.
845     Macro {
846         kind: MacroKind,
847         name: Symbol,
848         /// If `true`, this macro is a procedural macro. This
849         /// flag is only used for diagnostic purposes
850         proc_macro: bool,
851     },
852     /// Transform done by the compiler on the AST.
853     AstPass(AstPass),
854     /// Desugaring done by the compiler during HIR lowering.
855     Desugaring(DesugaringKind),
856     /// MIR inlining
857     Inlined,
858 }
859
860 impl ExpnKind {
861     pub fn descr(&self) -> String {
862         match *self {
863             ExpnKind::Root => kw::PathRoot.to_string(),
864             ExpnKind::Macro { kind, name, proc_macro: _ } => match kind {
865                 MacroKind::Bang => format!("{}!", name),
866                 MacroKind::Attr => format!("#[{}]", name),
867                 MacroKind::Derive => format!("#[derive({})]", name),
868             },
869             ExpnKind::AstPass(kind) => kind.descr().to_string(),
870             ExpnKind::Desugaring(kind) => format!("desugaring of {}", kind.descr()),
871             ExpnKind::Inlined => "inlined source".to_string(),
872         }
873     }
874 }
875
876 /// The kind of macro invocation or definition.
877 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
878 #[derive(HashStable_Generic)]
879 pub enum MacroKind {
880     /// A bang macro `foo!()`.
881     Bang,
882     /// An attribute macro `#[foo]`.
883     Attr,
884     /// A derive macro `#[derive(Foo)]`
885     Derive,
886 }
887
888 impl MacroKind {
889     pub fn descr(self) -> &'static str {
890         match self {
891             MacroKind::Bang => "macro",
892             MacroKind::Attr => "attribute macro",
893             MacroKind::Derive => "derive macro",
894         }
895     }
896
897     pub fn descr_expected(self) -> &'static str {
898         match self {
899             MacroKind::Attr => "attribute",
900             _ => self.descr(),
901         }
902     }
903
904     pub fn article(self) -> &'static str {
905         match self {
906             MacroKind::Attr => "an",
907             _ => "a",
908         }
909     }
910 }
911
912 /// The kind of AST transform.
913 #[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
914 pub enum AstPass {
915     StdImports,
916     TestHarness,
917     ProcMacroHarness,
918 }
919
920 impl AstPass {
921     fn descr(self) -> &'static str {
922         match self {
923             AstPass::StdImports => "standard library imports",
924             AstPass::TestHarness => "test harness",
925             AstPass::ProcMacroHarness => "proc macro harness",
926         }
927     }
928 }
929
930 /// The kind of compiler desugaring.
931 #[derive(Clone, Copy, PartialEq, Debug, Encodable, Decodable, HashStable_Generic)]
932 pub enum DesugaringKind {
933     /// We desugar `if c { i } else { e }` to `match $ExprKind::Use(c) { true => i, _ => e }`.
934     /// However, we do not want to blame `c` for unreachability but rather say that `i`
935     /// is unreachable. This desugaring kind allows us to avoid blaming `c`.
936     /// This also applies to `while` loops.
937     CondTemporary,
938     QuestionMark,
939     TryBlock,
940     /// Desugaring of an `impl Trait` in return type position
941     /// to an `type Foo = impl Trait;` and replacing the
942     /// `impl Trait` with `Foo`.
943     OpaqueTy,
944     Async,
945     Await,
946     ForLoop(ForLoopLoc),
947 }
948
949 /// A location in the desugaring of a `for` loop
950 #[derive(Clone, Copy, PartialEq, Debug, Encodable, Decodable, HashStable_Generic)]
951 pub enum ForLoopLoc {
952     Head,
953     IntoIter,
954 }
955
956 impl DesugaringKind {
957     /// The description wording should combine well with "desugaring of {}".
958     fn descr(self) -> &'static str {
959         match self {
960             DesugaringKind::CondTemporary => "`if` or `while` condition",
961             DesugaringKind::Async => "`async` block or function",
962             DesugaringKind::Await => "`await` expression",
963             DesugaringKind::QuestionMark => "operator `?`",
964             DesugaringKind::TryBlock => "`try` block",
965             DesugaringKind::OpaqueTy => "`impl Trait`",
966             DesugaringKind::ForLoop(_) => "`for` loop",
967         }
968     }
969 }
970
971 #[derive(Default)]
972 pub struct HygieneEncodeContext {
973     /// All `SyntaxContexts` for which we have written `SyntaxContextData` into crate metadata.
974     /// This is `None` after we finish encoding `SyntaxContexts`, to ensure
975     /// that we don't accidentally try to encode any more `SyntaxContexts`
976     serialized_ctxts: Lock<FxHashSet<SyntaxContext>>,
977     /// The `SyntaxContexts` that we have serialized (e.g. as a result of encoding `Spans`)
978     /// in the most recent 'round' of serializnig. Serializing `SyntaxContextData`
979     /// may cause us to serialize more `SyntaxContext`s, so serialize in a loop
980     /// until we reach a fixed point.
981     latest_ctxts: Lock<FxHashSet<SyntaxContext>>,
982
983     serialized_expns: Lock<FxHashSet<ExpnId>>,
984
985     latest_expns: Lock<FxHashSet<ExpnId>>,
986 }
987
988 impl HygieneEncodeContext {
989     pub fn encode<
990         T,
991         R,
992         F: FnMut(&mut T, u32, &SyntaxContextData) -> Result<(), R>,
993         G: FnMut(&mut T, u32, &ExpnData) -> Result<(), R>,
994     >(
995         &self,
996         encoder: &mut T,
997         mut encode_ctxt: F,
998         mut encode_expn: G,
999     ) -> Result<(), R> {
1000         // When we serialize a `SyntaxContextData`, we may end up serializing
1001         // a `SyntaxContext` that we haven't seen before
1002         while !self.latest_ctxts.lock().is_empty() || !self.latest_expns.lock().is_empty() {
1003             debug!(
1004                 "encode_hygiene: Serializing a round of {:?} SyntaxContextDatas: {:?}",
1005                 self.latest_ctxts.lock().len(),
1006                 self.latest_ctxts
1007             );
1008
1009             // Consume the current round of SyntaxContexts.
1010             // Drop the lock() temporary early
1011             let latest_ctxts = { std::mem::take(&mut *self.latest_ctxts.lock()) };
1012
1013             // It's fine to iterate over a HashMap, because the serialization
1014             // of the table that we insert data into doesn't depend on insertion
1015             // order
1016             for_all_ctxts_in(latest_ctxts.into_iter(), |(index, ctxt, data)| {
1017                 if self.serialized_ctxts.lock().insert(ctxt) {
1018                     encode_ctxt(encoder, index, data)?;
1019                 }
1020                 Ok(())
1021             })?;
1022
1023             let latest_expns = { std::mem::take(&mut *self.latest_expns.lock()) };
1024
1025             for_all_expns_in(latest_expns.into_iter(), |index, expn, data| {
1026                 if self.serialized_expns.lock().insert(expn) {
1027                     encode_expn(encoder, index, data)?;
1028                 }
1029                 Ok(())
1030             })?;
1031         }
1032         debug!("encode_hygiene: Done serializing SyntaxContextData");
1033         Ok(())
1034     }
1035 }
1036
1037 #[derive(Default)]
1038 /// Additional information used to assist in decoding hygiene data
1039 pub struct HygieneDecodeContext {
1040     // Maps serialized `SyntaxContext` ids to a `SyntaxContext` in the current
1041     // global `HygieneData`. When we deserialize a `SyntaxContext`, we need to create
1042     // a new id in the global `HygieneData`. This map tracks the ID we end up picking,
1043     // so that multiple occurrences of the same serialized id are decoded to the same
1044     // `SyntaxContext`
1045     remapped_ctxts: Lock<Vec<Option<SyntaxContext>>>,
1046     // The same as `remapepd_ctxts`, but for `ExpnId`s
1047     remapped_expns: Lock<Vec<Option<ExpnId>>>,
1048 }
1049
1050 pub fn decode_expn_id<
1051     'a,
1052     D: Decoder,
1053     F: FnOnce(&mut D, u32) -> Result<ExpnData, D::Error>,
1054     G: FnOnce(CrateNum) -> &'a HygieneDecodeContext,
1055 >(
1056     d: &mut D,
1057     mode: ExpnDataDecodeMode<'a, G>,
1058     decode_data: F,
1059 ) -> Result<ExpnId, D::Error> {
1060     let index = u32::decode(d)?;
1061     let context = match mode {
1062         ExpnDataDecodeMode::IncrComp(context) => context,
1063         ExpnDataDecodeMode::Metadata(get_context) => {
1064             let krate = CrateNum::decode(d)?;
1065             get_context(krate)
1066         }
1067     };
1068
1069     // Do this after decoding, so that we decode a `CrateNum`
1070     // if necessary
1071     if index == ExpnId::root().as_u32() {
1072         debug!("decode_expn_id: deserialized root");
1073         return Ok(ExpnId::root());
1074     }
1075
1076     let outer_expns = &context.remapped_expns;
1077
1078     // Ensure that the lock() temporary is dropped early
1079     {
1080         if let Some(expn_id) = outer_expns.lock().get(index as usize).copied().flatten() {
1081             return Ok(expn_id);
1082         }
1083     }
1084
1085     // Don't decode the data inside `HygieneData::with`, since we need to recursively decode
1086     // other ExpnIds
1087     let mut expn_data = decode_data(d, index)?;
1088
1089     let expn_id = HygieneData::with(|hygiene_data| {
1090         let expn_id = ExpnId(hygiene_data.expn_data.len() as u32);
1091
1092         // If we just deserialized an `ExpnData` owned by
1093         // the local crate, its `orig_id` will be stale,
1094         // so we need to update it to its own value.
1095         // This only happens when we deserialize the incremental cache,
1096         // since a crate will never decode its own metadata.
1097         if expn_data.krate == LOCAL_CRATE {
1098             expn_data.orig_id = Some(expn_id.0);
1099         }
1100
1101         hygiene_data.expn_data.push(Some(expn_data));
1102
1103         let mut expns = outer_expns.lock();
1104         let new_len = index as usize + 1;
1105         if expns.len() < new_len {
1106             expns.resize(new_len, None);
1107         }
1108         expns[index as usize] = Some(expn_id);
1109         drop(expns);
1110         expn_id
1111     });
1112     Ok(expn_id)
1113 }
1114
1115 // Decodes `SyntaxContext`, using the provided `HygieneDecodeContext`
1116 // to track which `SyntaxContext`s we have already decoded.
1117 // The provided closure will be invoked to deserialize a `SyntaxContextData`
1118 // if we haven't already seen the id of the `SyntaxContext` we are deserializing.
1119 pub fn decode_syntax_context<
1120     D: Decoder,
1121     F: FnOnce(&mut D, u32) -> Result<SyntaxContextData, D::Error>,
1122 >(
1123     d: &mut D,
1124     context: &HygieneDecodeContext,
1125     decode_data: F,
1126 ) -> Result<SyntaxContext, D::Error> {
1127     let raw_id: u32 = Decodable::decode(d)?;
1128     if raw_id == 0 {
1129         debug!("decode_syntax_context: deserialized root");
1130         // The root is special
1131         return Ok(SyntaxContext::root());
1132     }
1133
1134     let outer_ctxts = &context.remapped_ctxts;
1135
1136     // Ensure that the lock() temporary is dropped early
1137     {
1138         if let Some(ctxt) = outer_ctxts.lock().get(raw_id as usize).copied().flatten() {
1139             return Ok(ctxt);
1140         }
1141     }
1142
1143     // Allocate and store SyntaxContext id *before* calling the decoder function,
1144     // as the SyntaxContextData may reference itself.
1145     let new_ctxt = HygieneData::with(|hygiene_data| {
1146         let new_ctxt = SyntaxContext(hygiene_data.syntax_context_data.len() as u32);
1147         // Push a dummy SyntaxContextData to ensure that nobody else can get the
1148         // same ID as us. This will be overwritten after call `decode_Data`
1149         hygiene_data.syntax_context_data.push(SyntaxContextData {
1150             outer_expn: ExpnId::root(),
1151             outer_transparency: Transparency::Transparent,
1152             parent: SyntaxContext::root(),
1153             opaque: SyntaxContext::root(),
1154             opaque_and_semitransparent: SyntaxContext::root(),
1155             dollar_crate_name: kw::Empty,
1156         });
1157         let mut ctxts = outer_ctxts.lock();
1158         let new_len = raw_id as usize + 1;
1159         if ctxts.len() < new_len {
1160             ctxts.resize(new_len, None);
1161         }
1162         ctxts[raw_id as usize] = Some(new_ctxt);
1163         drop(ctxts);
1164         new_ctxt
1165     });
1166
1167     // Don't try to decode data while holding the lock, since we need to
1168     // be able to recursively decode a SyntaxContext
1169     let mut ctxt_data = decode_data(d, raw_id)?;
1170     // Reset `dollar_crate_name` so that it will be updated by `update_dollar_crate_names`
1171     // We don't care what the encoding crate set this to - we want to resolve it
1172     // from the perspective of the current compilation session
1173     ctxt_data.dollar_crate_name = kw::DollarCrate;
1174
1175     // Overwrite the dummy data with our decoded SyntaxContextData
1176     HygieneData::with(|hygiene_data| {
1177         let dummy = std::mem::replace(
1178             &mut hygiene_data.syntax_context_data[new_ctxt.as_u32() as usize],
1179             ctxt_data,
1180         );
1181         // Make sure nothing weird happening while `decode_data` was running
1182         assert_eq!(dummy.dollar_crate_name, kw::Empty);
1183     });
1184
1185     Ok(new_ctxt)
1186 }
1187
1188 fn for_all_ctxts_in<E, F: FnMut((u32, SyntaxContext, &SyntaxContextData)) -> Result<(), E>>(
1189     ctxts: impl Iterator<Item = SyntaxContext>,
1190     mut f: F,
1191 ) -> Result<(), E> {
1192     let all_data: Vec<_> = HygieneData::with(|data| {
1193         ctxts.map(|ctxt| (ctxt, data.syntax_context_data[ctxt.0 as usize].clone())).collect()
1194     });
1195     for (ctxt, data) in all_data.into_iter() {
1196         f((ctxt.0, ctxt, &data))?;
1197     }
1198     Ok(())
1199 }
1200
1201 fn for_all_expns_in<E, F: FnMut(u32, ExpnId, &ExpnData) -> Result<(), E>>(
1202     expns: impl Iterator<Item = ExpnId>,
1203     mut f: F,
1204 ) -> Result<(), E> {
1205     let all_data: Vec<_> = HygieneData::with(|data| {
1206         expns.map(|expn| (expn, data.expn_data[expn.0 as usize].clone())).collect()
1207     });
1208     for (expn, data) in all_data.into_iter() {
1209         f(expn.0, expn, &data.unwrap_or_else(|| panic!("Missing data for {:?}", expn)))?;
1210     }
1211     Ok(())
1212 }
1213
1214 impl<E: Encoder> Encodable<E> for ExpnId {
1215     default fn encode(&self, _: &mut E) -> Result<(), E::Error> {
1216         panic!("cannot encode `ExpnId` with `{}`", std::any::type_name::<E>());
1217     }
1218 }
1219
1220 impl<D: Decoder> Decodable<D> for ExpnId {
1221     default fn decode(_: &mut D) -> Result<Self, D::Error> {
1222         panic!("cannot decode `ExpnId` with `{}`", std::any::type_name::<D>());
1223     }
1224 }
1225
1226 pub fn raw_encode_syntax_context<E: Encoder>(
1227     ctxt: SyntaxContext,
1228     context: &HygieneEncodeContext,
1229     e: &mut E,
1230 ) -> Result<(), E::Error> {
1231     if !context.serialized_ctxts.lock().contains(&ctxt) {
1232         context.latest_ctxts.lock().insert(ctxt);
1233     }
1234     ctxt.0.encode(e)
1235 }
1236
1237 pub fn raw_encode_expn_id<E: Encoder>(
1238     expn: ExpnId,
1239     context: &HygieneEncodeContext,
1240     mode: ExpnDataEncodeMode,
1241     e: &mut E,
1242 ) -> Result<(), E::Error> {
1243     // Record the fact that we need to serialize the corresponding
1244     // `ExpnData`
1245     let needs_data = || {
1246         if !context.serialized_expns.lock().contains(&expn) {
1247             context.latest_expns.lock().insert(expn);
1248         }
1249     };
1250
1251     match mode {
1252         ExpnDataEncodeMode::IncrComp => {
1253             // Always serialize the `ExpnData` in incr comp mode
1254             needs_data();
1255             expn.0.encode(e)
1256         }
1257         ExpnDataEncodeMode::Metadata => {
1258             let data = expn.expn_data();
1259             // We only need to serialize the ExpnData
1260             // if it comes from this crate.
1261             // We currently don't serialize any hygiene information data for
1262             // proc-macro crates: see the `SpecializedEncoder<Span>` impl
1263             // for crate metadata.
1264             if data.krate == LOCAL_CRATE {
1265                 needs_data();
1266             }
1267             data.orig_id.expect("Missing orig_id").encode(e)?;
1268             data.krate.encode(e)
1269         }
1270     }
1271 }
1272
1273 pub enum ExpnDataEncodeMode {
1274     IncrComp,
1275     Metadata,
1276 }
1277
1278 pub enum ExpnDataDecodeMode<'a, F: FnOnce(CrateNum) -> &'a HygieneDecodeContext> {
1279     IncrComp(&'a HygieneDecodeContext),
1280     Metadata(F),
1281 }
1282
1283 impl<'a> ExpnDataDecodeMode<'a, Box<dyn FnOnce(CrateNum) -> &'a HygieneDecodeContext>> {
1284     pub fn incr_comp(ctxt: &'a HygieneDecodeContext) -> Self {
1285         ExpnDataDecodeMode::IncrComp(ctxt)
1286     }
1287 }
1288
1289 impl<E: Encoder> Encodable<E> for SyntaxContext {
1290     default fn encode(&self, _: &mut E) -> Result<(), E::Error> {
1291         panic!("cannot encode `SyntaxContext` with `{}`", std::any::type_name::<E>());
1292     }
1293 }
1294
1295 impl<D: Decoder> Decodable<D> for SyntaxContext {
1296     default fn decode(_: &mut D) -> Result<Self, D::Error> {
1297         panic!("cannot decode `SyntaxContext` with `{}`", std::any::type_name::<D>());
1298     }
1299 }
1300
1301 /// Updates the `disambiguator` field of the corresponding `ExpnData`
1302 /// such that the `Fingerprint` of the `ExpnData` does not collide with
1303 /// any other `ExpnIds`.
1304 ///
1305 /// This method is called only when an `ExpnData` is first associated
1306 /// with an `ExpnId` (when the `ExpnId` is initially constructed, or via
1307 /// `set_expn_data`). It is *not* called for foreign `ExpnId`s deserialized
1308 /// from another crate's metadata - since `ExpnData` includes a `krate` field,
1309 /// collisions are only possible between `ExpnId`s within the same crate.
1310 fn update_disambiguator(expn_id: ExpnId) {
1311     /// A `HashStableContext` which hashes the raw id values for `DefId`
1312     /// and `CrateNum`, rather than using their computed stable hash.
1313     ///
1314     /// This allows us to use the `HashStable` implementation on `ExpnId`
1315     /// early on in compilation, before we've constructed a `TyCtxt`.
1316     /// The `Fingerprint`s created by this context are not 'stable', since
1317     /// the raw `CrateNum` and `DefId` values for an item may change between
1318     /// sessions due to unrelated changes (e.g. adding/removing an different item).
1319     ///
1320     /// However, this is fine for our purposes - we only need to detect
1321     /// when two `ExpnData`s have the same `Fingerprint`. Since the hashes produced
1322     /// by this context still obey the properties of `HashStable`, we have
1323     /// that
1324     /// `hash_stable(expn1, DummyHashStableContext) == hash_stable(expn2, DummyHashStableContext)`
1325     /// iff `hash_stable(expn1, StableHashingContext) == hash_stable(expn2, StableHasingContext)`.
1326     ///
1327     /// This is sufficient for determining when we need to update the disambiguator.
1328     struct DummyHashStableContext<'a> {
1329         caching_source_map: CachingSourceMapView<'a>,
1330     }
1331
1332     impl<'a> crate::HashStableContext for DummyHashStableContext<'a> {
1333         #[inline]
1334         fn def_path_hash(&self, def_id: DefId) -> DefPathHash {
1335             DefPathHash(Fingerprint::new(
1336                 def_id.krate.as_u32().into(),
1337                 def_id.index.as_u32().into(),
1338             ))
1339         }
1340
1341         fn expn_id_cache() -> &'static LocalKey<ExpnIdCache> {
1342             // This cache is only used by `DummyHashStableContext`,
1343             // so we won't pollute the cache values of the normal `StableHashingContext`
1344             thread_local! {
1345                 static CACHE: ExpnIdCache = const { ExpnIdCache::new(Vec::new()) };
1346             }
1347
1348             &CACHE
1349         }
1350
1351         fn hash_spans(&self) -> bool {
1352             true
1353         }
1354         fn span_data_to_lines_and_cols(
1355             &mut self,
1356             span: &crate::SpanData,
1357         ) -> Option<(Lrc<SourceFile>, usize, BytePos, usize, BytePos)> {
1358             self.caching_source_map.span_data_to_lines_and_cols(span)
1359         }
1360     }
1361
1362     let source_map = SESSION_GLOBALS
1363         .with(|session_globals| session_globals.source_map.borrow().as_ref().unwrap().clone());
1364
1365     let mut ctx =
1366         DummyHashStableContext { caching_source_map: CachingSourceMapView::new(&source_map) };
1367
1368     let mut hasher = StableHasher::new();
1369
1370     let expn_data = expn_id.expn_data();
1371     // This disambiguator should not have been set yet.
1372     assert_eq!(
1373         expn_data.disambiguator, 0,
1374         "Already set disambiguator for ExpnData: {:?}",
1375         expn_data
1376     );
1377     expn_data.hash_stable(&mut ctx, &mut hasher);
1378     let first_hash = hasher.finish();
1379
1380     let modified = HygieneData::with(|data| {
1381         // If this is the first ExpnData with a given hash, then keep our
1382         // disambiguator at 0 (the default u32 value)
1383         let disambig = data.expn_data_disambiguators.entry(first_hash).or_default();
1384         data.expn_data[expn_id.0 as usize].as_mut().unwrap().disambiguator = *disambig;
1385         *disambig += 1;
1386
1387         *disambig != 1
1388     });
1389
1390     if modified {
1391         debug!("Set disambiguator for {:?} (hash {:?})", expn_id, first_hash);
1392         debug!("expn_data = {:?}", expn_id.expn_data());
1393
1394         // Verify that the new disambiguator makes the hash unique
1395         #[cfg(debug_assertions)]
1396         {
1397             hasher = StableHasher::new();
1398             expn_id.expn_data().hash_stable(&mut ctx, &mut hasher);
1399             let new_hash: Fingerprint = hasher.finish();
1400
1401             HygieneData::with(|data| {
1402                 assert_eq!(
1403                     data.expn_data_disambiguators.get(&new_hash),
1404                     None,
1405                     "Hash collision after disambiguator update!",
1406                 );
1407             });
1408         };
1409     }
1410 }