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::{Span, DUMMY_SP};
32 use crate::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
33 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
34 use rustc_data_structures::sync::{Lock, Lrc};
35 use rustc_macros::HashStable_Generic;
36 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
40 /// A `SyntaxContext` represents a chain of pairs `(ExpnId, Transparency)` named "marks".
41 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
42 pub struct SyntaxContext(u32);
44 #[derive(Debug, Encodable, Decodable, Clone)]
45 pub struct SyntaxContextData {
47 outer_transparency: Transparency,
48 parent: SyntaxContext,
49 /// This context, but with all transparent and semi-transparent expansions filtered away.
50 opaque: SyntaxContext,
51 /// This context, but with all transparent expansions filtered away.
52 opaque_and_semitransparent: SyntaxContext,
53 /// Name of the crate to which `$crate` with this context would resolve.
54 dollar_crate_name: Symbol,
57 /// A unique ID associated with a macro invocation and expansion.
58 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
59 pub struct ExpnId(u32);
61 /// A property of a macro expansion that determines how identifiers
62 /// produced by that expansion are resolved.
63 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Hash, Debug, Encodable, Decodable)]
64 #[derive(HashStable_Generic)]
65 pub enum Transparency {
66 /// Identifier produced by a transparent expansion is always resolved at call-site.
67 /// Call-site spans in procedural macros, hygiene opt-out in `macro` should use this.
69 /// Identifier produced by a semi-transparent expansion may be resolved
70 /// either at call-site or at definition-site.
71 /// If it's a local variable, label or `$crate` then it's resolved at def-site.
72 /// Otherwise it's resolved at call-site.
73 /// `macro_rules` macros behave like this, built-in macros currently behave like this too,
74 /// but that's an implementation detail.
76 /// Identifier produced by an opaque expansion is always resolved at definition-site.
77 /// Def-site spans in procedural macros, identifiers from `macro` by default use this.
82 pub fn fresh(expn_data: Option<ExpnData>) -> Self {
83 HygieneData::with(|data| data.fresh_expn(expn_data))
86 /// The ID of the theoretical expansion that generates freshly parsed, unexpanded AST.
88 pub fn root() -> Self {
93 pub fn as_u32(self) -> u32 {
98 pub fn from_u32(raw: u32) -> ExpnId {
103 pub fn expn_data(self) -> ExpnData {
104 HygieneData::with(|data| data.expn_data(self).clone())
108 pub fn set_expn_data(self, mut expn_data: ExpnData) {
109 HygieneData::with(|data| {
110 let old_expn_data = &mut data.expn_data[self.0 as usize];
111 assert!(old_expn_data.is_none(), "expansion data is reset for an expansion ID");
112 expn_data.orig_id.replace(self.as_u32()).expect_none("orig_id should be None");
113 *old_expn_data = Some(expn_data);
117 pub fn is_descendant_of(self, ancestor: ExpnId) -> bool {
118 HygieneData::with(|data| data.is_descendant_of(self, ancestor))
121 /// `expn_id.outer_expn_is_descendant_of(ctxt)` is equivalent to but faster than
122 /// `expn_id.is_descendant_of(ctxt.outer_expn())`.
123 pub fn outer_expn_is_descendant_of(self, ctxt: SyntaxContext) -> bool {
124 HygieneData::with(|data| data.is_descendant_of(self, data.outer_expn(ctxt)))
127 /// Returns span for the macro which originally caused this expansion to happen.
129 /// Stops backtracing at include! boundary.
130 pub fn expansion_cause(mut self) -> Option<Span> {
131 let mut last_macro = None;
133 let expn_data = self.expn_data();
134 // Stop going up the backtrace once include! is encountered
135 if expn_data.is_root()
136 || expn_data.kind == ExpnKind::Macro(MacroKind::Bang, sym::include)
140 self = expn_data.call_site.ctxt().outer_expn();
141 last_macro = Some(expn_data.call_site);
148 pub struct HygieneData {
149 /// Each expansion should have an associated expansion data, but sometimes there's a delay
150 /// between creation of an expansion ID and obtaining its data (e.g. macros are collected
151 /// first and then resolved later), so we use an `Option` here.
152 expn_data: Vec<Option<ExpnData>>,
153 syntax_context_data: Vec<SyntaxContextData>,
154 syntax_context_map: FxHashMap<(SyntaxContext, ExpnId, Transparency), SyntaxContext>,
158 crate fn new(edition: Edition) -> Self {
159 let mut root_data = ExpnData::default(
163 Some(DefId::local(CRATE_DEF_INDEX)),
165 root_data.orig_id = Some(0);
168 expn_data: vec![Some(root_data)],
169 syntax_context_data: vec![SyntaxContextData {
170 outer_expn: ExpnId::root(),
171 outer_transparency: Transparency::Opaque,
172 parent: SyntaxContext(0),
173 opaque: SyntaxContext(0),
174 opaque_and_semitransparent: SyntaxContext(0),
175 dollar_crate_name: kw::DollarCrate,
177 syntax_context_map: FxHashMap::default(),
181 pub fn with<T, F: FnOnce(&mut HygieneData) -> T>(f: F) -> T {
182 SESSION_GLOBALS.with(|session_globals| f(&mut *session_globals.hygiene_data.borrow_mut()))
185 fn fresh_expn(&mut self, mut expn_data: Option<ExpnData>) -> ExpnId {
186 let raw_id = self.expn_data.len() as u32;
187 if let Some(data) = expn_data.as_mut() {
188 data.orig_id.replace(raw_id).expect_none("orig_id should be None");
190 self.expn_data.push(expn_data);
194 fn expn_data(&self, expn_id: ExpnId) -> &ExpnData {
195 self.expn_data[expn_id.0 as usize].as_ref().expect("no expansion data for an expansion ID")
198 fn is_descendant_of(&self, mut expn_id: ExpnId, ancestor: ExpnId) -> bool {
199 while expn_id != ancestor {
200 if expn_id == ExpnId::root() {
203 expn_id = self.expn_data(expn_id).parent;
208 fn normalize_to_macros_2_0(&self, ctxt: SyntaxContext) -> SyntaxContext {
209 self.syntax_context_data[ctxt.0 as usize].opaque
212 fn normalize_to_macro_rules(&self, ctxt: SyntaxContext) -> SyntaxContext {
213 self.syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent
216 fn outer_expn(&self, ctxt: SyntaxContext) -> ExpnId {
217 self.syntax_context_data[ctxt.0 as usize].outer_expn
220 fn outer_mark(&self, ctxt: SyntaxContext) -> (ExpnId, Transparency) {
221 let data = &self.syntax_context_data[ctxt.0 as usize];
222 (data.outer_expn, data.outer_transparency)
225 fn parent_ctxt(&self, ctxt: SyntaxContext) -> SyntaxContext {
226 self.syntax_context_data[ctxt.0 as usize].parent
229 fn remove_mark(&self, ctxt: &mut SyntaxContext) -> (ExpnId, Transparency) {
230 let outer_mark = self.outer_mark(*ctxt);
231 *ctxt = self.parent_ctxt(*ctxt);
235 fn marks(&self, mut ctxt: SyntaxContext) -> Vec<(ExpnId, Transparency)> {
236 let mut marks = Vec::new();
237 while ctxt != SyntaxContext::root() {
238 debug!("marks: getting parent of {:?}", ctxt);
239 marks.push(self.outer_mark(ctxt));
240 ctxt = self.parent_ctxt(ctxt);
246 fn walk_chain(&self, mut span: Span, to: SyntaxContext) -> Span {
247 debug!("walk_chain({:?}, {:?})", span, to);
248 debug!("walk_chain: span ctxt = {:?}", span.ctxt());
249 while span.from_expansion() && span.ctxt() != to {
250 let outer_expn = self.outer_expn(span.ctxt());
251 debug!("walk_chain({:?}): outer_expn={:?}", span, outer_expn);
252 let expn_data = self.expn_data(outer_expn);
253 debug!("walk_chain({:?}): expn_data={:?}", span, expn_data);
254 span = expn_data.call_site;
259 fn adjust(&self, ctxt: &mut SyntaxContext, expn_id: ExpnId) -> Option<ExpnId> {
260 let mut scope = None;
261 while !self.is_descendant_of(expn_id, self.outer_expn(*ctxt)) {
262 scope = Some(self.remove_mark(ctxt).0);
271 transparency: Transparency,
273 assert_ne!(expn_id, ExpnId::root());
274 if transparency == Transparency::Opaque {
275 return self.apply_mark_internal(ctxt, expn_id, transparency);
278 let call_site_ctxt = self.expn_data(expn_id).call_site.ctxt();
279 let mut call_site_ctxt = if transparency == Transparency::SemiTransparent {
280 self.normalize_to_macros_2_0(call_site_ctxt)
282 self.normalize_to_macro_rules(call_site_ctxt)
285 if call_site_ctxt == SyntaxContext::root() {
286 return self.apply_mark_internal(ctxt, expn_id, transparency);
289 // Otherwise, `expn_id` is a macros 1.0 definition and the call site is in a
290 // macros 2.0 expansion, i.e., a macros 1.0 invocation is in a macros 2.0 definition.
292 // In this case, the tokens from the macros 1.0 definition inherit the hygiene
293 // at their invocation. That is, we pretend that the macros 1.0 definition
294 // was defined at its invocation (i.e., inside the macros 2.0 definition)
295 // so that the macros 2.0 definition remains hygienic.
297 // See the example at `test/ui/hygiene/legacy_interaction.rs`.
298 for (expn_id, transparency) in self.marks(ctxt) {
299 call_site_ctxt = self.apply_mark_internal(call_site_ctxt, expn_id, transparency);
301 self.apply_mark_internal(call_site_ctxt, expn_id, transparency)
304 fn apply_mark_internal(
308 transparency: Transparency,
310 let syntax_context_data = &mut self.syntax_context_data;
311 let mut opaque = syntax_context_data[ctxt.0 as usize].opaque;
312 let mut opaque_and_semitransparent =
313 syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent;
315 if transparency >= Transparency::Opaque {
319 .entry((parent, expn_id, transparency))
321 let new_opaque = SyntaxContext(syntax_context_data.len() as u32);
322 syntax_context_data.push(SyntaxContextData {
324 outer_transparency: transparency,
327 opaque_and_semitransparent: new_opaque,
328 dollar_crate_name: kw::DollarCrate,
334 if transparency >= Transparency::SemiTransparent {
335 let parent = opaque_and_semitransparent;
336 opaque_and_semitransparent = *self
338 .entry((parent, expn_id, transparency))
340 let new_opaque_and_semitransparent =
341 SyntaxContext(syntax_context_data.len() as u32);
342 syntax_context_data.push(SyntaxContextData {
344 outer_transparency: transparency,
347 opaque_and_semitransparent: new_opaque_and_semitransparent,
348 dollar_crate_name: kw::DollarCrate,
350 new_opaque_and_semitransparent
355 *self.syntax_context_map.entry((parent, expn_id, transparency)).or_insert_with(|| {
356 let new_opaque_and_semitransparent_and_transparent =
357 SyntaxContext(syntax_context_data.len() as u32);
358 syntax_context_data.push(SyntaxContextData {
360 outer_transparency: transparency,
363 opaque_and_semitransparent,
364 dollar_crate_name: kw::DollarCrate,
366 new_opaque_and_semitransparent_and_transparent
371 pub fn clear_syntax_context_map() {
372 HygieneData::with(|data| data.syntax_context_map = FxHashMap::default());
375 pub fn walk_chain(span: Span, to: SyntaxContext) -> Span {
376 HygieneData::with(|data| data.walk_chain(span, to))
379 pub fn update_dollar_crate_names(mut get_name: impl FnMut(SyntaxContext) -> Symbol) {
380 // The new contexts that need updating are at the end of the list and have `$crate` as a name.
381 let (len, to_update) = HygieneData::with(|data| {
383 data.syntax_context_data.len(),
384 data.syntax_context_data
387 .take_while(|scdata| scdata.dollar_crate_name == kw::DollarCrate)
391 // The callback must be called from outside of the `HygieneData` lock,
392 // since it will try to acquire it too.
393 let range_to_update = len - to_update..len;
395 range_to_update.clone().map(|idx| get_name(SyntaxContext::from_u32(idx as u32))).collect();
396 HygieneData::with(|data| {
397 range_to_update.zip(names.into_iter()).for_each(|(idx, name)| {
398 data.syntax_context_data[idx].dollar_crate_name = name;
403 pub fn debug_hygiene_data(verbose: bool) -> String {
404 HygieneData::with(|data| {
406 format!("{:#?}", data)
408 let mut s = String::from("");
409 s.push_str("Expansions:");
410 data.expn_data.iter().enumerate().for_each(|(id, expn_info)| {
411 let expn_info = expn_info.as_ref().expect("no expansion data for an expansion ID");
413 "\n{}: parent: {:?}, call_site_ctxt: {:?}, def_site_ctxt: {:?}, kind: {:?}",
416 expn_info.call_site.ctxt(),
417 expn_info.def_site.ctxt(),
421 s.push_str("\n\nSyntaxContexts:");
422 data.syntax_context_data.iter().enumerate().for_each(|(id, ctxt)| {
424 "\n#{}: parent: {:?}, outer_mark: ({:?}, {:?})",
425 id, ctxt.parent, ctxt.outer_expn, ctxt.outer_transparency,
435 pub const fn root() -> Self {
440 crate fn as_u32(self) -> u32 {
445 crate fn from_u32(raw: u32) -> SyntaxContext {
449 /// Extend a syntax context with a given expansion and transparency.
450 crate fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> SyntaxContext {
451 HygieneData::with(|data| data.apply_mark(self, expn_id, transparency))
454 /// Pulls a single mark off of the syntax context. This effectively moves the
455 /// context up one macro definition level. That is, if we have a nested macro
456 /// definition as follows:
466 /// and we have a SyntaxContext that is referring to something declared by an invocation
467 /// of g (call it g1), calling remove_mark will result in the SyntaxContext for the
468 /// invocation of f that created g1.
469 /// Returns the mark that was removed.
470 pub fn remove_mark(&mut self) -> ExpnId {
471 HygieneData::with(|data| data.remove_mark(self).0)
474 pub fn marks(self) -> Vec<(ExpnId, Transparency)> {
475 HygieneData::with(|data| data.marks(self))
478 /// Adjust this context for resolution in a scope created by the given expansion.
479 /// For example, consider the following three resolutions of `f`:
482 /// mod foo { pub fn f() {} } // `f`'s `SyntaxContext` is empty.
484 /// macro m($f:ident) {
486 /// pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
487 /// pub fn $f() {} // `$f`'s `SyntaxContext` is empty.
489 /// foo::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
490 /// //^ Since `mod foo` is outside this expansion, `adjust` removes the mark from `f`,
491 /// //| and it resolves to `::foo::f`.
492 /// bar::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
493 /// //^ Since `mod bar` not outside this expansion, `adjust` does not change `f`,
494 /// //| and it resolves to `::bar::f`.
495 /// bar::$f(); // `f`'s `SyntaxContext` is empty.
496 /// //^ Since `mod bar` is not outside this expansion, `adjust` does not change `$f`,
497 /// //| and it resolves to `::bar::$f`.
500 /// This returns the expansion whose definition scope we use to privacy check the resolution,
501 /// or `None` if we privacy check as usual (i.e., not w.r.t. a macro definition scope).
502 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
503 HygieneData::with(|data| data.adjust(self, expn_id))
506 /// Like `SyntaxContext::adjust`, but also normalizes `self` to macros 2.0.
507 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
508 HygieneData::with(|data| {
509 *self = data.normalize_to_macros_2_0(*self);
510 data.adjust(self, expn_id)
514 /// Adjust this context for resolution in a scope created by the given expansion
515 /// via a glob import with the given `SyntaxContext`.
520 /// macro m($i:ident) {
522 /// pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
523 /// pub fn $i() {} // `$i`'s `SyntaxContext` is empty.
526 /// macro n($j:ident) {
528 /// f(); // `f`'s `SyntaxContext` has a mark from `m` and a mark from `n`
529 /// //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::f`.
530 /// $i(); // `$i`'s `SyntaxContext` has a mark from `n`
531 /// //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::$i`.
532 /// $j(); // `$j`'s `SyntaxContext` has a mark from `m`
533 /// //^ This cannot be glob-adjusted, so this is a resolution error.
537 /// This returns `None` if the context cannot be glob-adjusted.
538 /// Otherwise, it returns the scope to use when privacy checking (see `adjust` for details).
539 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
540 HygieneData::with(|data| {
541 let mut scope = None;
542 let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
543 while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
544 scope = Some(data.remove_mark(&mut glob_ctxt).0);
545 if data.remove_mark(self).0 != scope.unwrap() {
549 if data.adjust(self, expn_id).is_some() {
556 /// Undo `glob_adjust` if possible:
559 /// if let Some(privacy_checking_scope) = self.reverse_glob_adjust(expansion, glob_ctxt) {
560 /// assert!(self.glob_adjust(expansion, glob_ctxt) == Some(privacy_checking_scope));
563 pub fn reverse_glob_adjust(
567 ) -> Option<Option<ExpnId>> {
568 HygieneData::with(|data| {
569 if data.adjust(self, expn_id).is_some() {
573 let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
574 let mut marks = Vec::new();
575 while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
576 marks.push(data.remove_mark(&mut glob_ctxt));
579 let scope = marks.last().map(|mark| mark.0);
580 while let Some((expn_id, transparency)) = marks.pop() {
581 *self = data.apply_mark(*self, expn_id, transparency);
587 pub fn hygienic_eq(self, other: SyntaxContext, expn_id: ExpnId) -> bool {
588 HygieneData::with(|data| {
589 let mut self_normalized = data.normalize_to_macros_2_0(self);
590 data.adjust(&mut self_normalized, expn_id);
591 self_normalized == data.normalize_to_macros_2_0(other)
596 pub fn normalize_to_macros_2_0(self) -> SyntaxContext {
597 HygieneData::with(|data| data.normalize_to_macros_2_0(self))
601 pub fn normalize_to_macro_rules(self) -> SyntaxContext {
602 HygieneData::with(|data| data.normalize_to_macro_rules(self))
606 pub fn outer_expn(self) -> ExpnId {
607 HygieneData::with(|data| data.outer_expn(self))
610 /// `ctxt.outer_expn_data()` is equivalent to but faster than
611 /// `ctxt.outer_expn().expn_data()`.
613 pub fn outer_expn_data(self) -> ExpnData {
614 HygieneData::with(|data| data.expn_data(data.outer_expn(self)).clone())
618 pub fn outer_mark(self) -> (ExpnId, Transparency) {
619 HygieneData::with(|data| data.outer_mark(self))
623 pub fn outer_mark_with_data(self) -> (ExpnId, Transparency, ExpnData) {
624 HygieneData::with(|data| {
625 let (expn_id, transparency) = data.outer_mark(self);
626 (expn_id, transparency, data.expn_data(expn_id).clone())
630 pub fn dollar_crate_name(self) -> Symbol {
631 HygieneData::with(|data| data.syntax_context_data[self.0 as usize].dollar_crate_name)
635 impl fmt::Debug for SyntaxContext {
636 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
637 write!(f, "#{}", self.0)
642 /// Creates a fresh expansion with given properties.
643 /// Expansions are normally created by macros, but in some cases expansions are created for
644 /// other compiler-generated code to set per-span properties like allowed unstable features.
645 /// The returned span belongs to the created expansion and has the new properties,
646 /// but its location is inherited from the current span.
647 pub fn fresh_expansion(self, expn_data: ExpnData) -> Span {
648 self.fresh_expansion_with_transparency(expn_data, Transparency::Transparent)
651 pub fn fresh_expansion_with_transparency(
654 transparency: Transparency,
656 HygieneData::with(|data| {
657 let expn_id = data.fresh_expn(Some(expn_data));
658 self.with_ctxt(data.apply_mark(SyntaxContext::root(), expn_id, transparency))
663 /// A subset of properties from both macro definition and macro call available through global data.
664 /// Avoid using this if you have access to the original definition or call structures.
665 #[derive(Clone, Debug, Encodable, Decodable, HashStable_Generic)]
666 pub struct ExpnData {
667 // --- The part unique to each expansion.
668 /// The kind of this expansion - macro or compiler desugaring.
670 /// The expansion that produced this expansion.
672 /// The location of the actual macro invocation or syntax sugar , e.g.
673 /// `let x = foo!();` or `if let Some(y) = x {}`
675 /// This may recursively refer to other macro invocations, e.g., if
676 /// `foo!()` invoked `bar!()` internally, and there was an
677 /// expression inside `bar!`; the call_site of the expression in
678 /// the expansion would point to the `bar!` invocation; that
679 /// call_site span would have its own ExpnData, with the call_site
680 /// pointing to the `foo!` invocation.
683 // --- The part specific to the macro/desugaring definition.
684 // --- It may be reasonable to share this part between expansions with the same definition,
685 // --- but such sharing is known to bring some minor inconveniences without also bringing
686 // --- noticeable perf improvements (PR #62898).
687 /// The span of the macro definition (possibly dummy).
688 /// This span serves only informational purpose and is not used for resolution.
690 /// List of `#[unstable]`/feature-gated features that the macro is allowed to use
691 /// internally without forcing the whole crate to opt-in
693 pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
694 /// Whether the macro is allowed to use `unsafe` internally
695 /// even if the user crate has `#![forbid(unsafe_code)]`.
696 pub allow_internal_unsafe: bool,
697 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`)
698 /// for a given macro.
699 pub local_inner_macros: bool,
700 /// Edition of the crate in which the macro is defined.
701 pub edition: Edition,
702 /// The `DefId` of the macro being invoked,
703 /// if this `ExpnData` corresponds to a macro invocation
704 pub macro_def_id: Option<DefId>,
705 /// The crate that originally created this `ExpnData`. During
706 /// metadata serialization, we only encode `ExpnData`s that were
707 /// created locally - when our serialized metadata is decoded,
708 /// foreign `ExpnId`s will have their `ExpnData` looked up
709 /// from the crate specified by `Crate
711 /// The raw that this `ExpnData` had in its original crate.
712 /// An `ExpnData` can be created before being assigned an `ExpnId`,
713 /// so this might be `None` until `set_expn_data` is called
714 // This is used only for serialization/deserialization purposes:
715 // two `ExpnData`s that differ only in their `orig_id` should
716 // be considered equivalent.
717 #[stable_hasher(ignore)]
718 pub orig_id: Option<u32>,
721 // This would require special handling of `orig_id` and `parent`
722 impl !PartialEq for ExpnData {}
725 /// Constructs expansion data with default properties.
730 macro_def_id: Option<DefId>,
734 parent: ExpnId::root(),
737 allow_internal_unstable: None,
738 allow_internal_unsafe: false,
739 local_inner_macros: false,
747 pub fn allow_unstable(
751 allow_internal_unstable: Lrc<[Symbol]>,
752 macro_def_id: Option<DefId>,
755 allow_internal_unstable: Some(allow_internal_unstable),
756 ..ExpnData::default(kind, call_site, edition, macro_def_id)
761 pub fn is_root(&self) -> bool {
762 matches!(self.kind, ExpnKind::Root)
767 #[derive(Clone, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
769 /// No expansion, aka root expansion. Only `ExpnId::root()` has this kind.
771 /// Expansion produced by a macro.
772 Macro(MacroKind, Symbol),
773 /// Transform done by the compiler on the AST.
775 /// Desugaring done by the compiler during HIR lowering.
776 Desugaring(DesugaringKind),
780 pub fn descr(&self) -> String {
782 ExpnKind::Root => kw::PathRoot.to_string(),
783 ExpnKind::Macro(macro_kind, name) => match macro_kind {
784 MacroKind::Bang => format!("{}!", name),
785 MacroKind::Attr => format!("#[{}]", name),
786 MacroKind::Derive => format!("#[derive({})]", name),
788 ExpnKind::AstPass(kind) => kind.descr().to_string(),
789 ExpnKind::Desugaring(kind) => format!("desugaring of {}", kind.descr()),
794 /// The kind of macro invocation or definition.
795 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
796 #[derive(HashStable_Generic)]
798 /// A bang macro `foo!()`.
800 /// An attribute macro `#[foo]`.
802 /// A derive macro `#[derive(Foo)]`
807 pub fn descr(self) -> &'static str {
809 MacroKind::Bang => "macro",
810 MacroKind::Attr => "attribute macro",
811 MacroKind::Derive => "derive macro",
815 pub fn descr_expected(self) -> &'static str {
817 MacroKind::Attr => "attribute",
822 pub fn article(self) -> &'static str {
824 MacroKind::Attr => "an",
830 /// The kind of AST transform.
831 #[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
839 fn descr(self) -> &'static str {
841 AstPass::StdImports => "standard library imports",
842 AstPass::TestHarness => "test harness",
843 AstPass::ProcMacroHarness => "proc macro harness",
848 /// The kind of compiler desugaring.
849 #[derive(Clone, Copy, PartialEq, Debug, Encodable, Decodable, HashStable_Generic)]
850 pub enum DesugaringKind {
851 /// We desugar `if c { i } else { e }` to `match $ExprKind::Use(c) { true => i, _ => e }`.
852 /// However, we do not want to blame `c` for unreachability but rather say that `i`
853 /// is unreachable. This desugaring kind allows us to avoid blaming `c`.
854 /// This also applies to `while` loops.
858 /// Desugaring of an `impl Trait` in return type position
859 /// to an `type Foo = impl Trait;` and replacing the
860 /// `impl Trait` with `Foo`.
867 /// A location in the desugaring of a `for` loop
868 #[derive(Clone, Copy, PartialEq, Debug, Encodable, Decodable, HashStable_Generic)]
869 pub enum ForLoopLoc {
874 impl DesugaringKind {
875 /// The description wording should combine well with "desugaring of {}".
876 fn descr(self) -> &'static str {
878 DesugaringKind::CondTemporary => "`if` or `while` condition",
879 DesugaringKind::Async => "`async` block or function",
880 DesugaringKind::Await => "`await` expression",
881 DesugaringKind::QuestionMark => "operator `?`",
882 DesugaringKind::TryBlock => "`try` block",
883 DesugaringKind::OpaqueTy => "`impl Trait`",
884 DesugaringKind::ForLoop(_) => "`for` loop",
890 pub struct HygieneEncodeContext {
891 /// All `SyntaxContexts` for which we have written `SyntaxContextData` into crate metadata.
892 /// This is `None` after we finish encoding `SyntaxContexts`, to ensure
893 /// that we don't accidentally try to encode any more `SyntaxContexts`
894 serialized_ctxts: Lock<FxHashSet<SyntaxContext>>,
895 /// The `SyntaxContexts` that we have serialized (e.g. as a result of encoding `Spans`)
896 /// in the most recent 'round' of serializnig. Serializing `SyntaxContextData`
897 /// may cause us to serialize more `SyntaxContext`s, so serialize in a loop
898 /// until we reach a fixed point.
899 latest_ctxts: Lock<FxHashSet<SyntaxContext>>,
901 serialized_expns: Lock<FxHashSet<ExpnId>>,
903 latest_expns: Lock<FxHashSet<ExpnId>>,
906 impl HygieneEncodeContext {
910 F: FnMut(&mut T, u32, &SyntaxContextData) -> Result<(), R>,
911 G: FnMut(&mut T, u32, &ExpnData) -> Result<(), R>,
918 // When we serialize a `SyntaxContextData`, we may end up serializing
919 // a `SyntaxContext` that we haven't seen before
920 while !self.latest_ctxts.lock().is_empty() || !self.latest_expns.lock().is_empty() {
922 "encode_hygiene: Serializing a round of {:?} SyntaxContextDatas: {:?}",
923 self.latest_ctxts.lock().len(),
927 // Consume the current round of SyntaxContexts.
928 // Drop the lock() temporary early
929 let latest_ctxts = { std::mem::take(&mut *self.latest_ctxts.lock()) };
931 // It's fine to iterate over a HashMap, because the serialization
932 // of the table that we insert data into doesn't depend on insertion
934 for_all_ctxts_in(latest_ctxts.into_iter(), |(index, ctxt, data)| {
935 if self.serialized_ctxts.lock().insert(ctxt) {
936 encode_ctxt(encoder, index, data)?;
941 let latest_expns = { std::mem::take(&mut *self.latest_expns.lock()) };
943 for_all_expns_in(latest_expns.into_iter(), |index, expn, data| {
944 if self.serialized_expns.lock().insert(expn) {
945 encode_expn(encoder, index, data)?;
950 debug!("encode_hygiene: Done serializing SyntaxContextData");
956 /// Additional information used to assist in decoding hygiene data
957 pub struct HygieneDecodeContext {
958 // Maps serialized `SyntaxContext` ids to a `SyntaxContext` in the current
959 // global `HygieneData`. When we deserialize a `SyntaxContext`, we need to create
960 // a new id in the global `HygieneData`. This map tracks the ID we end up picking,
961 // so that multiple occurrences of the same serialized id are decoded to the same
963 remapped_ctxts: Lock<Vec<Option<SyntaxContext>>>,
964 // The same as `remapepd_ctxts`, but for `ExpnId`s
965 remapped_expns: Lock<Vec<Option<ExpnId>>>,
968 pub fn decode_expn_id<
971 F: FnOnce(&mut D, u32) -> Result<ExpnData, D::Error>,
972 G: FnOnce(CrateNum) -> &'a HygieneDecodeContext,
975 mode: ExpnDataDecodeMode<'a, G>,
977 ) -> Result<ExpnId, D::Error> {
978 let index = u32::decode(d)?;
979 let context = match mode {
980 ExpnDataDecodeMode::IncrComp(context) => context,
981 ExpnDataDecodeMode::Metadata(get_context) => {
982 let krate = CrateNum::decode(d)?;
987 // Do this after decoding, so that we decode a `CrateNum`
989 if index == ExpnId::root().as_u32() {
990 debug!("decode_expn_id: deserialized root");
991 return Ok(ExpnId::root());
994 let outer_expns = &context.remapped_expns;
996 // Ensure that the lock() temporary is dropped early
998 if let Some(expn_id) = outer_expns.lock().get(index as usize).copied().flatten() {
1003 // Don't decode the data inside `HygieneData::with`, since we need to recursively decode
1005 let mut expn_data = decode_data(d, index)?;
1007 let expn_id = HygieneData::with(|hygiene_data| {
1008 let expn_id = ExpnId(hygiene_data.expn_data.len() as u32);
1010 // If we just deserialized an `ExpnData` owned by
1011 // the local crate, its `orig_id` will be stale,
1012 // so we need to update it to its own value.
1013 // This only happens when we deserialize the incremental cache,
1014 // since a crate will never decode its own metadata.
1015 if expn_data.krate == LOCAL_CRATE {
1016 expn_data.orig_id = Some(expn_id.0);
1019 hygiene_data.expn_data.push(Some(expn_data));
1021 let mut expns = outer_expns.lock();
1022 let new_len = index as usize + 1;
1023 if expns.len() < new_len {
1024 expns.resize(new_len, None);
1026 expns[index as usize] = Some(expn_id);
1033 // Decodes `SyntaxContext`, using the provided `HygieneDecodeContext`
1034 // to track which `SyntaxContext`s we have already decoded.
1035 // The provided closure will be invoked to deserialize a `SyntaxContextData`
1036 // if we haven't already seen the id of the `SyntaxContext` we are deserializing.
1037 pub fn decode_syntax_context<
1039 F: FnOnce(&mut D, u32) -> Result<SyntaxContextData, D::Error>,
1042 context: &HygieneDecodeContext,
1044 ) -> Result<SyntaxContext, D::Error> {
1045 let raw_id: u32 = Decodable::decode(d)?;
1047 debug!("decode_syntax_context: deserialized root");
1048 // The root is special
1049 return Ok(SyntaxContext::root());
1052 let outer_ctxts = &context.remapped_ctxts;
1054 // Ensure that the lock() temporary is dropped early
1056 if let Some(ctxt) = outer_ctxts.lock().get(raw_id as usize).copied().flatten() {
1061 // Allocate and store SyntaxContext id *before* calling the decoder function,
1062 // as the SyntaxContextData may reference itself.
1063 let new_ctxt = HygieneData::with(|hygiene_data| {
1064 let new_ctxt = SyntaxContext(hygiene_data.syntax_context_data.len() as u32);
1065 // Push a dummy SyntaxContextData to ensure that nobody else can get the
1066 // same ID as us. This will be overwritten after call `decode_Data`
1067 hygiene_data.syntax_context_data.push(SyntaxContextData {
1068 outer_expn: ExpnId::root(),
1069 outer_transparency: Transparency::Transparent,
1070 parent: SyntaxContext::root(),
1071 opaque: SyntaxContext::root(),
1072 opaque_and_semitransparent: SyntaxContext::root(),
1073 dollar_crate_name: kw::Invalid,
1075 let mut ctxts = outer_ctxts.lock();
1076 let new_len = raw_id as usize + 1;
1077 if ctxts.len() < new_len {
1078 ctxts.resize(new_len, None);
1080 ctxts[raw_id as usize] = Some(new_ctxt);
1085 // Don't try to decode data while holding the lock, since we need to
1086 // be able to recursively decode a SyntaxContext
1087 let mut ctxt_data = decode_data(d, raw_id)?;
1088 // Reset `dollar_crate_name` so that it will be updated by `update_dollar_crate_names`
1089 // We don't care what the encoding crate set this to - we want to resolve it
1090 // from the perspective of the current compilation session
1091 ctxt_data.dollar_crate_name = kw::DollarCrate;
1093 // Overwrite the dummy data with our decoded SyntaxContextData
1094 HygieneData::with(|hygiene_data| {
1095 let dummy = std::mem::replace(
1096 &mut hygiene_data.syntax_context_data[new_ctxt.as_u32() as usize],
1099 // Make sure nothing weird happening while `decode_data` was running
1100 assert_eq!(dummy.dollar_crate_name, kw::Invalid);
1106 pub fn num_syntax_ctxts() -> usize {
1107 HygieneData::with(|data| data.syntax_context_data.len())
1110 pub fn for_all_ctxts_in<E, F: FnMut((u32, SyntaxContext, &SyntaxContextData)) -> Result<(), E>>(
1111 ctxts: impl Iterator<Item = SyntaxContext>,
1113 ) -> Result<(), E> {
1114 let all_data: Vec<_> = HygieneData::with(|data| {
1115 ctxts.map(|ctxt| (ctxt, data.syntax_context_data[ctxt.0 as usize].clone())).collect()
1117 for (ctxt, data) in all_data.into_iter() {
1118 f((ctxt.0, ctxt, &data))?;
1123 pub fn for_all_expns_in<E, F: FnMut(u32, ExpnId, &ExpnData) -> Result<(), E>>(
1124 expns: impl Iterator<Item = ExpnId>,
1126 ) -> Result<(), E> {
1127 let all_data: Vec<_> = HygieneData::with(|data| {
1128 expns.map(|expn| (expn, data.expn_data[expn.0 as usize].clone())).collect()
1130 for (expn, data) in all_data.into_iter() {
1131 f(expn.0, expn, &data.unwrap_or_else(|| panic!("Missing data for {:?}", expn)))?;
1136 pub fn for_all_data<E, F: FnMut((u32, SyntaxContext, &SyntaxContextData)) -> Result<(), E>>(
1138 ) -> Result<(), E> {
1139 let all_data = HygieneData::with(|data| data.syntax_context_data.clone());
1140 for (i, data) in all_data.into_iter().enumerate() {
1141 f((i as u32, SyntaxContext(i as u32), &data))?;
1146 impl<E: Encoder> Encodable<E> for ExpnId {
1147 default fn encode(&self, _: &mut E) -> Result<(), E::Error> {
1148 panic!("cannot encode `ExpnId` with `{}`", std::any::type_name::<E>());
1152 impl<D: Decoder> Decodable<D> for ExpnId {
1153 default fn decode(_: &mut D) -> Result<Self, D::Error> {
1154 panic!("cannot decode `ExpnId` with `{}`", std::any::type_name::<D>());
1158 pub fn for_all_expn_data<E, F: FnMut(u32, &ExpnData) -> Result<(), E>>(mut f: F) -> Result<(), E> {
1159 let all_data = HygieneData::with(|data| data.expn_data.clone());
1160 for (i, data) in all_data.into_iter().enumerate() {
1161 f(i as u32, &data.unwrap_or_else(|| panic!("Missing ExpnData!")))?;
1166 pub fn raw_encode_syntax_context<E: Encoder>(
1167 ctxt: SyntaxContext,
1168 context: &HygieneEncodeContext,
1170 ) -> Result<(), E::Error> {
1171 if !context.serialized_ctxts.lock().contains(&ctxt) {
1172 context.latest_ctxts.lock().insert(ctxt);
1177 pub fn raw_encode_expn_id<E: Encoder>(
1179 context: &HygieneEncodeContext,
1180 mode: ExpnDataEncodeMode,
1182 ) -> Result<(), E::Error> {
1183 // Record the fact that we need to serialize the corresponding
1185 let needs_data = || {
1186 if !context.serialized_expns.lock().contains(&expn) {
1187 context.latest_expns.lock().insert(expn);
1192 ExpnDataEncodeMode::IncrComp => {
1193 // Always serialize the `ExpnData` in incr comp mode
1197 ExpnDataEncodeMode::Metadata => {
1198 let data = expn.expn_data();
1199 // We only need to serialize the ExpnData
1200 // if it comes from this crate.
1201 // We currently don't serialize any hygiene information data for
1202 // proc-macro crates: see the `SpecializedEncoder<Span>` impl
1203 // for crate metadata.
1204 if data.krate == LOCAL_CRATE {
1207 data.orig_id.expect("Missing orig_id").encode(e)?;
1208 data.krate.encode(e)
1213 pub enum ExpnDataEncodeMode {
1218 pub enum ExpnDataDecodeMode<'a, F: FnOnce(CrateNum) -> &'a HygieneDecodeContext> {
1219 IncrComp(&'a HygieneDecodeContext),
1223 impl<'a> ExpnDataDecodeMode<'a, Box<dyn FnOnce(CrateNum) -> &'a HygieneDecodeContext>> {
1224 pub fn incr_comp(ctxt: &'a HygieneDecodeContext) -> Self {
1225 ExpnDataDecodeMode::IncrComp(ctxt)
1229 impl<E: Encoder> Encodable<E> for SyntaxContext {
1230 default fn encode(&self, _: &mut E) -> Result<(), E::Error> {
1231 panic!("cannot encode `SyntaxContext` with `{}`", std::any::type_name::<E>());
1235 impl<D: Decoder> Decodable<D> for SyntaxContext {
1236 default fn decode(_: &mut D) -> Result<Self, D::Error> {
1237 panic!("cannot decode `SyntaxContext` with `{}`", std::any::type_name::<D>());