1 //! Machinery for hygienic macros.
3 //! Inspired by Matthew Flatt et al., “Macros That Work Together: Compile-Time Bindings, Partial
4 //! Expansion, and Definition Contexts,” *Journal of Functional Programming* 22, no. 2
5 //! (March 1, 2012): 181–216, <https://doi.org/10.1017/S0956796812000093>.
7 // Hygiene data is stored in a global variable and accessed via TLS, which
8 // means that accesses are somewhat expensive. (`HygieneData::with`
9 // encapsulates a single access.) Therefore, on hot code paths it is worth
10 // ensuring that multiple HygieneData accesses are combined into a single
11 // `HygieneData::with`.
13 // This explains why `HygieneData`, `SyntaxContext` and `ExpnId` have interfaces
14 // with a certain amount of redundancy in them. For example,
15 // `SyntaxContext::outer_expn_data` combines `SyntaxContext::outer` and
16 // `ExpnId::expn_data` so that two `HygieneData` accesses can be performed within
17 // a single `HygieneData::with` call.
19 // It also explains why many functions appear in `HygieneData` and again in
20 // `SyntaxContext` or `ExpnId`. For example, `HygieneData::outer` and
21 // `SyntaxContext::outer` do the same thing, but the former is for use within a
22 // `HygieneData::with` call while the latter is for use outside such a call.
23 // When modifying this file it is important to understand this distinction,
24 // because getting it wrong can lead to nested `HygieneData::with` calls that
25 // trigger runtime aborts. (Fortunately these are obvious and easy to fix.)
27 use crate::edition::Edition;
28 use crate::symbol::{kw, sym, Symbol};
29 use crate::SESSION_GLOBALS;
30 use crate::{BytePos, CachingSourceMapView, ExpnIdCache, SourceFile, Span, DUMMY_SP};
32 use crate::def_id::{CrateNum, DefId, DefPathHash, CRATE_DEF_INDEX, LOCAL_CRATE};
33 use rustc_data_structures::fingerprint::Fingerprint;
34 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
35 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
36 use rustc_data_structures::sync::{Lock, Lrc};
37 use rustc_macros::HashStable_Generic;
38 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
41 use std::thread::LocalKey;
44 /// A `SyntaxContext` represents a chain of pairs `(ExpnId, Transparency)` named "marks".
45 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
46 pub struct SyntaxContext(u32);
48 #[derive(Debug, Encodable, Decodable, Clone)]
49 pub struct SyntaxContextData {
51 outer_transparency: Transparency,
52 parent: SyntaxContext,
53 /// This context, but with all transparent and semi-transparent expansions filtered away.
54 opaque: SyntaxContext,
55 /// This context, but with all transparent expansions filtered away.
56 opaque_and_semitransparent: SyntaxContext,
57 /// Name of the crate to which `$crate` with this context would resolve.
58 dollar_crate_name: Symbol,
61 /// A unique ID associated with a macro invocation and expansion.
62 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
63 pub struct ExpnId(u32);
65 /// A property of a macro expansion that determines how identifiers
66 /// produced by that expansion are resolved.
67 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Hash, Debug, Encodable, Decodable)]
68 #[derive(HashStable_Generic)]
69 pub enum Transparency {
70 /// Identifier produced by a transparent expansion is always resolved at call-site.
71 /// Call-site spans in procedural macros, hygiene opt-out in `macro` should use this.
73 /// Identifier produced by a semi-transparent expansion may be resolved
74 /// either at call-site or at definition-site.
75 /// If it's a local variable, label or `$crate` then it's resolved at def-site.
76 /// Otherwise it's resolved at call-site.
77 /// `macro_rules` macros behave like this, built-in macros currently behave like this too,
78 /// but that's an implementation detail.
80 /// Identifier produced by an opaque expansion is always resolved at definition-site.
81 /// Def-site spans in procedural macros, identifiers from `macro` by default use this.
86 pub fn fresh(expn_data: Option<ExpnData>) -> Self {
87 let has_data = expn_data.is_some();
88 let expn_id = HygieneData::with(|data| data.fresh_expn(expn_data));
90 update_disambiguator(expn_id);
95 /// The ID of the theoretical expansion that generates freshly parsed, unexpanded AST.
97 pub fn root() -> Self {
102 pub fn as_u32(self) -> u32 {
107 pub fn from_u32(raw: u32) -> ExpnId {
112 pub fn expn_data(self) -> ExpnData {
113 HygieneData::with(|data| data.expn_data(self).clone())
117 pub fn set_expn_data(self, mut expn_data: ExpnData) {
118 HygieneData::with(|data| {
119 let old_expn_data = &mut data.expn_data[self.0 as usize];
120 assert!(old_expn_data.is_none(), "expansion data is reset for an expansion ID");
121 assert_eq!(expn_data.orig_id, None);
122 expn_data.orig_id = Some(self.as_u32());
123 *old_expn_data = Some(expn_data);
125 update_disambiguator(self)
128 pub fn is_descendant_of(self, ancestor: ExpnId) -> bool {
129 HygieneData::with(|data| data.is_descendant_of(self, ancestor))
132 /// `expn_id.outer_expn_is_descendant_of(ctxt)` is equivalent to but faster than
133 /// `expn_id.is_descendant_of(ctxt.outer_expn())`.
134 pub fn outer_expn_is_descendant_of(self, ctxt: SyntaxContext) -> bool {
135 HygieneData::with(|data| data.is_descendant_of(self, data.outer_expn(ctxt)))
138 /// Returns span for the macro which originally caused this expansion to happen.
140 /// Stops backtracing at include! boundary.
141 pub fn expansion_cause(mut self) -> Option<Span> {
142 let mut last_macro = None;
144 let expn_data = self.expn_data();
145 // Stop going up the backtrace once include! is encountered
146 if expn_data.is_root()
149 ExpnKind::Macro { kind: MacroKind::Bang, name: sym::include, proc_macro: _ }
154 self = expn_data.call_site.ctxt().outer_expn();
155 last_macro = Some(expn_data.call_site);
162 pub struct HygieneData {
163 /// Each expansion should have an associated expansion data, but sometimes there's a delay
164 /// between creation of an expansion ID and obtaining its data (e.g. macros are collected
165 /// first and then resolved later), so we use an `Option` here.
166 expn_data: Vec<Option<ExpnData>>,
167 syntax_context_data: Vec<SyntaxContextData>,
168 syntax_context_map: FxHashMap<(SyntaxContext, ExpnId, Transparency), SyntaxContext>,
169 /// Maps the `Fingerprint` of an `ExpnData` to the next disambiguator value.
170 /// This is used by `update_disambiguator` to keep track of which `ExpnData`s
171 /// would have collisions without a disambiguator.
172 /// The keys of this map are always computed with `ExpnData.disambiguator`
174 expn_data_disambiguators: FxHashMap<Fingerprint, u32>,
178 crate fn new(edition: Edition) -> Self {
179 let mut root_data = ExpnData::default(
183 Some(DefId::local(CRATE_DEF_INDEX)),
185 root_data.orig_id = Some(0);
188 expn_data: vec![Some(root_data)],
189 syntax_context_data: vec![SyntaxContextData {
190 outer_expn: ExpnId::root(),
191 outer_transparency: Transparency::Opaque,
192 parent: SyntaxContext(0),
193 opaque: SyntaxContext(0),
194 opaque_and_semitransparent: SyntaxContext(0),
195 dollar_crate_name: kw::DollarCrate,
197 syntax_context_map: FxHashMap::default(),
198 expn_data_disambiguators: FxHashMap::default(),
202 pub fn with<T, F: FnOnce(&mut HygieneData) -> T>(f: F) -> T {
203 SESSION_GLOBALS.with(|session_globals| f(&mut *session_globals.hygiene_data.borrow_mut()))
206 fn fresh_expn(&mut self, mut expn_data: Option<ExpnData>) -> ExpnId {
207 let raw_id = self.expn_data.len() as u32;
208 if let Some(data) = expn_data.as_mut() {
209 assert_eq!(data.orig_id, None);
210 data.orig_id = Some(raw_id);
212 self.expn_data.push(expn_data);
216 fn expn_data(&self, expn_id: ExpnId) -> &ExpnData {
217 self.expn_data[expn_id.0 as usize].as_ref().expect("no expansion data for an expansion ID")
220 fn is_descendant_of(&self, mut expn_id: ExpnId, ancestor: ExpnId) -> bool {
221 while expn_id != ancestor {
222 if expn_id == ExpnId::root() {
225 expn_id = self.expn_data(expn_id).parent;
230 fn normalize_to_macros_2_0(&self, ctxt: SyntaxContext) -> SyntaxContext {
231 self.syntax_context_data[ctxt.0 as usize].opaque
234 fn normalize_to_macro_rules(&self, ctxt: SyntaxContext) -> SyntaxContext {
235 self.syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent
238 fn outer_expn(&self, ctxt: SyntaxContext) -> ExpnId {
239 self.syntax_context_data[ctxt.0 as usize].outer_expn
242 fn outer_mark(&self, ctxt: SyntaxContext) -> (ExpnId, Transparency) {
243 let data = &self.syntax_context_data[ctxt.0 as usize];
244 (data.outer_expn, data.outer_transparency)
247 fn parent_ctxt(&self, ctxt: SyntaxContext) -> SyntaxContext {
248 self.syntax_context_data[ctxt.0 as usize].parent
251 fn remove_mark(&self, ctxt: &mut SyntaxContext) -> (ExpnId, Transparency) {
252 let outer_mark = self.outer_mark(*ctxt);
253 *ctxt = self.parent_ctxt(*ctxt);
257 fn marks(&self, mut ctxt: SyntaxContext) -> Vec<(ExpnId, Transparency)> {
258 let mut marks = Vec::new();
259 while ctxt != SyntaxContext::root() {
260 debug!("marks: getting parent of {:?}", ctxt);
261 marks.push(self.outer_mark(ctxt));
262 ctxt = self.parent_ctxt(ctxt);
268 fn walk_chain(&self, mut span: Span, to: SyntaxContext) -> Span {
269 debug!("walk_chain({:?}, {:?})", span, to);
270 debug!("walk_chain: span ctxt = {:?}", span.ctxt());
271 while span.from_expansion() && span.ctxt() != to {
272 let outer_expn = self.outer_expn(span.ctxt());
273 debug!("walk_chain({:?}): outer_expn={:?}", span, outer_expn);
274 let expn_data = self.expn_data(outer_expn);
275 debug!("walk_chain({:?}): expn_data={:?}", span, expn_data);
276 span = expn_data.call_site;
281 fn adjust(&self, ctxt: &mut SyntaxContext, expn_id: ExpnId) -> Option<ExpnId> {
282 let mut scope = None;
283 while !self.is_descendant_of(expn_id, self.outer_expn(*ctxt)) {
284 scope = Some(self.remove_mark(ctxt).0);
293 transparency: Transparency,
295 assert_ne!(expn_id, ExpnId::root());
296 if transparency == Transparency::Opaque {
297 return self.apply_mark_internal(ctxt, expn_id, transparency);
300 let call_site_ctxt = self.expn_data(expn_id).call_site.ctxt();
301 let mut call_site_ctxt = if transparency == Transparency::SemiTransparent {
302 self.normalize_to_macros_2_0(call_site_ctxt)
304 self.normalize_to_macro_rules(call_site_ctxt)
307 if call_site_ctxt == SyntaxContext::root() {
308 return self.apply_mark_internal(ctxt, expn_id, transparency);
311 // Otherwise, `expn_id` is a macros 1.0 definition and the call site is in a
312 // macros 2.0 expansion, i.e., a macros 1.0 invocation is in a macros 2.0 definition.
314 // In this case, the tokens from the macros 1.0 definition inherit the hygiene
315 // at their invocation. That is, we pretend that the macros 1.0 definition
316 // was defined at its invocation (i.e., inside the macros 2.0 definition)
317 // so that the macros 2.0 definition remains hygienic.
319 // See the example at `test/ui/hygiene/legacy_interaction.rs`.
320 for (expn_id, transparency) in self.marks(ctxt) {
321 call_site_ctxt = self.apply_mark_internal(call_site_ctxt, expn_id, transparency);
323 self.apply_mark_internal(call_site_ctxt, expn_id, transparency)
326 fn apply_mark_internal(
330 transparency: Transparency,
332 let syntax_context_data = &mut self.syntax_context_data;
333 let mut opaque = syntax_context_data[ctxt.0 as usize].opaque;
334 let mut opaque_and_semitransparent =
335 syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent;
337 if transparency >= Transparency::Opaque {
341 .entry((parent, expn_id, transparency))
343 let new_opaque = SyntaxContext(syntax_context_data.len() as u32);
344 syntax_context_data.push(SyntaxContextData {
346 outer_transparency: transparency,
349 opaque_and_semitransparent: new_opaque,
350 dollar_crate_name: kw::DollarCrate,
356 if transparency >= Transparency::SemiTransparent {
357 let parent = opaque_and_semitransparent;
358 opaque_and_semitransparent = *self
360 .entry((parent, expn_id, transparency))
362 let new_opaque_and_semitransparent =
363 SyntaxContext(syntax_context_data.len() as u32);
364 syntax_context_data.push(SyntaxContextData {
366 outer_transparency: transparency,
369 opaque_and_semitransparent: new_opaque_and_semitransparent,
370 dollar_crate_name: kw::DollarCrate,
372 new_opaque_and_semitransparent
377 *self.syntax_context_map.entry((parent, expn_id, transparency)).or_insert_with(|| {
378 let new_opaque_and_semitransparent_and_transparent =
379 SyntaxContext(syntax_context_data.len() as u32);
380 syntax_context_data.push(SyntaxContextData {
382 outer_transparency: transparency,
385 opaque_and_semitransparent,
386 dollar_crate_name: kw::DollarCrate,
388 new_opaque_and_semitransparent_and_transparent
393 pub fn clear_syntax_context_map() {
394 HygieneData::with(|data| data.syntax_context_map = FxHashMap::default());
397 pub fn walk_chain(span: Span, to: SyntaxContext) -> Span {
398 HygieneData::with(|data| data.walk_chain(span, to))
401 pub fn update_dollar_crate_names(mut get_name: impl FnMut(SyntaxContext) -> Symbol) {
402 // The new contexts that need updating are at the end of the list and have `$crate` as a name.
403 let (len, to_update) = HygieneData::with(|data| {
405 data.syntax_context_data.len(),
406 data.syntax_context_data
409 .take_while(|scdata| scdata.dollar_crate_name == kw::DollarCrate)
413 // The callback must be called from outside of the `HygieneData` lock,
414 // since it will try to acquire it too.
415 let range_to_update = len - to_update..len;
417 range_to_update.clone().map(|idx| get_name(SyntaxContext::from_u32(idx as u32))).collect();
418 HygieneData::with(|data| {
419 range_to_update.zip(names).for_each(|(idx, name)| {
420 data.syntax_context_data[idx].dollar_crate_name = name;
425 pub fn debug_hygiene_data(verbose: bool) -> String {
426 HygieneData::with(|data| {
428 format!("{:#?}", data)
430 let mut s = String::from("");
431 s.push_str("Expansions:");
432 data.expn_data.iter().enumerate().for_each(|(id, expn_info)| {
433 let expn_info = expn_info.as_ref().expect("no expansion data for an expansion ID");
435 "\n{}: parent: {:?}, call_site_ctxt: {:?}, def_site_ctxt: {:?}, kind: {:?}",
438 expn_info.call_site.ctxt(),
439 expn_info.def_site.ctxt(),
443 s.push_str("\n\nSyntaxContexts:");
444 data.syntax_context_data.iter().enumerate().for_each(|(id, ctxt)| {
446 "\n#{}: parent: {:?}, outer_mark: ({:?}, {:?})",
447 id, ctxt.parent, ctxt.outer_expn, ctxt.outer_transparency,
457 pub const fn root() -> Self {
462 crate fn as_u32(self) -> u32 {
467 crate fn from_u32(raw: u32) -> SyntaxContext {
471 /// Extend a syntax context with a given expansion and transparency.
472 crate fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> SyntaxContext {
473 HygieneData::with(|data| data.apply_mark(self, expn_id, transparency))
476 /// Pulls a single mark off of the syntax context. This effectively moves the
477 /// context up one macro definition level. That is, if we have a nested macro
478 /// definition as follows:
488 /// and we have a SyntaxContext that is referring to something declared by an invocation
489 /// of g (call it g1), calling remove_mark will result in the SyntaxContext for the
490 /// invocation of f that created g1.
491 /// Returns the mark that was removed.
492 pub fn remove_mark(&mut self) -> ExpnId {
493 HygieneData::with(|data| data.remove_mark(self).0)
496 pub fn marks(self) -> Vec<(ExpnId, Transparency)> {
497 HygieneData::with(|data| data.marks(self))
500 /// Adjust this context for resolution in a scope created by the given expansion.
501 /// For example, consider the following three resolutions of `f`:
504 /// mod foo { pub fn f() {} } // `f`'s `SyntaxContext` is empty.
506 /// macro m($f:ident) {
508 /// pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
509 /// pub fn $f() {} // `$f`'s `SyntaxContext` is empty.
511 /// foo::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
512 /// //^ Since `mod foo` is outside this expansion, `adjust` removes the mark from `f`,
513 /// //| and it resolves to `::foo::f`.
514 /// bar::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
515 /// //^ Since `mod bar` not outside this expansion, `adjust` does not change `f`,
516 /// //| and it resolves to `::bar::f`.
517 /// bar::$f(); // `f`'s `SyntaxContext` is empty.
518 /// //^ Since `mod bar` is not outside this expansion, `adjust` does not change `$f`,
519 /// //| and it resolves to `::bar::$f`.
522 /// This returns the expansion whose definition scope we use to privacy check the resolution,
523 /// or `None` if we privacy check as usual (i.e., not w.r.t. a macro definition scope).
524 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
525 HygieneData::with(|data| data.adjust(self, expn_id))
528 /// Like `SyntaxContext::adjust`, but also normalizes `self` to macros 2.0.
529 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
530 HygieneData::with(|data| {
531 *self = data.normalize_to_macros_2_0(*self);
532 data.adjust(self, expn_id)
536 /// Adjust this context for resolution in a scope created by the given expansion
537 /// via a glob import with the given `SyntaxContext`.
542 /// macro m($i:ident) {
544 /// pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
545 /// pub fn $i() {} // `$i`'s `SyntaxContext` is empty.
548 /// macro n($j:ident) {
550 /// f(); // `f`'s `SyntaxContext` has a mark from `m` and a mark from `n`
551 /// //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::f`.
552 /// $i(); // `$i`'s `SyntaxContext` has a mark from `n`
553 /// //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::$i`.
554 /// $j(); // `$j`'s `SyntaxContext` has a mark from `m`
555 /// //^ This cannot be glob-adjusted, so this is a resolution error.
559 /// This returns `None` if the context cannot be glob-adjusted.
560 /// Otherwise, it returns the scope to use when privacy checking (see `adjust` for details).
561 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
562 HygieneData::with(|data| {
563 let mut scope = None;
564 let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
565 while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
566 scope = Some(data.remove_mark(&mut glob_ctxt).0);
567 if data.remove_mark(self).0 != scope.unwrap() {
571 if data.adjust(self, expn_id).is_some() {
578 /// Undo `glob_adjust` if possible:
581 /// if let Some(privacy_checking_scope) = self.reverse_glob_adjust(expansion, glob_ctxt) {
582 /// assert!(self.glob_adjust(expansion, glob_ctxt) == Some(privacy_checking_scope));
585 pub fn reverse_glob_adjust(
589 ) -> Option<Option<ExpnId>> {
590 HygieneData::with(|data| {
591 if data.adjust(self, expn_id).is_some() {
595 let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
596 let mut marks = Vec::new();
597 while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
598 marks.push(data.remove_mark(&mut glob_ctxt));
601 let scope = marks.last().map(|mark| mark.0);
602 while let Some((expn_id, transparency)) = marks.pop() {
603 *self = data.apply_mark(*self, expn_id, transparency);
609 pub fn hygienic_eq(self, other: SyntaxContext, expn_id: ExpnId) -> bool {
610 HygieneData::with(|data| {
611 let mut self_normalized = data.normalize_to_macros_2_0(self);
612 data.adjust(&mut self_normalized, expn_id);
613 self_normalized == data.normalize_to_macros_2_0(other)
618 pub fn normalize_to_macros_2_0(self) -> SyntaxContext {
619 HygieneData::with(|data| data.normalize_to_macros_2_0(self))
623 pub fn normalize_to_macro_rules(self) -> SyntaxContext {
624 HygieneData::with(|data| data.normalize_to_macro_rules(self))
628 pub fn outer_expn(self) -> ExpnId {
629 HygieneData::with(|data| data.outer_expn(self))
632 /// `ctxt.outer_expn_data()` is equivalent to but faster than
633 /// `ctxt.outer_expn().expn_data()`.
635 pub fn outer_expn_data(self) -> ExpnData {
636 HygieneData::with(|data| data.expn_data(data.outer_expn(self)).clone())
640 pub fn outer_mark(self) -> (ExpnId, Transparency) {
641 HygieneData::with(|data| data.outer_mark(self))
644 pub fn dollar_crate_name(self) -> Symbol {
645 HygieneData::with(|data| data.syntax_context_data[self.0 as usize].dollar_crate_name)
648 pub fn edition(self) -> Edition {
649 self.outer_expn_data().edition
653 impl fmt::Debug for SyntaxContext {
654 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
655 write!(f, "#{}", self.0)
660 /// Creates a fresh expansion with given properties.
661 /// Expansions are normally created by macros, but in some cases expansions are created for
662 /// other compiler-generated code to set per-span properties like allowed unstable features.
663 /// The returned span belongs to the created expansion and has the new properties,
664 /// but its location is inherited from the current span.
665 pub fn fresh_expansion(self, expn_data: ExpnData) -> Span {
666 self.fresh_expansion_with_transparency(expn_data, Transparency::Transparent)
669 pub fn fresh_expansion_with_transparency(
672 transparency: Transparency,
674 let expn_id = ExpnId::fresh(Some(expn_data));
675 HygieneData::with(|data| {
676 self.with_ctxt(data.apply_mark(SyntaxContext::root(), expn_id, transparency))
680 /// Reuses the span but adds information like the kind of the desugaring and features that are
681 /// allowed inside this span.
682 pub fn mark_with_reason(
684 allow_internal_unstable: Option<Lrc<[Symbol]>>,
685 reason: DesugaringKind,
688 self.fresh_expansion(ExpnData {
689 allow_internal_unstable,
690 ..ExpnData::default(ExpnKind::Desugaring(reason), self, edition, None)
695 /// A subset of properties from both macro definition and macro call available through global data.
696 /// Avoid using this if you have access to the original definition or call structures.
697 #[derive(Clone, Debug, Encodable, Decodable, HashStable_Generic)]
698 pub struct ExpnData {
699 // --- The part unique to each expansion.
700 /// The kind of this expansion - macro or compiler desugaring.
702 /// The expansion that produced this expansion.
704 /// The location of the actual macro invocation or syntax sugar , e.g.
705 /// `let x = foo!();` or `if let Some(y) = x {}`
707 /// This may recursively refer to other macro invocations, e.g., if
708 /// `foo!()` invoked `bar!()` internally, and there was an
709 /// expression inside `bar!`; the call_site of the expression in
710 /// the expansion would point to the `bar!` invocation; that
711 /// call_site span would have its own ExpnData, with the call_site
712 /// pointing to the `foo!` invocation.
715 // --- The part specific to the macro/desugaring definition.
716 // --- It may be reasonable to share this part between expansions with the same definition,
717 // --- but such sharing is known to bring some minor inconveniences without also bringing
718 // --- noticeable perf improvements (PR #62898).
719 /// The span of the macro definition (possibly dummy).
720 /// This span serves only informational purpose and is not used for resolution.
722 /// List of `#[unstable]`/feature-gated features that the macro is allowed to use
723 /// internally without forcing the whole crate to opt-in
725 pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
726 /// Whether the macro is allowed to use `unsafe` internally
727 /// even if the user crate has `#![forbid(unsafe_code)]`.
728 pub allow_internal_unsafe: bool,
729 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`)
730 /// for a given macro.
731 pub local_inner_macros: bool,
732 /// Edition of the crate in which the macro is defined.
733 pub edition: Edition,
734 /// The `DefId` of the macro being invoked,
735 /// if this `ExpnData` corresponds to a macro invocation
736 pub macro_def_id: Option<DefId>,
737 /// The crate that originally created this `ExpnData`. During
738 /// metadata serialization, we only encode `ExpnData`s that were
739 /// created locally - when our serialized metadata is decoded,
740 /// foreign `ExpnId`s will have their `ExpnData` looked up
741 /// from the crate specified by `Crate
743 /// The raw that this `ExpnData` had in its original crate.
744 /// An `ExpnData` can be created before being assigned an `ExpnId`,
745 /// so this might be `None` until `set_expn_data` is called
746 // This is used only for serialization/deserialization purposes:
747 // two `ExpnData`s that differ only in their `orig_id` should
748 // be considered equivalent.
749 #[stable_hasher(ignore)]
750 orig_id: Option<u32>,
752 /// Used to force two `ExpnData`s to have different `Fingerprint`s.
753 /// Due to macro expansion, it's possible to end up with two `ExpnId`s
754 /// that have identical `ExpnData`s. This violates the contract of `HashStable`
755 /// - the two `ExpnId`s are not equal, but their `Fingerprint`s are equal
756 /// (since the numerical `ExpnId` value is not considered by the `HashStable`
759 /// The `disambiguator` field is set by `update_disambiguator` when two distinct
760 /// `ExpnId`s would end up with the same `Fingerprint`. Since `ExpnData` includes
761 /// a `krate` field, this value only needs to be unique within a single crate.
765 // These would require special handling of `orig_id`.
766 impl !PartialEq for ExpnData {}
767 impl !Hash for ExpnData {}
775 allow_internal_unstable: Option<Lrc<[Symbol]>>,
776 allow_internal_unsafe: bool,
777 local_inner_macros: bool,
779 macro_def_id: Option<DefId>,
786 allow_internal_unstable,
787 allow_internal_unsafe,
797 /// Constructs expansion data with default properties.
802 macro_def_id: Option<DefId>,
806 parent: ExpnId::root(),
809 allow_internal_unstable: None,
810 allow_internal_unsafe: false,
811 local_inner_macros: false,
820 pub fn allow_unstable(
824 allow_internal_unstable: Lrc<[Symbol]>,
825 macro_def_id: Option<DefId>,
828 allow_internal_unstable: Some(allow_internal_unstable),
829 ..ExpnData::default(kind, call_site, edition, macro_def_id)
834 pub fn is_root(&self) -> bool {
835 matches!(self.kind, ExpnKind::Root)
840 #[derive(Clone, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
842 /// No expansion, aka root expansion. Only `ExpnId::root()` has this kind.
844 /// Expansion produced by a macro.
848 /// If `true`, this macro is a procedural macro. This
849 /// flag is only used for diagnostic purposes
852 /// Transform done by the compiler on the AST.
854 /// Desugaring done by the compiler during HIR lowering.
855 Desugaring(DesugaringKind),
861 pub fn descr(&self) -> String {
863 ExpnKind::Root => kw::PathRoot.to_string(),
864 ExpnKind::Macro { kind, name, proc_macro: _ } => match kind {
865 MacroKind::Bang => format!("{}!", name),
866 MacroKind::Attr => format!("#[{}]", name),
867 MacroKind::Derive => format!("#[derive({})]", name),
869 ExpnKind::AstPass(kind) => kind.descr().to_string(),
870 ExpnKind::Desugaring(kind) => format!("desugaring of {}", kind.descr()),
871 ExpnKind::Inlined => "inlined source".to_string(),
876 /// The kind of macro invocation or definition.
877 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
878 #[derive(HashStable_Generic)]
880 /// A bang macro `foo!()`.
882 /// An attribute macro `#[foo]`.
884 /// A derive macro `#[derive(Foo)]`
889 pub fn descr(self) -> &'static str {
891 MacroKind::Bang => "macro",
892 MacroKind::Attr => "attribute macro",
893 MacroKind::Derive => "derive macro",
897 pub fn descr_expected(self) -> &'static str {
899 MacroKind::Attr => "attribute",
904 pub fn article(self) -> &'static str {
906 MacroKind::Attr => "an",
912 /// The kind of AST transform.
913 #[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
921 fn descr(self) -> &'static str {
923 AstPass::StdImports => "standard library imports",
924 AstPass::TestHarness => "test harness",
925 AstPass::ProcMacroHarness => "proc macro harness",
930 /// The kind of compiler desugaring.
931 #[derive(Clone, Copy, PartialEq, Debug, Encodable, Decodable, HashStable_Generic)]
932 pub enum DesugaringKind {
933 /// We desugar `if c { i } else { e }` to `match $ExprKind::Use(c) { true => i, _ => e }`.
934 /// However, we do not want to blame `c` for unreachability but rather say that `i`
935 /// is unreachable. This desugaring kind allows us to avoid blaming `c`.
936 /// This also applies to `while` loops.
940 /// Desugaring of an `impl Trait` in return type position
941 /// to an `type Foo = impl Trait;` and replacing the
942 /// `impl Trait` with `Foo`.
949 /// A location in the desugaring of a `for` loop
950 #[derive(Clone, Copy, PartialEq, Debug, Encodable, Decodable, HashStable_Generic)]
951 pub enum ForLoopLoc {
956 impl DesugaringKind {
957 /// The description wording should combine well with "desugaring of {}".
958 fn descr(self) -> &'static str {
960 DesugaringKind::CondTemporary => "`if` or `while` condition",
961 DesugaringKind::Async => "`async` block or function",
962 DesugaringKind::Await => "`await` expression",
963 DesugaringKind::QuestionMark => "operator `?`",
964 DesugaringKind::TryBlock => "`try` block",
965 DesugaringKind::OpaqueTy => "`impl Trait`",
966 DesugaringKind::ForLoop(_) => "`for` loop",
972 pub struct HygieneEncodeContext {
973 /// All `SyntaxContexts` for which we have written `SyntaxContextData` into crate metadata.
974 /// This is `None` after we finish encoding `SyntaxContexts`, to ensure
975 /// that we don't accidentally try to encode any more `SyntaxContexts`
976 serialized_ctxts: Lock<FxHashSet<SyntaxContext>>,
977 /// The `SyntaxContexts` that we have serialized (e.g. as a result of encoding `Spans`)
978 /// in the most recent 'round' of serializnig. Serializing `SyntaxContextData`
979 /// may cause us to serialize more `SyntaxContext`s, so serialize in a loop
980 /// until we reach a fixed point.
981 latest_ctxts: Lock<FxHashSet<SyntaxContext>>,
983 serialized_expns: Lock<FxHashSet<ExpnId>>,
985 latest_expns: Lock<FxHashSet<ExpnId>>,
988 impl HygieneEncodeContext {
992 F: FnMut(&mut T, u32, &SyntaxContextData) -> Result<(), R>,
993 G: FnMut(&mut T, u32, &ExpnData) -> Result<(), R>,
1000 // When we serialize a `SyntaxContextData`, we may end up serializing
1001 // a `SyntaxContext` that we haven't seen before
1002 while !self.latest_ctxts.lock().is_empty() || !self.latest_expns.lock().is_empty() {
1004 "encode_hygiene: Serializing a round of {:?} SyntaxContextDatas: {:?}",
1005 self.latest_ctxts.lock().len(),
1009 // Consume the current round of SyntaxContexts.
1010 // Drop the lock() temporary early
1011 let latest_ctxts = { std::mem::take(&mut *self.latest_ctxts.lock()) };
1013 // It's fine to iterate over a HashMap, because the serialization
1014 // of the table that we insert data into doesn't depend on insertion
1016 for_all_ctxts_in(latest_ctxts.into_iter(), |(index, ctxt, data)| {
1017 if self.serialized_ctxts.lock().insert(ctxt) {
1018 encode_ctxt(encoder, index, data)?;
1023 let latest_expns = { std::mem::take(&mut *self.latest_expns.lock()) };
1025 for_all_expns_in(latest_expns.into_iter(), |index, expn, data| {
1026 if self.serialized_expns.lock().insert(expn) {
1027 encode_expn(encoder, index, data)?;
1032 debug!("encode_hygiene: Done serializing SyntaxContextData");
1038 /// Additional information used to assist in decoding hygiene data
1039 pub struct HygieneDecodeContext {
1040 // Maps serialized `SyntaxContext` ids to a `SyntaxContext` in the current
1041 // global `HygieneData`. When we deserialize a `SyntaxContext`, we need to create
1042 // a new id in the global `HygieneData`. This map tracks the ID we end up picking,
1043 // so that multiple occurrences of the same serialized id are decoded to the same
1045 remapped_ctxts: Lock<Vec<Option<SyntaxContext>>>,
1046 // The same as `remapepd_ctxts`, but for `ExpnId`s
1047 remapped_expns: Lock<Vec<Option<ExpnId>>>,
1050 pub fn decode_expn_id<
1053 F: FnOnce(&mut D, u32) -> Result<ExpnData, D::Error>,
1054 G: FnOnce(CrateNum) -> &'a HygieneDecodeContext,
1057 mode: ExpnDataDecodeMode<'a, G>,
1059 ) -> Result<ExpnId, D::Error> {
1060 let index = u32::decode(d)?;
1061 let context = match mode {
1062 ExpnDataDecodeMode::IncrComp(context) => context,
1063 ExpnDataDecodeMode::Metadata(get_context) => {
1064 let krate = CrateNum::decode(d)?;
1069 // Do this after decoding, so that we decode a `CrateNum`
1071 if index == ExpnId::root().as_u32() {
1072 debug!("decode_expn_id: deserialized root");
1073 return Ok(ExpnId::root());
1076 let outer_expns = &context.remapped_expns;
1078 // Ensure that the lock() temporary is dropped early
1080 if let Some(expn_id) = outer_expns.lock().get(index as usize).copied().flatten() {
1085 // Don't decode the data inside `HygieneData::with`, since we need to recursively decode
1087 let mut expn_data = decode_data(d, index)?;
1089 let expn_id = HygieneData::with(|hygiene_data| {
1090 let expn_id = ExpnId(hygiene_data.expn_data.len() as u32);
1092 // If we just deserialized an `ExpnData` owned by
1093 // the local crate, its `orig_id` will be stale,
1094 // so we need to update it to its own value.
1095 // This only happens when we deserialize the incremental cache,
1096 // since a crate will never decode its own metadata.
1097 if expn_data.krate == LOCAL_CRATE {
1098 expn_data.orig_id = Some(expn_id.0);
1101 hygiene_data.expn_data.push(Some(expn_data));
1103 let mut expns = outer_expns.lock();
1104 let new_len = index as usize + 1;
1105 if expns.len() < new_len {
1106 expns.resize(new_len, None);
1108 expns[index as usize] = Some(expn_id);
1115 // Decodes `SyntaxContext`, using the provided `HygieneDecodeContext`
1116 // to track which `SyntaxContext`s we have already decoded.
1117 // The provided closure will be invoked to deserialize a `SyntaxContextData`
1118 // if we haven't already seen the id of the `SyntaxContext` we are deserializing.
1119 pub fn decode_syntax_context<
1121 F: FnOnce(&mut D, u32) -> Result<SyntaxContextData, D::Error>,
1124 context: &HygieneDecodeContext,
1126 ) -> Result<SyntaxContext, D::Error> {
1127 let raw_id: u32 = Decodable::decode(d)?;
1129 debug!("decode_syntax_context: deserialized root");
1130 // The root is special
1131 return Ok(SyntaxContext::root());
1134 let outer_ctxts = &context.remapped_ctxts;
1136 // Ensure that the lock() temporary is dropped early
1138 if let Some(ctxt) = outer_ctxts.lock().get(raw_id as usize).copied().flatten() {
1143 // Allocate and store SyntaxContext id *before* calling the decoder function,
1144 // as the SyntaxContextData may reference itself.
1145 let new_ctxt = HygieneData::with(|hygiene_data| {
1146 let new_ctxt = SyntaxContext(hygiene_data.syntax_context_data.len() as u32);
1147 // Push a dummy SyntaxContextData to ensure that nobody else can get the
1148 // same ID as us. This will be overwritten after call `decode_Data`
1149 hygiene_data.syntax_context_data.push(SyntaxContextData {
1150 outer_expn: ExpnId::root(),
1151 outer_transparency: Transparency::Transparent,
1152 parent: SyntaxContext::root(),
1153 opaque: SyntaxContext::root(),
1154 opaque_and_semitransparent: SyntaxContext::root(),
1155 dollar_crate_name: kw::Empty,
1157 let mut ctxts = outer_ctxts.lock();
1158 let new_len = raw_id as usize + 1;
1159 if ctxts.len() < new_len {
1160 ctxts.resize(new_len, None);
1162 ctxts[raw_id as usize] = Some(new_ctxt);
1167 // Don't try to decode data while holding the lock, since we need to
1168 // be able to recursively decode a SyntaxContext
1169 let mut ctxt_data = decode_data(d, raw_id)?;
1170 // Reset `dollar_crate_name` so that it will be updated by `update_dollar_crate_names`
1171 // We don't care what the encoding crate set this to - we want to resolve it
1172 // from the perspective of the current compilation session
1173 ctxt_data.dollar_crate_name = kw::DollarCrate;
1175 // Overwrite the dummy data with our decoded SyntaxContextData
1176 HygieneData::with(|hygiene_data| {
1177 let dummy = std::mem::replace(
1178 &mut hygiene_data.syntax_context_data[new_ctxt.as_u32() as usize],
1181 // Make sure nothing weird happening while `decode_data` was running
1182 assert_eq!(dummy.dollar_crate_name, kw::Empty);
1188 fn for_all_ctxts_in<E, F: FnMut((u32, SyntaxContext, &SyntaxContextData)) -> Result<(), E>>(
1189 ctxts: impl Iterator<Item = SyntaxContext>,
1191 ) -> Result<(), E> {
1192 let all_data: Vec<_> = HygieneData::with(|data| {
1193 ctxts.map(|ctxt| (ctxt, data.syntax_context_data[ctxt.0 as usize].clone())).collect()
1195 for (ctxt, data) in all_data.into_iter() {
1196 f((ctxt.0, ctxt, &data))?;
1201 fn for_all_expns_in<E, F: FnMut(u32, ExpnId, &ExpnData) -> Result<(), E>>(
1202 expns: impl Iterator<Item = ExpnId>,
1204 ) -> Result<(), E> {
1205 let all_data: Vec<_> = HygieneData::with(|data| {
1206 expns.map(|expn| (expn, data.expn_data[expn.0 as usize].clone())).collect()
1208 for (expn, data) in all_data.into_iter() {
1209 f(expn.0, expn, &data.unwrap_or_else(|| panic!("Missing data for {:?}", expn)))?;
1214 impl<E: Encoder> Encodable<E> for ExpnId {
1215 default fn encode(&self, _: &mut E) -> Result<(), E::Error> {
1216 panic!("cannot encode `ExpnId` with `{}`", std::any::type_name::<E>());
1220 impl<D: Decoder> Decodable<D> for ExpnId {
1221 default fn decode(_: &mut D) -> Result<Self, D::Error> {
1222 panic!("cannot decode `ExpnId` with `{}`", std::any::type_name::<D>());
1226 pub fn raw_encode_syntax_context<E: Encoder>(
1227 ctxt: SyntaxContext,
1228 context: &HygieneEncodeContext,
1230 ) -> Result<(), E::Error> {
1231 if !context.serialized_ctxts.lock().contains(&ctxt) {
1232 context.latest_ctxts.lock().insert(ctxt);
1237 pub fn raw_encode_expn_id<E: Encoder>(
1239 context: &HygieneEncodeContext,
1240 mode: ExpnDataEncodeMode,
1242 ) -> Result<(), E::Error> {
1243 // Record the fact that we need to serialize the corresponding
1245 let needs_data = || {
1246 if !context.serialized_expns.lock().contains(&expn) {
1247 context.latest_expns.lock().insert(expn);
1252 ExpnDataEncodeMode::IncrComp => {
1253 // Always serialize the `ExpnData` in incr comp mode
1257 ExpnDataEncodeMode::Metadata => {
1258 let data = expn.expn_data();
1259 // We only need to serialize the ExpnData
1260 // if it comes from this crate.
1261 // We currently don't serialize any hygiene information data for
1262 // proc-macro crates: see the `SpecializedEncoder<Span>` impl
1263 // for crate metadata.
1264 if data.krate == LOCAL_CRATE {
1267 data.orig_id.expect("Missing orig_id").encode(e)?;
1268 data.krate.encode(e)
1273 pub enum ExpnDataEncodeMode {
1278 pub enum ExpnDataDecodeMode<'a, F: FnOnce(CrateNum) -> &'a HygieneDecodeContext> {
1279 IncrComp(&'a HygieneDecodeContext),
1283 impl<'a> ExpnDataDecodeMode<'a, Box<dyn FnOnce(CrateNum) -> &'a HygieneDecodeContext>> {
1284 pub fn incr_comp(ctxt: &'a HygieneDecodeContext) -> Self {
1285 ExpnDataDecodeMode::IncrComp(ctxt)
1289 impl<E: Encoder> Encodable<E> for SyntaxContext {
1290 default fn encode(&self, _: &mut E) -> Result<(), E::Error> {
1291 panic!("cannot encode `SyntaxContext` with `{}`", std::any::type_name::<E>());
1295 impl<D: Decoder> Decodable<D> for SyntaxContext {
1296 default fn decode(_: &mut D) -> Result<Self, D::Error> {
1297 panic!("cannot decode `SyntaxContext` with `{}`", std::any::type_name::<D>());
1301 /// Updates the `disambiguator` field of the corresponding `ExpnData`
1302 /// such that the `Fingerprint` of the `ExpnData` does not collide with
1303 /// any other `ExpnIds`.
1305 /// This method is called only when an `ExpnData` is first associated
1306 /// with an `ExpnId` (when the `ExpnId` is initially constructed, or via
1307 /// `set_expn_data`). It is *not* called for foreign `ExpnId`s deserialized
1308 /// from another crate's metadata - since `ExpnData` includes a `krate` field,
1309 /// collisions are only possible between `ExpnId`s within the same crate.
1310 fn update_disambiguator(expn_id: ExpnId) {
1311 /// A `HashStableContext` which hashes the raw id values for `DefId`
1312 /// and `CrateNum`, rather than using their computed stable hash.
1314 /// This allows us to use the `HashStable` implementation on `ExpnId`
1315 /// early on in compilation, before we've constructed a `TyCtxt`.
1316 /// The `Fingerprint`s created by this context are not 'stable', since
1317 /// the raw `CrateNum` and `DefId` values for an item may change between
1318 /// sessions due to unrelated changes (e.g. adding/removing an different item).
1320 /// However, this is fine for our purposes - we only need to detect
1321 /// when two `ExpnData`s have the same `Fingerprint`. Since the hashes produced
1322 /// by this context still obey the properties of `HashStable`, we have
1324 /// `hash_stable(expn1, DummyHashStableContext) == hash_stable(expn2, DummyHashStableContext)`
1325 /// iff `hash_stable(expn1, StableHashingContext) == hash_stable(expn2, StableHasingContext)`.
1327 /// This is sufficient for determining when we need to update the disambiguator.
1328 struct DummyHashStableContext<'a> {
1329 caching_source_map: CachingSourceMapView<'a>,
1332 impl<'a> crate::HashStableContext for DummyHashStableContext<'a> {
1334 fn def_path_hash(&self, def_id: DefId) -> DefPathHash {
1335 DefPathHash(Fingerprint::new(
1336 def_id.krate.as_u32().into(),
1337 def_id.index.as_u32().into(),
1341 fn expn_id_cache() -> &'static LocalKey<ExpnIdCache> {
1342 // This cache is only used by `DummyHashStableContext`,
1343 // so we won't pollute the cache values of the normal `StableHashingContext`
1345 static CACHE: ExpnIdCache = const { ExpnIdCache::new(Vec::new()) };
1351 fn hash_spans(&self) -> bool {
1354 fn span_data_to_lines_and_cols(
1356 span: &crate::SpanData,
1357 ) -> Option<(Lrc<SourceFile>, usize, BytePos, usize, BytePos)> {
1358 self.caching_source_map.span_data_to_lines_and_cols(span)
1362 let source_map = SESSION_GLOBALS
1363 .with(|session_globals| session_globals.source_map.borrow().as_ref().unwrap().clone());
1366 DummyHashStableContext { caching_source_map: CachingSourceMapView::new(&source_map) };
1368 let mut hasher = StableHasher::new();
1370 let expn_data = expn_id.expn_data();
1371 // This disambiguator should not have been set yet.
1373 expn_data.disambiguator, 0,
1374 "Already set disambiguator for ExpnData: {:?}",
1377 expn_data.hash_stable(&mut ctx, &mut hasher);
1378 let first_hash = hasher.finish();
1380 let modified = HygieneData::with(|data| {
1381 // If this is the first ExpnData with a given hash, then keep our
1382 // disambiguator at 0 (the default u32 value)
1383 let disambig = data.expn_data_disambiguators.entry(first_hash).or_default();
1384 data.expn_data[expn_id.0 as usize].as_mut().unwrap().disambiguator = *disambig;
1391 debug!("Set disambiguator for {:?} (hash {:?})", expn_id, first_hash);
1392 debug!("expn_data = {:?}", expn_id.expn_data());
1394 // Verify that the new disambiguator makes the hash unique
1395 #[cfg(debug_assertions)]
1397 hasher = StableHasher::new();
1398 expn_id.expn_data().hash_stable(&mut ctx, &mut hasher);
1399 let new_hash: Fingerprint = hasher.finish();
1401 HygieneData::with(|data| {
1403 data.expn_data_disambiguators.get(&new_hash),
1405 "Hash collision after disambiguator update!",