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