1 //! Machinery for hygienic macros.
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>.
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`.
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.
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.)
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}
;
32 use crate::def_id
::{CrateNum, DefId, 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}
;
41 use std
::thread
::LocalKey
;
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);
48 #[derive(Debug, Encodable, Decodable, Clone)]
49 pub struct SyntaxContextData
{
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
,
61 /// A unique ID associated with a macro invocation and expansion.
62 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
63 pub struct ExpnId(u32);
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.
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.
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.
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
));
90 update_disambiguator(expn_id
);
95 /// The ID of the theoretical expansion that generates freshly parsed, unexpanded AST.
97 pub fn root() -> Self {
102 pub fn as_u32(self) -> u32 {
107 pub fn from_u32(raw
: u32) -> ExpnId
{
112 pub fn expn_data(self) -> ExpnData
{
113 HygieneData
::with(|data
| data
.expn_data(self).clone())
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
);
125 update_disambiguator(self)
128 pub fn is_descendant_of(self, ancestor
: ExpnId
) -> bool
{
129 HygieneData
::with(|data
| data
.is_descendant_of(self, ancestor
))
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
)))
138 /// Returns span for the macro which originally caused this expansion to happen.
140 /// Stops backtracing at include! boundary.
141 pub fn expansion_cause(mut self) -> Option
<Span
> {
142 let mut last_macro
= None
;
144 let expn_data
= self.expn_data();
145 // Stop going up the backtrace once include! is encountered
146 if expn_data
.is_root()
147 || expn_data
.kind
== ExpnKind
::Macro(MacroKind
::Bang
, sym
::include
)
151 self = expn_data
.call_site
.ctxt().outer_expn();
152 last_macro
= Some(expn_data
.call_site
);
159 pub struct HygieneData
{
160 /// Each expansion should have an associated expansion data, but sometimes there's a delay
161 /// between creation of an expansion ID and obtaining its data (e.g. macros are collected
162 /// first and then resolved later), so we use an `Option` here.
163 expn_data
: Vec
<Option
<ExpnData
>>,
164 syntax_context_data
: Vec
<SyntaxContextData
>,
165 syntax_context_map
: FxHashMap
<(SyntaxContext
, ExpnId
, Transparency
), SyntaxContext
>,
166 /// Maps the `Fingerprint` of an `ExpnData` to the next disambiguator value.
167 /// This is used by `update_disambiguator` to keep track of which `ExpnData`s
168 /// would have collisions without a disambiguator.
169 /// The keys of this map are always computed with `ExpnData.disambiguator`
171 expn_data_disambiguators
: FxHashMap
<Fingerprint
, u32>,
175 crate fn new(edition
: Edition
) -> Self {
176 let mut root_data
= ExpnData
::default(
180 Some(DefId
::local(CRATE_DEF_INDEX
)),
182 root_data
.orig_id
= Some(0);
185 expn_data
: vec
![Some(root_data
)],
186 syntax_context_data
: vec
![SyntaxContextData
{
187 outer_expn
: ExpnId
::root(),
188 outer_transparency
: Transparency
::Opaque
,
189 parent
: SyntaxContext(0),
190 opaque
: SyntaxContext(0),
191 opaque_and_semitransparent
: SyntaxContext(0),
192 dollar_crate_name
: kw
::DollarCrate
,
194 syntax_context_map
: FxHashMap
::default(),
195 expn_data_disambiguators
: FxHashMap
::default(),
199 pub fn with
<T
, F
: FnOnce(&mut HygieneData
) -> T
>(f
: F
) -> T
{
200 SESSION_GLOBALS
.with(|session_globals
| f(&mut *session_globals
.hygiene_data
.borrow_mut()))
203 fn fresh_expn(&mut self, mut expn_data
: Option
<ExpnData
>) -> ExpnId
{
204 let raw_id
= self.expn_data
.len() as u32;
205 if let Some(data
) = expn_data
.as_mut() {
206 assert_eq
!(data
.orig_id
, None
);
207 data
.orig_id
= Some(raw_id
);
209 self.expn_data
.push(expn_data
);
213 fn expn_data(&self, expn_id
: ExpnId
) -> &ExpnData
{
214 self.expn_data
[expn_id
.0 as usize].as_ref().expect("no expansion data for an expansion ID")
217 fn is_descendant_of(&self, mut expn_id
: ExpnId
, ancestor
: ExpnId
) -> bool
{
218 while expn_id
!= ancestor
{
219 if expn_id
== ExpnId
::root() {
222 expn_id
= self.expn_data(expn_id
).parent
;
227 fn normalize_to_macros_2_0(&self, ctxt
: SyntaxContext
) -> SyntaxContext
{
228 self.syntax_context_data
[ctxt
.0 as usize].opaque
231 fn normalize_to_macro_rules(&self, ctxt
: SyntaxContext
) -> SyntaxContext
{
232 self.syntax_context_data
[ctxt
.0 as usize].opaque_and_semitransparent
235 fn outer_expn(&self, ctxt
: SyntaxContext
) -> ExpnId
{
236 self.syntax_context_data
[ctxt
.0 as usize].outer_expn
239 fn outer_mark(&self, ctxt
: SyntaxContext
) -> (ExpnId
, Transparency
) {
240 let data
= &self.syntax_context_data
[ctxt
.0 as usize];
241 (data
.outer_expn
, data
.outer_transparency
)
244 fn parent_ctxt(&self, ctxt
: SyntaxContext
) -> SyntaxContext
{
245 self.syntax_context_data
[ctxt
.0 as usize].parent
248 fn remove_mark(&self, ctxt
: &mut SyntaxContext
) -> (ExpnId
, Transparency
) {
249 let outer_mark
= self.outer_mark(*ctxt
);
250 *ctxt
= self.parent_ctxt(*ctxt
);
254 fn marks(&self, mut ctxt
: SyntaxContext
) -> Vec
<(ExpnId
, Transparency
)> {
255 let mut marks
= Vec
::new();
256 while ctxt
!= SyntaxContext
::root() {
257 debug
!("marks: getting parent of {:?}", ctxt
);
258 marks
.push(self.outer_mark(ctxt
));
259 ctxt
= self.parent_ctxt(ctxt
);
265 fn walk_chain(&self, mut span
: Span
, to
: SyntaxContext
) -> Span
{
266 debug
!("walk_chain({:?}, {:?})", span
, to
);
267 debug
!("walk_chain: span ctxt = {:?}", span
.ctxt());
268 while span
.from_expansion() && span
.ctxt() != to
{
269 let outer_expn
= self.outer_expn(span
.ctxt());
270 debug
!("walk_chain({:?}): outer_expn={:?}", span
, outer_expn
);
271 let expn_data
= self.expn_data(outer_expn
);
272 debug
!("walk_chain({:?}): expn_data={:?}", span
, expn_data
);
273 span
= expn_data
.call_site
;
278 fn adjust(&self, ctxt
: &mut SyntaxContext
, expn_id
: ExpnId
) -> Option
<ExpnId
> {
279 let mut scope
= None
;
280 while !self.is_descendant_of(expn_id
, self.outer_expn(*ctxt
)) {
281 scope
= Some(self.remove_mark(ctxt
).0);
290 transparency
: Transparency
,
292 assert_ne
!(expn_id
, ExpnId
::root());
293 if transparency
== Transparency
::Opaque
{
294 return self.apply_mark_internal(ctxt
, expn_id
, transparency
);
297 let call_site_ctxt
= self.expn_data(expn_id
).call_site
.ctxt();
298 let mut call_site_ctxt
= if transparency
== Transparency
::SemiTransparent
{
299 self.normalize_to_macros_2_0(call_site_ctxt
)
301 self.normalize_to_macro_rules(call_site_ctxt
)
304 if call_site_ctxt
== SyntaxContext
::root() {
305 return self.apply_mark_internal(ctxt
, expn_id
, transparency
);
308 // Otherwise, `expn_id` is a macros 1.0 definition and the call site is in a
309 // macros 2.0 expansion, i.e., a macros 1.0 invocation is in a macros 2.0 definition.
311 // In this case, the tokens from the macros 1.0 definition inherit the hygiene
312 // at their invocation. That is, we pretend that the macros 1.0 definition
313 // was defined at its invocation (i.e., inside the macros 2.0 definition)
314 // so that the macros 2.0 definition remains hygienic.
316 // See the example at `test/ui/hygiene/legacy_interaction.rs`.
317 for (expn_id
, transparency
) in self.marks(ctxt
) {
318 call_site_ctxt
= self.apply_mark_internal(call_site_ctxt
, expn_id
, transparency
);
320 self.apply_mark_internal(call_site_ctxt
, expn_id
, transparency
)
323 fn apply_mark_internal(
327 transparency
: Transparency
,
329 let syntax_context_data
= &mut self.syntax_context_data
;
330 let mut opaque
= syntax_context_data
[ctxt
.0 as usize].opaque
;
331 let mut opaque_and_semitransparent
=
332 syntax_context_data
[ctxt
.0 as usize].opaque_and_semitransparent
;
334 if transparency
>= Transparency
::Opaque
{
338 .entry((parent
, expn_id
, transparency
))
340 let new_opaque
= SyntaxContext(syntax_context_data
.len() as u32);
341 syntax_context_data
.push(SyntaxContextData
{
343 outer_transparency
: transparency
,
346 opaque_and_semitransparent
: new_opaque
,
347 dollar_crate_name
: kw
::DollarCrate
,
353 if transparency
>= Transparency
::SemiTransparent
{
354 let parent
= opaque_and_semitransparent
;
355 opaque_and_semitransparent
= *self
357 .entry((parent
, expn_id
, transparency
))
359 let new_opaque_and_semitransparent
=
360 SyntaxContext(syntax_context_data
.len() as u32);
361 syntax_context_data
.push(SyntaxContextData
{
363 outer_transparency
: transparency
,
366 opaque_and_semitransparent
: new_opaque_and_semitransparent
,
367 dollar_crate_name
: kw
::DollarCrate
,
369 new_opaque_and_semitransparent
374 *self.syntax_context_map
.entry((parent
, expn_id
, transparency
)).or_insert_with(|| {
375 let new_opaque_and_semitransparent_and_transparent
=
376 SyntaxContext(syntax_context_data
.len() as u32);
377 syntax_context_data
.push(SyntaxContextData
{
379 outer_transparency
: transparency
,
382 opaque_and_semitransparent
,
383 dollar_crate_name
: kw
::DollarCrate
,
385 new_opaque_and_semitransparent_and_transparent
390 pub fn clear_syntax_context_map() {
391 HygieneData
::with(|data
| data
.syntax_context_map
= FxHashMap
::default());
394 pub fn walk_chain(span
: Span
, to
: SyntaxContext
) -> Span
{
395 HygieneData
::with(|data
| data
.walk_chain(span
, to
))
398 pub fn update_dollar_crate_names(mut get_name
: impl FnMut(SyntaxContext
) -> Symbol
) {
399 // The new contexts that need updating are at the end of the list and have `$crate` as a name.
400 let (len
, to_update
) = HygieneData
::with(|data
| {
402 data
.syntax_context_data
.len(),
403 data
.syntax_context_data
406 .take_while(|scdata
| scdata
.dollar_crate_name
== kw
::DollarCrate
)
410 // The callback must be called from outside of the `HygieneData` lock,
411 // since it will try to acquire it too.
412 let range_to_update
= len
- to_update
..len
;
414 range_to_update
.clone().map(|idx
| get_name(SyntaxContext
::from_u32(idx
as u32))).collect();
415 HygieneData
::with(|data
| {
416 range_to_update
.zip(names
).for_each(|(idx
, name
)| {
417 data
.syntax_context_data
[idx
].dollar_crate_name
= name
;
422 pub fn debug_hygiene_data(verbose
: bool
) -> String
{
423 HygieneData
::with(|data
| {
425 format
!("{:#?}", data
)
427 let mut s
= String
::from("");
428 s
.push_str("Expansions:");
429 data
.expn_data
.iter().enumerate().for_each(|(id
, expn_info
)| {
430 let expn_info
= expn_info
.as_ref().expect("no expansion data for an expansion ID");
432 "\n{}: parent: {:?}, call_site_ctxt: {:?}, def_site_ctxt: {:?}, kind: {:?}",
435 expn_info
.call_site
.ctxt(),
436 expn_info
.def_site
.ctxt(),
440 s
.push_str("\n\nSyntaxContexts:");
441 data
.syntax_context_data
.iter().enumerate().for_each(|(id
, ctxt
)| {
443 "\n#{}: parent: {:?}, outer_mark: ({:?}, {:?})",
444 id
, ctxt
.parent
, ctxt
.outer_expn
, ctxt
.outer_transparency
,
454 pub const fn root() -> Self {
459 crate fn as_u32(self) -> u32 {
464 crate fn from_u32(raw
: u32) -> SyntaxContext
{
468 /// Extend a syntax context with a given expansion and transparency.
469 crate fn apply_mark(self, expn_id
: ExpnId
, transparency
: Transparency
) -> SyntaxContext
{
470 HygieneData
::with(|data
| data
.apply_mark(self, expn_id
, transparency
))
473 /// Pulls a single mark off of the syntax context. This effectively moves the
474 /// context up one macro definition level. That is, if we have a nested macro
475 /// definition as follows:
485 /// and we have a SyntaxContext that is referring to something declared by an invocation
486 /// of g (call it g1), calling remove_mark will result in the SyntaxContext for the
487 /// invocation of f that created g1.
488 /// Returns the mark that was removed.
489 pub fn remove_mark(&mut self) -> ExpnId
{
490 HygieneData
::with(|data
| data
.remove_mark(self).0)
493 pub fn marks(self) -> Vec
<(ExpnId
, Transparency
)> {
494 HygieneData
::with(|data
| data
.marks(self))
497 /// Adjust this context for resolution in a scope created by the given expansion.
498 /// For example, consider the following three resolutions of `f`:
501 /// mod foo { pub fn f() {} } // `f`'s `SyntaxContext` is empty.
503 /// macro m($f:ident) {
505 /// pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
506 /// pub fn $f() {} // `$f`'s `SyntaxContext` is empty.
508 /// foo::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
509 /// //^ Since `mod foo` is outside this expansion, `adjust` removes the mark from `f`,
510 /// //| and it resolves to `::foo::f`.
511 /// bar::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
512 /// //^ Since `mod bar` not outside this expansion, `adjust` does not change `f`,
513 /// //| and it resolves to `::bar::f`.
514 /// bar::$f(); // `f`'s `SyntaxContext` is empty.
515 /// //^ Since `mod bar` is not outside this expansion, `adjust` does not change `$f`,
516 /// //| and it resolves to `::bar::$f`.
519 /// This returns the expansion whose definition scope we use to privacy check the resolution,
520 /// or `None` if we privacy check as usual (i.e., not w.r.t. a macro definition scope).
521 pub fn adjust(&mut self, expn_id
: ExpnId
) -> Option
<ExpnId
> {
522 HygieneData
::with(|data
| data
.adjust(self, expn_id
))
525 /// Like `SyntaxContext::adjust`, but also normalizes `self` to macros 2.0.
526 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id
: ExpnId
) -> Option
<ExpnId
> {
527 HygieneData
::with(|data
| {
528 *self = data
.normalize_to_macros_2_0(*self);
529 data
.adjust(self, expn_id
)
533 /// Adjust this context for resolution in a scope created by the given expansion
534 /// via a glob import with the given `SyntaxContext`.
539 /// macro m($i:ident) {
541 /// pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
542 /// pub fn $i() {} // `$i`'s `SyntaxContext` is empty.
545 /// macro n($j:ident) {
547 /// f(); // `f`'s `SyntaxContext` has a mark from `m` and a mark from `n`
548 /// //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::f`.
549 /// $i(); // `$i`'s `SyntaxContext` has a mark from `n`
550 /// //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::$i`.
551 /// $j(); // `$j`'s `SyntaxContext` has a mark from `m`
552 /// //^ This cannot be glob-adjusted, so this is a resolution error.
556 /// This returns `None` if the context cannot be glob-adjusted.
557 /// Otherwise, it returns the scope to use when privacy checking (see `adjust` for details).
558 pub fn glob_adjust(&mut self, expn_id
: ExpnId
, glob_span
: Span
) -> Option
<Option
<ExpnId
>> {
559 HygieneData
::with(|data
| {
560 let mut scope
= None
;
561 let mut glob_ctxt
= data
.normalize_to_macros_2_0(glob_span
.ctxt());
562 while !data
.is_descendant_of(expn_id
, data
.outer_expn(glob_ctxt
)) {
563 scope
= Some(data
.remove_mark(&mut glob_ctxt
).0);
564 if data
.remove_mark(self).0 != scope
.unwrap() {
568 if data
.adjust(self, expn_id
).is_some() {
575 /// Undo `glob_adjust` if possible:
578 /// if let Some(privacy_checking_scope) = self.reverse_glob_adjust(expansion, glob_ctxt) {
579 /// assert!(self.glob_adjust(expansion, glob_ctxt) == Some(privacy_checking_scope));
582 pub fn reverse_glob_adjust(
586 ) -> Option
<Option
<ExpnId
>> {
587 HygieneData
::with(|data
| {
588 if data
.adjust(self, expn_id
).is_some() {
592 let mut glob_ctxt
= data
.normalize_to_macros_2_0(glob_span
.ctxt());
593 let mut marks
= Vec
::new();
594 while !data
.is_descendant_of(expn_id
, data
.outer_expn(glob_ctxt
)) {
595 marks
.push(data
.remove_mark(&mut glob_ctxt
));
598 let scope
= marks
.last().map(|mark
| mark
.0);
599 while let Some((expn_id
, transparency
)) = marks
.pop() {
600 *self = data
.apply_mark(*self, expn_id
, transparency
);
606 pub fn hygienic_eq(self, other
: SyntaxContext
, expn_id
: ExpnId
) -> bool
{
607 HygieneData
::with(|data
| {
608 let mut self_normalized
= data
.normalize_to_macros_2_0(self);
609 data
.adjust(&mut self_normalized
, expn_id
);
610 self_normalized
== data
.normalize_to_macros_2_0(other
)
615 pub fn normalize_to_macros_2_0(self) -> SyntaxContext
{
616 HygieneData
::with(|data
| data
.normalize_to_macros_2_0(self))
620 pub fn normalize_to_macro_rules(self) -> SyntaxContext
{
621 HygieneData
::with(|data
| data
.normalize_to_macro_rules(self))
625 pub fn outer_expn(self) -> ExpnId
{
626 HygieneData
::with(|data
| data
.outer_expn(self))
629 /// `ctxt.outer_expn_data()` is equivalent to but faster than
630 /// `ctxt.outer_expn().expn_data()`.
632 pub fn outer_expn_data(self) -> ExpnData
{
633 HygieneData
::with(|data
| data
.expn_data(data
.outer_expn(self)).clone())
637 pub fn outer_mark(self) -> (ExpnId
, Transparency
) {
638 HygieneData
::with(|data
| data
.outer_mark(self))
641 pub fn dollar_crate_name(self) -> Symbol
{
642 HygieneData
::with(|data
| data
.syntax_context_data
[self.0 as usize].dollar_crate_name
)
645 pub fn edition(self) -> Edition
{
646 self.outer_expn_data().edition
650 impl fmt
::Debug
for SyntaxContext
{
651 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
652 write
!(f
, "#{}", self.0)
657 /// Creates a fresh expansion with given properties.
658 /// Expansions are normally created by macros, but in some cases expansions are created for
659 /// other compiler-generated code to set per-span properties like allowed unstable features.
660 /// The returned span belongs to the created expansion and has the new properties,
661 /// but its location is inherited from the current span.
662 pub fn fresh_expansion(self, expn_data
: ExpnData
) -> Span
{
663 self.fresh_expansion_with_transparency(expn_data
, Transparency
::Transparent
)
666 pub fn fresh_expansion_with_transparency(
669 transparency
: Transparency
,
671 let expn_id
= ExpnId
::fresh(Some(expn_data
));
672 HygieneData
::with(|data
| {
673 self.with_ctxt(data
.apply_mark(SyntaxContext
::root(), expn_id
, transparency
))
677 /// Reuses the span but adds information like the kind of the desugaring and features that are
678 /// allowed inside this span.
679 pub fn mark_with_reason(
681 allow_internal_unstable
: Option
<Lrc
<[Symbol
]>>,
682 reason
: DesugaringKind
,
685 self.fresh_expansion(ExpnData
{
686 allow_internal_unstable
,
687 ..ExpnData
::default(ExpnKind
::Desugaring(reason
), self, edition
, None
)
692 /// A subset of properties from both macro definition and macro call available through global data.
693 /// Avoid using this if you have access to the original definition or call structures.
694 #[derive(Clone, Debug, Encodable, Decodable, HashStable_Generic)]
695 pub struct ExpnData
{
696 // --- The part unique to each expansion.
697 /// The kind of this expansion - macro or compiler desugaring.
699 /// The expansion that produced this expansion.
701 /// The location of the actual macro invocation or syntax sugar , e.g.
702 /// `let x = foo!();` or `if let Some(y) = x {}`
704 /// This may recursively refer to other macro invocations, e.g., if
705 /// `foo!()` invoked `bar!()` internally, and there was an
706 /// expression inside `bar!`; the call_site of the expression in
707 /// the expansion would point to the `bar!` invocation; that
708 /// call_site span would have its own ExpnData, with the call_site
709 /// pointing to the `foo!` invocation.
712 // --- The part specific to the macro/desugaring definition.
713 // --- It may be reasonable to share this part between expansions with the same definition,
714 // --- but such sharing is known to bring some minor inconveniences without also bringing
715 // --- noticeable perf improvements (PR #62898).
716 /// The span of the macro definition (possibly dummy).
717 /// This span serves only informational purpose and is not used for resolution.
719 /// List of `#[unstable]`/feature-gated features that the macro is allowed to use
720 /// internally without forcing the whole crate to opt-in
722 pub allow_internal_unstable
: Option
<Lrc
<[Symbol
]>>,
723 /// Whether the macro is allowed to use `unsafe` internally
724 /// even if the user crate has `#![forbid(unsafe_code)]`.
725 pub allow_internal_unsafe
: bool
,
726 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`)
727 /// for a given macro.
728 pub local_inner_macros
: bool
,
729 /// Edition of the crate in which the macro is defined.
730 pub edition
: Edition
,
731 /// The `DefId` of the macro being invoked,
732 /// if this `ExpnData` corresponds to a macro invocation
733 pub macro_def_id
: Option
<DefId
>,
734 /// The crate that originally created this `ExpnData`. During
735 /// metadata serialization, we only encode `ExpnData`s that were
736 /// created locally - when our serialized metadata is decoded,
737 /// foreign `ExpnId`s will have their `ExpnData` looked up
738 /// from the crate specified by `Crate
740 /// The raw that this `ExpnData` had in its original crate.
741 /// An `ExpnData` can be created before being assigned an `ExpnId`,
742 /// so this might be `None` until `set_expn_data` is called
743 // This is used only for serialization/deserialization purposes:
744 // two `ExpnData`s that differ only in their `orig_id` should
745 // be considered equivalent.
746 #[stable_hasher(ignore)]
747 orig_id
: Option
<u32>,
749 /// Used to force two `ExpnData`s to have different `Fingerprint`s.
750 /// Due to macro expansion, it's possible to end up with two `ExpnId`s
751 /// that have identical `ExpnData`s. This violates the contract of `HashStable`
752 /// - the two `ExpnId`s are not equal, but their `Fingerprint`s are equal
753 /// (since the numerical `ExpnId` value is not considered by the `HashStable`
756 /// The `disambiguator` field is set by `update_disambiguator` when two distinct
757 /// `ExpnId`s would end up with the same `Fingerprint`. Since `ExpnData` includes
758 /// a `krate` field, this value only needs to be unique within a single crate.
762 // These would require special handling of `orig_id`.
763 impl !PartialEq
for ExpnData {}
764 impl !Hash
for ExpnData {}
772 allow_internal_unstable
: Option
<Lrc
<[Symbol
]>>,
773 allow_internal_unsafe
: bool
,
774 local_inner_macros
: bool
,
776 macro_def_id
: Option
<DefId
>,
783 allow_internal_unstable
,
784 allow_internal_unsafe
,
794 /// Constructs expansion data with default properties.
799 macro_def_id
: Option
<DefId
>,
803 parent
: ExpnId
::root(),
806 allow_internal_unstable
: None
,
807 allow_internal_unsafe
: false,
808 local_inner_macros
: false,
817 pub fn allow_unstable(
821 allow_internal_unstable
: Lrc
<[Symbol
]>,
822 macro_def_id
: Option
<DefId
>,
825 allow_internal_unstable
: Some(allow_internal_unstable
),
826 ..ExpnData
::default(kind
, call_site
, edition
, macro_def_id
)
831 pub fn is_root(&self) -> bool
{
832 matches
!(self.kind
, ExpnKind
::Root
)
837 #[derive(Clone, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
839 /// No expansion, aka root expansion. Only `ExpnId::root()` has this kind.
841 /// Expansion produced by a macro.
842 Macro(MacroKind
, Symbol
),
843 /// Transform done by the compiler on the AST.
845 /// Desugaring done by the compiler during HIR lowering.
846 Desugaring(DesugaringKind
),
852 pub fn descr(&self) -> String
{
854 ExpnKind
::Root
=> kw
::PathRoot
.to_string(),
855 ExpnKind
::Macro(macro_kind
, name
) => match macro_kind
{
856 MacroKind
::Bang
=> format
!("{}!", name
),
857 MacroKind
::Attr
=> format
!("#[{}]", name
),
858 MacroKind
::Derive
=> format
!("#[derive({})]", name
),
860 ExpnKind
::AstPass(kind
) => kind
.descr().to_string(),
861 ExpnKind
::Desugaring(kind
) => format
!("desugaring of {}", kind
.descr()),
862 ExpnKind
::Inlined
=> "inlined source".to_string(),
867 /// The kind of macro invocation or definition.
868 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
869 #[derive(HashStable_Generic)]
871 /// A bang macro `foo!()`.
873 /// An attribute macro `#[foo]`.
875 /// A derive macro `#[derive(Foo)]`
880 pub fn descr(self) -> &'
static str {
882 MacroKind
::Bang
=> "macro",
883 MacroKind
::Attr
=> "attribute macro",
884 MacroKind
::Derive
=> "derive macro",
888 pub fn descr_expected(self) -> &'
static str {
890 MacroKind
::Attr
=> "attribute",
895 pub fn article(self) -> &'
static str {
897 MacroKind
::Attr
=> "an",
903 /// The kind of AST transform.
904 #[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
912 fn descr(self) -> &'
static str {
914 AstPass
::StdImports
=> "standard library imports",
915 AstPass
::TestHarness
=> "test harness",
916 AstPass
::ProcMacroHarness
=> "proc macro harness",
921 /// The kind of compiler desugaring.
922 #[derive(Clone, Copy, PartialEq, Debug, Encodable, Decodable, HashStable_Generic)]
923 pub enum DesugaringKind
{
924 /// We desugar `if c { i } else { e }` to `match $ExprKind::Use(c) { true => i, _ => e }`.
925 /// However, we do not want to blame `c` for unreachability but rather say that `i`
926 /// is unreachable. This desugaring kind allows us to avoid blaming `c`.
927 /// This also applies to `while` loops.
931 /// Desugaring of an `impl Trait` in return type position
932 /// to an `type Foo = impl Trait;` and replacing the
933 /// `impl Trait` with `Foo`.
940 /// A location in the desugaring of a `for` loop
941 #[derive(Clone, Copy, PartialEq, Debug, Encodable, Decodable, HashStable_Generic)]
942 pub enum ForLoopLoc
{
947 impl DesugaringKind
{
948 /// The description wording should combine well with "desugaring of {}".
949 fn descr(self) -> &'
static str {
951 DesugaringKind
::CondTemporary
=> "`if` or `while` condition",
952 DesugaringKind
::Async
=> "`async` block or function",
953 DesugaringKind
::Await
=> "`await` expression",
954 DesugaringKind
::QuestionMark
=> "operator `?`",
955 DesugaringKind
::TryBlock
=> "`try` block",
956 DesugaringKind
::OpaqueTy
=> "`impl Trait`",
957 DesugaringKind
::ForLoop(_
) => "`for` loop",
963 pub struct HygieneEncodeContext
{
964 /// All `SyntaxContexts` for which we have written `SyntaxContextData` into crate metadata.
965 /// This is `None` after we finish encoding `SyntaxContexts`, to ensure
966 /// that we don't accidentally try to encode any more `SyntaxContexts`
967 serialized_ctxts
: Lock
<FxHashSet
<SyntaxContext
>>,
968 /// The `SyntaxContexts` that we have serialized (e.g. as a result of encoding `Spans`)
969 /// in the most recent 'round' of serializnig. Serializing `SyntaxContextData`
970 /// may cause us to serialize more `SyntaxContext`s, so serialize in a loop
971 /// until we reach a fixed point.
972 latest_ctxts
: Lock
<FxHashSet
<SyntaxContext
>>,
974 serialized_expns
: Lock
<FxHashSet
<ExpnId
>>,
976 latest_expns
: Lock
<FxHashSet
<ExpnId
>>,
979 impl HygieneEncodeContext
{
983 F
: FnMut(&mut T
, u32, &SyntaxContextData
) -> Result
<(), R
>,
984 G
: FnMut(&mut T
, u32, &ExpnData
) -> Result
<(), R
>,
991 // When we serialize a `SyntaxContextData`, we may end up serializing
992 // a `SyntaxContext` that we haven't seen before
993 while !self.latest_ctxts
.lock().is_empty() || !self.latest_expns
.lock().is_empty() {
995 "encode_hygiene: Serializing a round of {:?} SyntaxContextDatas: {:?}",
996 self.latest_ctxts
.lock().len(),
1000 // Consume the current round of SyntaxContexts.
1001 // Drop the lock() temporary early
1002 let latest_ctxts
= { std::mem::take(&mut *self.latest_ctxts.lock()) }
;
1004 // It's fine to iterate over a HashMap, because the serialization
1005 // of the table that we insert data into doesn't depend on insertion
1007 for_all_ctxts_in(latest_ctxts
.into_iter(), |(index
, ctxt
, data
)| {
1008 if self.serialized_ctxts
.lock().insert(ctxt
) {
1009 encode_ctxt(encoder
, index
, data
)?
;
1014 let latest_expns
= { std::mem::take(&mut *self.latest_expns.lock()) }
;
1016 for_all_expns_in(latest_expns
.into_iter(), |index
, expn
, data
| {
1017 if self.serialized_expns
.lock().insert(expn
) {
1018 encode_expn(encoder
, index
, data
)?
;
1023 debug
!("encode_hygiene: Done serializing SyntaxContextData");
1029 /// Additional information used to assist in decoding hygiene data
1030 pub struct HygieneDecodeContext
{
1031 // Maps serialized `SyntaxContext` ids to a `SyntaxContext` in the current
1032 // global `HygieneData`. When we deserialize a `SyntaxContext`, we need to create
1033 // a new id in the global `HygieneData`. This map tracks the ID we end up picking,
1034 // so that multiple occurrences of the same serialized id are decoded to the same
1036 remapped_ctxts
: Lock
<Vec
<Option
<SyntaxContext
>>>,
1037 // The same as `remapepd_ctxts`, but for `ExpnId`s
1038 remapped_expns
: Lock
<Vec
<Option
<ExpnId
>>>,
1041 pub fn decode_expn_id
<
1044 F
: FnOnce(&mut D
, u32) -> Result
<ExpnData
, D
::Error
>,
1045 G
: FnOnce(CrateNum
) -> &'a HygieneDecodeContext
,
1048 mode
: ExpnDataDecodeMode
<'a
, G
>,
1050 ) -> Result
<ExpnId
, D
::Error
> {
1051 let index
= u32::decode(d
)?
;
1052 let context
= match mode
{
1053 ExpnDataDecodeMode
::IncrComp(context
) => context
,
1054 ExpnDataDecodeMode
::Metadata(get_context
) => {
1055 let krate
= CrateNum
::decode(d
)?
;
1060 // Do this after decoding, so that we decode a `CrateNum`
1062 if index
== ExpnId
::root().as_u32() {
1063 debug
!("decode_expn_id: deserialized root");
1064 return Ok(ExpnId
::root());
1067 let outer_expns
= &context
.remapped_expns
;
1069 // Ensure that the lock() temporary is dropped early
1071 if let Some(expn_id
) = outer_expns
.lock().get(index
as usize).copied().flatten() {
1076 // Don't decode the data inside `HygieneData::with`, since we need to recursively decode
1078 let mut expn_data
= decode_data(d
, index
)?
;
1080 let expn_id
= HygieneData
::with(|hygiene_data
| {
1081 let expn_id
= ExpnId(hygiene_data
.expn_data
.len() as u32);
1083 // If we just deserialized an `ExpnData` owned by
1084 // the local crate, its `orig_id` will be stale,
1085 // so we need to update it to its own value.
1086 // This only happens when we deserialize the incremental cache,
1087 // since a crate will never decode its own metadata.
1088 if expn_data
.krate
== LOCAL_CRATE
{
1089 expn_data
.orig_id
= Some(expn_id
.0);
1092 hygiene_data
.expn_data
.push(Some(expn_data
));
1094 let mut expns
= outer_expns
.lock();
1095 let new_len
= index
as usize + 1;
1096 if expns
.len() < new_len
{
1097 expns
.resize(new_len
, None
);
1099 expns
[index
as usize] = Some(expn_id
);
1106 // Decodes `SyntaxContext`, using the provided `HygieneDecodeContext`
1107 // to track which `SyntaxContext`s we have already decoded.
1108 // The provided closure will be invoked to deserialize a `SyntaxContextData`
1109 // if we haven't already seen the id of the `SyntaxContext` we are deserializing.
1110 pub fn decode_syntax_context
<
1112 F
: FnOnce(&mut D
, u32) -> Result
<SyntaxContextData
, D
::Error
>,
1115 context
: &HygieneDecodeContext
,
1117 ) -> Result
<SyntaxContext
, D
::Error
> {
1118 let raw_id
: u32 = Decodable
::decode(d
)?
;
1120 debug
!("decode_syntax_context: deserialized root");
1121 // The root is special
1122 return Ok(SyntaxContext
::root());
1125 let outer_ctxts
= &context
.remapped_ctxts
;
1127 // Ensure that the lock() temporary is dropped early
1129 if let Some(ctxt
) = outer_ctxts
.lock().get(raw_id
as usize).copied().flatten() {
1134 // Allocate and store SyntaxContext id *before* calling the decoder function,
1135 // as the SyntaxContextData may reference itself.
1136 let new_ctxt
= HygieneData
::with(|hygiene_data
| {
1137 let new_ctxt
= SyntaxContext(hygiene_data
.syntax_context_data
.len() as u32);
1138 // Push a dummy SyntaxContextData to ensure that nobody else can get the
1139 // same ID as us. This will be overwritten after call `decode_Data`
1140 hygiene_data
.syntax_context_data
.push(SyntaxContextData
{
1141 outer_expn
: ExpnId
::root(),
1142 outer_transparency
: Transparency
::Transparent
,
1143 parent
: SyntaxContext
::root(),
1144 opaque
: SyntaxContext
::root(),
1145 opaque_and_semitransparent
: SyntaxContext
::root(),
1146 dollar_crate_name
: kw
::Empty
,
1148 let mut ctxts
= outer_ctxts
.lock();
1149 let new_len
= raw_id
as usize + 1;
1150 if ctxts
.len() < new_len
{
1151 ctxts
.resize(new_len
, None
);
1153 ctxts
[raw_id
as usize] = Some(new_ctxt
);
1158 // Don't try to decode data while holding the lock, since we need to
1159 // be able to recursively decode a SyntaxContext
1160 let mut ctxt_data
= decode_data(d
, raw_id
)?
;
1161 // Reset `dollar_crate_name` so that it will be updated by `update_dollar_crate_names`
1162 // We don't care what the encoding crate set this to - we want to resolve it
1163 // from the perspective of the current compilation session
1164 ctxt_data
.dollar_crate_name
= kw
::DollarCrate
;
1166 // Overwrite the dummy data with our decoded SyntaxContextData
1167 HygieneData
::with(|hygiene_data
| {
1168 let dummy
= std
::mem
::replace(
1169 &mut hygiene_data
.syntax_context_data
[new_ctxt
.as_u32() as usize],
1172 // Make sure nothing weird happening while `decode_data` was running
1173 assert_eq
!(dummy
.dollar_crate_name
, kw
::Empty
);
1179 fn for_all_ctxts_in
<E
, F
: FnMut((u32, SyntaxContext
, &SyntaxContextData
)) -> Result
<(), E
>>(
1180 ctxts
: impl Iterator
<Item
= SyntaxContext
>,
1182 ) -> Result
<(), E
> {
1183 let all_data
: Vec
<_
> = HygieneData
::with(|data
| {
1184 ctxts
.map(|ctxt
| (ctxt
, data
.syntax_context_data
[ctxt
.0 as usize].clone())).collect()
1186 for (ctxt
, data
) in all_data
.into_iter() {
1187 f((ctxt
.0, ctxt
, &data
))?
;
1192 fn for_all_expns_in
<E
, F
: FnMut(u32, ExpnId
, &ExpnData
) -> Result
<(), E
>>(
1193 expns
: impl Iterator
<Item
= ExpnId
>,
1195 ) -> Result
<(), E
> {
1196 let all_data
: Vec
<_
> = HygieneData
::with(|data
| {
1197 expns
.map(|expn
| (expn
, data
.expn_data
[expn
.0 as usize].clone())).collect()
1199 for (expn
, data
) in all_data
.into_iter() {
1200 f(expn
.0, expn
, &data
.unwrap_or_else(|| panic
!("Missing data for {:?}", expn
)))?
;
1205 impl<E
: Encoder
> Encodable
<E
> for ExpnId
{
1206 default fn encode(&self, _
: &mut E
) -> Result
<(), E
::Error
> {
1207 panic
!("cannot encode `ExpnId` with `{}`", std
::any
::type_name
::<E
>());
1211 impl<D
: Decoder
> Decodable
<D
> for ExpnId
{
1212 default fn decode(_
: &mut D
) -> Result
<Self, D
::Error
> {
1213 panic
!("cannot decode `ExpnId` with `{}`", std
::any
::type_name
::<D
>());
1217 pub fn raw_encode_syntax_context
<E
: Encoder
>(
1218 ctxt
: SyntaxContext
,
1219 context
: &HygieneEncodeContext
,
1221 ) -> Result
<(), E
::Error
> {
1222 if !context
.serialized_ctxts
.lock().contains(&ctxt
) {
1223 context
.latest_ctxts
.lock().insert(ctxt
);
1228 pub fn raw_encode_expn_id
<E
: Encoder
>(
1230 context
: &HygieneEncodeContext
,
1231 mode
: ExpnDataEncodeMode
,
1233 ) -> Result
<(), E
::Error
> {
1234 // Record the fact that we need to serialize the corresponding
1236 let needs_data
= || {
1237 if !context
.serialized_expns
.lock().contains(&expn
) {
1238 context
.latest_expns
.lock().insert(expn
);
1243 ExpnDataEncodeMode
::IncrComp
=> {
1244 // Always serialize the `ExpnData` in incr comp mode
1248 ExpnDataEncodeMode
::Metadata
=> {
1249 let data
= expn
.expn_data();
1250 // We only need to serialize the ExpnData
1251 // if it comes from this crate.
1252 // We currently don't serialize any hygiene information data for
1253 // proc-macro crates: see the `SpecializedEncoder<Span>` impl
1254 // for crate metadata.
1255 if data
.krate
== LOCAL_CRATE
{
1258 data
.orig_id
.expect("Missing orig_id").encode(e
)?
;
1259 data
.krate
.encode(e
)
1264 pub enum ExpnDataEncodeMode
{
1269 pub enum ExpnDataDecodeMode
<'a
, F
: FnOnce(CrateNum
) -> &'a HygieneDecodeContext
> {
1270 IncrComp(&'a HygieneDecodeContext
),
1274 impl<'a
> ExpnDataDecodeMode
<'a
, Box
<dyn FnOnce(CrateNum
) -> &'a HygieneDecodeContext
>> {
1275 pub fn incr_comp(ctxt
: &'a HygieneDecodeContext
) -> Self {
1276 ExpnDataDecodeMode
::IncrComp(ctxt
)
1280 impl<E
: Encoder
> Encodable
<E
> for SyntaxContext
{
1281 default fn encode(&self, _
: &mut E
) -> Result
<(), E
::Error
> {
1282 panic
!("cannot encode `SyntaxContext` with `{}`", std
::any
::type_name
::<E
>());
1286 impl<D
: Decoder
> Decodable
<D
> for SyntaxContext
{
1287 default fn decode(_
: &mut D
) -> Result
<Self, D
::Error
> {
1288 panic
!("cannot decode `SyntaxContext` with `{}`", std
::any
::type_name
::<D
>());
1292 /// Updates the `disambiguator` field of the corresponding `ExpnData`
1293 /// such that the `Fingerprint` of the `ExpnData` does not collide with
1294 /// any other `ExpnIds`.
1296 /// This method is called only when an `ExpnData` is first associated
1297 /// with an `ExpnId` (when the `ExpnId` is initially constructed, or via
1298 /// `set_expn_data`). It is *not* called for foreign `ExpnId`s deserialized
1299 /// from another crate's metadata - since `ExpnData` includes a `krate` field,
1300 /// collisions are only possible between `ExpnId`s within the same crate.
1301 fn update_disambiguator(expn_id
: ExpnId
) {
1302 /// A `HashStableContext` which hashes the raw id values for `DefId`
1303 /// and `CrateNum`, rather than using their computed stable hash.
1305 /// This allows us to use the `HashStable` implementation on `ExpnId`
1306 /// early on in compilation, before we've constructed a `TyCtxt`.
1307 /// The `Fingerprint`s created by this context are not 'stable', since
1308 /// the raw `CrateNum` and `DefId` values for an item may change between
1309 /// sessions due to unrelated changes (e.g. adding/removing an different item).
1311 /// However, this is fine for our purposes - we only need to detect
1312 /// when two `ExpnData`s have the same `Fingerprint`. Since the hashes produced
1313 /// by this context still obey the properties of `HashStable`, we have
1315 /// `hash_stable(expn1, DummyHashStableContext) == hash_stable(expn2, DummyHashStableContext)`
1316 /// iff `hash_stable(expn1, StableHashingContext) == hash_stable(expn2, StableHasingContext)`.
1318 /// This is sufficient for determining when we need to update the disambiguator.
1319 struct DummyHashStableContext
<'a
> {
1320 caching_source_map
: CachingSourceMapView
<'a
>,
1323 impl<'a
> crate::HashStableContext
for DummyHashStableContext
<'a
> {
1324 fn hash_def_id(&mut self, def_id
: DefId
, hasher
: &mut StableHasher
) {
1325 def_id
.krate
.as_u32().hash_stable(self, hasher
);
1326 def_id
.index
.as_u32().hash_stable(self, hasher
);
1329 fn expn_id_cache() -> &'
static LocalKey
<ExpnIdCache
> {
1330 // This cache is only used by `DummyHashStableContext`,
1331 // so we won't pollute the cache values of the normal `StableHashingContext`
1333 static CACHE
: ExpnIdCache
= Default
::default();
1339 fn hash_crate_num(&mut self, krate
: CrateNum
, hasher
: &mut StableHasher
) {
1340 krate
.as_u32().hash_stable(self, hasher
);
1342 fn hash_spans(&self) -> bool
{
1345 fn span_data_to_lines_and_cols(
1347 span
: &crate::SpanData
,
1348 ) -> Option
<(Lrc
<SourceFile
>, usize, BytePos
, usize, BytePos
)> {
1349 self.caching_source_map
.span_data_to_lines_and_cols(span
)
1353 let source_map
= SESSION_GLOBALS
1354 .with(|session_globals
| session_globals
.source_map
.borrow().as_ref().unwrap().clone());
1357 DummyHashStableContext { caching_source_map: CachingSourceMapView::new(&source_map) }
;
1359 let mut hasher
= StableHasher
::new();
1361 let expn_data
= expn_id
.expn_data();
1362 // This disambiguator should not have been set yet.
1364 expn_data
.disambiguator
, 0,
1365 "Already set disambiguator for ExpnData: {:?}",
1368 expn_data
.hash_stable(&mut ctx
, &mut hasher
);
1369 let first_hash
= hasher
.finish();
1371 let modified
= HygieneData
::with(|data
| {
1372 // If this is the first ExpnData with a given hash, then keep our
1373 // disambiguator at 0 (the default u32 value)
1374 let disambig
= data
.expn_data_disambiguators
.entry(first_hash
).or_default();
1375 data
.expn_data
[expn_id
.0 as usize].as_mut().unwrap().disambiguator
= *disambig
;
1382 debug
!("Set disambiguator for {:?} (hash {:?})", expn_id
, first_hash
);
1383 debug
!("expn_data = {:?}", expn_id
.expn_data());
1385 // Verify that the new disambiguator makes the hash unique
1386 #[cfg(debug_assertions)]
1388 hasher
= StableHasher
::new();
1389 expn_id
.expn_data().hash_stable(&mut ctx
, &mut hasher
);
1390 let new_hash
: Fingerprint
= hasher
.finish();
1392 HygieneData
::with(|data
| {
1394 data
.expn_data_disambiguators
.get(&new_hash
),
1396 "Hash collision after disambiguator update!",