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