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