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};
34 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
35 use rustc_data_structures::sync::{Lock, Lrc};
36 use rustc_macros::HashStable_Generic;
37 use rustc_serialize::{
38 Decodable, Decoder, Encodable, Encoder, UseSpecializedDecodable, UseSpecializedEncodable,
42 /// A `SyntaxContext` represents a chain of pairs `(ExpnId, Transparency)` named "marks".
43 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
44 pub struct SyntaxContext(u32);
46 #[derive(Debug, RustcEncodable, RustcDecodable, Clone)]
47 pub struct SyntaxContextData {
49 outer_transparency: Transparency,
50 parent: SyntaxContext,
51 /// This context, but with all transparent and semi-transparent expansions filtered away.
52 opaque: SyntaxContext,
53 /// This context, but with all transparent expansions filtered away.
54 opaque_and_semitransparent: SyntaxContext,
55 /// Name of the crate to which `$crate` with this context would resolve.
56 dollar_crate_name: Symbol,
59 /// A unique ID associated with a macro invocation and expansion.
60 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
61 pub struct ExpnId(u32);
63 /// A property of a macro expansion that determines how identifiers
64 /// produced by that expansion are resolved.
65 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Hash, Debug, RustcEncodable, RustcDecodable)]
66 #[derive(HashStable_Generic)]
67 pub enum Transparency {
68 /// Identifier produced by a transparent expansion is always resolved at call-site.
69 /// Call-site spans in procedural macros, hygiene opt-out in `macro` should use this.
71 /// Identifier produced by a semi-transparent expansion may be resolved
72 /// either at call-site or at definition-site.
73 /// If it's a local variable, label or `$crate` then it's resolved at def-site.
74 /// Otherwise it's resolved at call-site.
75 /// `macro_rules` macros behave like this, built-in macros currently behave like this too,
76 /// but that's an implementation detail.
78 /// Identifier produced by an opaque expansion is always resolved at definition-site.
79 /// Def-site spans in procedural macros, identifiers from `macro` by default use this.
84 pub fn fresh(expn_data: Option<ExpnData>) -> Self {
85 HygieneData::with(|data| data.fresh_expn(expn_data))
88 /// The ID of the theoretical expansion that generates freshly parsed, unexpanded AST.
90 pub fn root() -> Self {
95 pub fn as_u32(self) -> u32 {
100 pub fn from_u32(raw: u32) -> ExpnId {
105 pub fn expn_data(self) -> ExpnData {
106 HygieneData::with(|data| data.expn_data(self).clone())
110 pub fn set_expn_data(self, mut expn_data: ExpnData) {
111 HygieneData::with(|data| {
112 let old_expn_data = &mut data.expn_data[self.0 as usize];
113 assert!(old_expn_data.is_none(), "expansion data is reset for an expansion ID");
114 expn_data.orig_id.replace(self.as_u32()).expect_none("orig_id should be None");
115 *old_expn_data = Some(expn_data);
119 pub fn is_descendant_of(self, ancestor: ExpnId) -> bool {
120 HygieneData::with(|data| data.is_descendant_of(self, ancestor))
123 /// `expn_id.outer_expn_is_descendant_of(ctxt)` is equivalent to but faster than
124 /// `expn_id.is_descendant_of(ctxt.outer_expn())`.
125 pub fn outer_expn_is_descendant_of(self, ctxt: SyntaxContext) -> bool {
126 HygieneData::with(|data| data.is_descendant_of(self, data.outer_expn(ctxt)))
129 /// Returns span for the macro which originally caused this expansion to happen.
131 /// Stops backtracing at include! boundary.
132 pub fn expansion_cause(mut self) -> Option<Span> {
133 let mut last_macro = None;
135 let expn_data = self.expn_data();
136 // Stop going up the backtrace once include! is encountered
137 if expn_data.is_root()
138 || expn_data.kind == ExpnKind::Macro(MacroKind::Bang, sym::include)
142 self = expn_data.call_site.ctxt().outer_expn();
143 last_macro = Some(expn_data.call_site);
150 pub struct HygieneData {
151 /// Each expansion should have an associated expansion data, but sometimes there's a delay
152 /// between creation of an expansion ID and obtaining its data (e.g. macros are collected
153 /// first and then resolved later), so we use an `Option` here.
154 expn_data: Vec<Option<ExpnData>>,
155 syntax_context_data: Vec<SyntaxContextData>,
156 syntax_context_map: FxHashMap<(SyntaxContext, ExpnId, Transparency), SyntaxContext>,
160 crate fn new(edition: Edition) -> Self {
161 let mut root_data = ExpnData::default(
165 Some(DefId::local(CRATE_DEF_INDEX)),
167 root_data.orig_id = Some(0);
170 expn_data: vec![Some(root_data)],
171 syntax_context_data: vec![SyntaxContextData {
172 outer_expn: ExpnId::root(),
173 outer_transparency: Transparency::Opaque,
174 parent: SyntaxContext(0),
175 opaque: SyntaxContext(0),
176 opaque_and_semitransparent: SyntaxContext(0),
177 dollar_crate_name: kw::DollarCrate,
179 syntax_context_map: FxHashMap::default(),
183 pub fn with<T, F: FnOnce(&mut HygieneData) -> T>(f: F) -> T {
184 SESSION_GLOBALS.with(|session_globals| f(&mut *session_globals.hygiene_data.borrow_mut()))
187 fn fresh_expn(&mut self, mut expn_data: Option<ExpnData>) -> ExpnId {
188 let raw_id = self.expn_data.len() as u32;
189 if let Some(data) = expn_data.as_mut() {
190 data.orig_id.replace(raw_id).expect_none("orig_id should be None");
192 self.expn_data.push(expn_data);
196 fn expn_data(&self, expn_id: ExpnId) -> &ExpnData {
197 self.expn_data[expn_id.0 as usize].as_ref().expect("no expansion data for an expansion ID")
200 fn is_descendant_of(&self, mut expn_id: ExpnId, ancestor: ExpnId) -> bool {
201 while expn_id != ancestor {
202 if expn_id == ExpnId::root() {
205 expn_id = self.expn_data(expn_id).parent;
210 fn normalize_to_macros_2_0(&self, ctxt: SyntaxContext) -> SyntaxContext {
211 self.syntax_context_data[ctxt.0 as usize].opaque
214 fn normalize_to_macro_rules(&self, ctxt: SyntaxContext) -> SyntaxContext {
215 self.syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent
218 fn outer_expn(&self, ctxt: SyntaxContext) -> ExpnId {
219 self.syntax_context_data[ctxt.0 as usize].outer_expn
222 fn outer_mark(&self, ctxt: SyntaxContext) -> (ExpnId, Transparency) {
223 let data = &self.syntax_context_data[ctxt.0 as usize];
224 (data.outer_expn, data.outer_transparency)
227 fn parent_ctxt(&self, ctxt: SyntaxContext) -> SyntaxContext {
228 self.syntax_context_data[ctxt.0 as usize].parent
231 fn remove_mark(&self, ctxt: &mut SyntaxContext) -> (ExpnId, Transparency) {
232 let outer_mark = self.outer_mark(*ctxt);
233 *ctxt = self.parent_ctxt(*ctxt);
237 fn marks(&self, mut ctxt: SyntaxContext) -> Vec<(ExpnId, Transparency)> {
238 let mut marks = Vec::new();
239 while ctxt != SyntaxContext::root() {
240 debug!("marks: getting parent of {:?}", ctxt);
241 marks.push(self.outer_mark(ctxt));
242 ctxt = self.parent_ctxt(ctxt);
248 fn walk_chain(&self, mut span: Span, to: SyntaxContext) -> Span {
249 debug!("walk_chain({:?}, {:?})", span, to);
250 debug!("walk_chain: span ctxt = {:?}", span.ctxt());
251 while span.from_expansion() && span.ctxt() != to {
252 let outer_expn = self.outer_expn(span.ctxt());
253 debug!("walk_chain({:?}): outer_expn={:?}", span, outer_expn);
254 let expn_data = self.expn_data(outer_expn);
255 debug!("walk_chain({:?}): expn_data={:?}", span, expn_data);
256 span = expn_data.call_site;
261 fn adjust(&self, ctxt: &mut SyntaxContext, expn_id: ExpnId) -> Option<ExpnId> {
262 let mut scope = None;
263 while !self.is_descendant_of(expn_id, self.outer_expn(*ctxt)) {
264 scope = Some(self.remove_mark(ctxt).0);
273 transparency: Transparency,
275 assert_ne!(expn_id, ExpnId::root());
276 if transparency == Transparency::Opaque {
277 return self.apply_mark_internal(ctxt, expn_id, transparency);
280 let call_site_ctxt = self.expn_data(expn_id).call_site.ctxt();
281 let mut call_site_ctxt = if transparency == Transparency::SemiTransparent {
282 self.normalize_to_macros_2_0(call_site_ctxt)
284 self.normalize_to_macro_rules(call_site_ctxt)
287 if call_site_ctxt == SyntaxContext::root() {
288 return self.apply_mark_internal(ctxt, expn_id, transparency);
291 // Otherwise, `expn_id` is a macros 1.0 definition and the call site is in a
292 // macros 2.0 expansion, i.e., a macros 1.0 invocation is in a macros 2.0 definition.
294 // In this case, the tokens from the macros 1.0 definition inherit the hygiene
295 // at their invocation. That is, we pretend that the macros 1.0 definition
296 // was defined at its invocation (i.e., inside the macros 2.0 definition)
297 // so that the macros 2.0 definition remains hygienic.
299 // See the example at `test/ui/hygiene/legacy_interaction.rs`.
300 for (expn_id, transparency) in self.marks(ctxt) {
301 call_site_ctxt = self.apply_mark_internal(call_site_ctxt, expn_id, transparency);
303 self.apply_mark_internal(call_site_ctxt, expn_id, transparency)
306 fn apply_mark_internal(
310 transparency: Transparency,
312 let syntax_context_data = &mut self.syntax_context_data;
313 let mut opaque = syntax_context_data[ctxt.0 as usize].opaque;
314 let mut opaque_and_semitransparent =
315 syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent;
317 if transparency >= Transparency::Opaque {
321 .entry((parent, expn_id, transparency))
323 let new_opaque = SyntaxContext(syntax_context_data.len() as u32);
324 syntax_context_data.push(SyntaxContextData {
326 outer_transparency: transparency,
329 opaque_and_semitransparent: new_opaque,
330 dollar_crate_name: kw::DollarCrate,
336 if transparency >= Transparency::SemiTransparent {
337 let parent = opaque_and_semitransparent;
338 opaque_and_semitransparent = *self
340 .entry((parent, expn_id, transparency))
342 let new_opaque_and_semitransparent =
343 SyntaxContext(syntax_context_data.len() as u32);
344 syntax_context_data.push(SyntaxContextData {
346 outer_transparency: transparency,
349 opaque_and_semitransparent: new_opaque_and_semitransparent,
350 dollar_crate_name: kw::DollarCrate,
352 new_opaque_and_semitransparent
357 *self.syntax_context_map.entry((parent, expn_id, transparency)).or_insert_with(|| {
358 let new_opaque_and_semitransparent_and_transparent =
359 SyntaxContext(syntax_context_data.len() as u32);
360 syntax_context_data.push(SyntaxContextData {
362 outer_transparency: transparency,
365 opaque_and_semitransparent,
366 dollar_crate_name: kw::DollarCrate,
368 new_opaque_and_semitransparent_and_transparent
373 pub fn clear_syntax_context_map() {
374 HygieneData::with(|data| data.syntax_context_map = FxHashMap::default());
377 pub fn walk_chain(span: Span, to: SyntaxContext) -> Span {
378 HygieneData::with(|data| data.walk_chain(span, to))
381 pub fn update_dollar_crate_names(mut get_name: impl FnMut(SyntaxContext) -> Symbol) {
382 // The new contexts that need updating are at the end of the list and have `$crate` as a name.
383 let (len, to_update) = HygieneData::with(|data| {
385 data.syntax_context_data.len(),
386 data.syntax_context_data
389 .take_while(|scdata| scdata.dollar_crate_name == kw::DollarCrate)
393 // The callback must be called from outside of the `HygieneData` lock,
394 // since it will try to acquire it too.
395 let range_to_update = len - to_update..len;
397 range_to_update.clone().map(|idx| get_name(SyntaxContext::from_u32(idx as u32))).collect();
398 HygieneData::with(|data| {
399 range_to_update.zip(names.into_iter()).for_each(|(idx, name)| {
400 data.syntax_context_data[idx].dollar_crate_name = name;
405 pub fn debug_hygiene_data(verbose: bool) -> String {
406 HygieneData::with(|data| {
408 format!("{:#?}", data)
410 let mut s = String::from("");
411 s.push_str("Expansions:");
412 data.expn_data.iter().enumerate().for_each(|(id, expn_info)| {
413 let expn_info = expn_info.as_ref().expect("no expansion data for an expansion ID");
415 "\n{}: parent: {:?}, call_site_ctxt: {:?}, def_site_ctxt: {:?}, kind: {:?}",
418 expn_info.call_site.ctxt(),
419 expn_info.def_site.ctxt(),
423 s.push_str("\n\nSyntaxContexts:");
424 data.syntax_context_data.iter().enumerate().for_each(|(id, ctxt)| {
426 "\n#{}: parent: {:?}, outer_mark: ({:?}, {:?})",
427 id, ctxt.parent, ctxt.outer_expn, ctxt.outer_transparency,
437 pub const fn root() -> Self {
442 crate fn as_u32(self) -> u32 {
447 crate fn from_u32(raw: u32) -> SyntaxContext {
451 /// Extend a syntax context with a given expansion and transparency.
452 crate fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> SyntaxContext {
453 HygieneData::with(|data| data.apply_mark(self, expn_id, transparency))
456 /// Pulls a single mark off of the syntax context. This effectively moves the
457 /// context up one macro definition level. That is, if we have a nested macro
458 /// definition as follows:
468 /// and we have a SyntaxContext that is referring to something declared by an invocation
469 /// of g (call it g1), calling remove_mark will result in the SyntaxContext for the
470 /// invocation of f that created g1.
471 /// Returns the mark that was removed.
472 pub fn remove_mark(&mut self) -> ExpnId {
473 HygieneData::with(|data| data.remove_mark(self).0)
476 pub fn marks(self) -> Vec<(ExpnId, Transparency)> {
477 HygieneData::with(|data| data.marks(self))
480 /// Adjust this context for resolution in a scope created by the given expansion.
481 /// For example, consider the following three resolutions of `f`:
484 /// mod foo { pub fn f() {} } // `f`'s `SyntaxContext` is empty.
486 /// macro m($f:ident) {
488 /// pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
489 /// pub fn $f() {} // `$f`'s `SyntaxContext` is empty.
491 /// foo::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
492 /// //^ Since `mod foo` is outside this expansion, `adjust` removes the mark from `f`,
493 /// //| and it resolves to `::foo::f`.
494 /// bar::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
495 /// //^ Since `mod bar` not outside this expansion, `adjust` does not change `f`,
496 /// //| and it resolves to `::bar::f`.
497 /// bar::$f(); // `f`'s `SyntaxContext` is empty.
498 /// //^ Since `mod bar` is not outside this expansion, `adjust` does not change `$f`,
499 /// //| and it resolves to `::bar::$f`.
502 /// This returns the expansion whose definition scope we use to privacy check the resolution,
503 /// or `None` if we privacy check as usual (i.e., not w.r.t. a macro definition scope).
504 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
505 HygieneData::with(|data| data.adjust(self, expn_id))
508 /// Like `SyntaxContext::adjust`, but also normalizes `self` to macros 2.0.
509 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
510 HygieneData::with(|data| {
511 *self = data.normalize_to_macros_2_0(*self);
512 data.adjust(self, expn_id)
516 /// Adjust this context for resolution in a scope created by the given expansion
517 /// via a glob import with the given `SyntaxContext`.
522 /// macro m($i:ident) {
524 /// pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
525 /// pub fn $i() {} // `$i`'s `SyntaxContext` is empty.
528 /// macro n($j:ident) {
530 /// f(); // `f`'s `SyntaxContext` has a mark from `m` and a mark from `n`
531 /// //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::f`.
532 /// $i(); // `$i`'s `SyntaxContext` has a mark from `n`
533 /// //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::$i`.
534 /// $j(); // `$j`'s `SyntaxContext` has a mark from `m`
535 /// //^ This cannot be glob-adjusted, so this is a resolution error.
539 /// This returns `None` if the context cannot be glob-adjusted.
540 /// Otherwise, it returns the scope to use when privacy checking (see `adjust` for details).
541 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
542 HygieneData::with(|data| {
543 let mut scope = None;
544 let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
545 while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
546 scope = Some(data.remove_mark(&mut glob_ctxt).0);
547 if data.remove_mark(self).0 != scope.unwrap() {
551 if data.adjust(self, expn_id).is_some() {
558 /// Undo `glob_adjust` if possible:
561 /// if let Some(privacy_checking_scope) = self.reverse_glob_adjust(expansion, glob_ctxt) {
562 /// assert!(self.glob_adjust(expansion, glob_ctxt) == Some(privacy_checking_scope));
565 pub fn reverse_glob_adjust(
569 ) -> Option<Option<ExpnId>> {
570 HygieneData::with(|data| {
571 if data.adjust(self, expn_id).is_some() {
575 let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
576 let mut marks = Vec::new();
577 while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
578 marks.push(data.remove_mark(&mut glob_ctxt));
581 let scope = marks.last().map(|mark| mark.0);
582 while let Some((expn_id, transparency)) = marks.pop() {
583 *self = data.apply_mark(*self, expn_id, transparency);
589 pub fn hygienic_eq(self, other: SyntaxContext, expn_id: ExpnId) -> bool {
590 HygieneData::with(|data| {
591 let mut self_normalized = data.normalize_to_macros_2_0(self);
592 data.adjust(&mut self_normalized, expn_id);
593 self_normalized == data.normalize_to_macros_2_0(other)
598 pub fn normalize_to_macros_2_0(self) -> SyntaxContext {
599 HygieneData::with(|data| data.normalize_to_macros_2_0(self))
603 pub fn normalize_to_macro_rules(self) -> SyntaxContext {
604 HygieneData::with(|data| data.normalize_to_macro_rules(self))
608 pub fn outer_expn(self) -> ExpnId {
609 HygieneData::with(|data| data.outer_expn(self))
612 /// `ctxt.outer_expn_data()` is equivalent to but faster than
613 /// `ctxt.outer_expn().expn_data()`.
615 pub fn outer_expn_data(self) -> ExpnData {
616 HygieneData::with(|data| data.expn_data(data.outer_expn(self)).clone())
620 pub fn outer_mark(self) -> (ExpnId, Transparency) {
621 HygieneData::with(|data| data.outer_mark(self))
625 pub fn outer_mark_with_data(self) -> (ExpnId, Transparency, ExpnData) {
626 HygieneData::with(|data| {
627 let (expn_id, transparency) = data.outer_mark(self);
628 (expn_id, transparency, data.expn_data(expn_id).clone())
632 pub fn dollar_crate_name(self) -> Symbol {
633 HygieneData::with(|data| data.syntax_context_data[self.0 as usize].dollar_crate_name)
637 impl fmt::Debug for SyntaxContext {
638 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
639 write!(f, "#{}", self.0)
644 /// Creates a fresh expansion with given properties.
645 /// Expansions are normally created by macros, but in some cases expansions are created for
646 /// other compiler-generated code to set per-span properties like allowed unstable features.
647 /// The returned span belongs to the created expansion and has the new properties,
648 /// but its location is inherited from the current span.
649 pub fn fresh_expansion(self, expn_data: ExpnData) -> Span {
650 self.fresh_expansion_with_transparency(expn_data, Transparency::Transparent)
653 pub fn fresh_expansion_with_transparency(
656 transparency: Transparency,
658 HygieneData::with(|data| {
659 let expn_id = data.fresh_expn(Some(expn_data));
660 self.with_ctxt(data.apply_mark(SyntaxContext::root(), expn_id, transparency))
665 /// A subset of properties from both macro definition and macro call available through global data.
666 /// Avoid using this if you have access to the original definition or call structures.
667 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable_Generic)]
668 pub struct ExpnData {
669 // --- The part unique to each expansion.
670 /// The kind of this expansion - macro or compiler desugaring.
672 /// The expansion that produced this expansion.
674 /// The location of the actual macro invocation or syntax sugar , e.g.
675 /// `let x = foo!();` or `if let Some(y) = x {}`
677 /// This may recursively refer to other macro invocations, e.g., if
678 /// `foo!()` invoked `bar!()` internally, and there was an
679 /// expression inside `bar!`; the call_site of the expression in
680 /// the expansion would point to the `bar!` invocation; that
681 /// call_site span would have its own ExpnData, with the call_site
682 /// pointing to the `foo!` invocation.
685 // --- The part specific to the macro/desugaring definition.
686 // --- It may be reasonable to share this part between expansions with the same definition,
687 // --- but such sharing is known to bring some minor inconveniences without also bringing
688 // --- noticeable perf improvements (PR #62898).
689 /// The span of the macro definition (possibly dummy).
690 /// This span serves only informational purpose and is not used for resolution.
692 /// List of `#[unstable]`/feature-gated features that the macro is allowed to use
693 /// internally without forcing the whole crate to opt-in
695 pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
696 /// Whether the macro is allowed to use `unsafe` internally
697 /// even if the user crate has `#![forbid(unsafe_code)]`.
698 pub allow_internal_unsafe: bool,
699 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`)
700 /// for a given macro.
701 pub local_inner_macros: bool,
702 /// Edition of the crate in which the macro is defined.
703 pub edition: Edition,
704 /// The `DefId` of the macro being invoked,
705 /// if this `ExpnData` corresponds to a macro invocation
706 pub macro_def_id: Option<DefId>,
707 /// The crate that originally created this `ExpnData. During
708 /// metadata serialization, we only encode `ExpnData`s that were
709 /// created locally - when our serialized metadata is decoded,
710 /// foreign `ExpnId`s will have their `ExpnData` looked up
711 /// from the crate specified by `Crate
713 /// The raw that this `ExpnData` had in its original crate.
714 /// An `ExpnData` can be created before being assigned an `ExpnId`,
715 /// so this might be `None` until `set_expn_data` is called
716 // This is used only for serialization/deserialization purposes:
717 // two `ExpnData`s that differ only in their `orig_id` should
718 // be considered equivalent.
719 #[stable_hasher(ignore)]
720 pub orig_id: Option<u32>,
723 // This would require special handling of `orig_id` and `parent`
724 impl !PartialEq for ExpnData {}
727 /// Constructs expansion data with default properties.
732 macro_def_id: Option<DefId>,
736 parent: ExpnId::root(),
739 allow_internal_unstable: None,
740 allow_internal_unsafe: false,
741 local_inner_macros: false,
749 pub fn allow_unstable(
753 allow_internal_unstable: Lrc<[Symbol]>,
754 macro_def_id: Option<DefId>,
757 allow_internal_unstable: Some(allow_internal_unstable),
758 ..ExpnData::default(kind, call_site, edition, macro_def_id)
763 pub fn is_root(&self) -> bool {
764 if let ExpnKind::Root = self.kind { true } else { false }
769 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
771 /// No expansion, aka root expansion. Only `ExpnId::root()` has this kind.
773 /// Expansion produced by a macro.
774 Macro(MacroKind, Symbol),
775 /// Transform done by the compiler on the AST.
777 /// Desugaring done by the compiler during HIR lowering.
778 Desugaring(DesugaringKind),
782 pub fn descr(&self) -> String {
784 ExpnKind::Root => kw::PathRoot.to_string(),
785 ExpnKind::Macro(macro_kind, name) => match macro_kind {
786 MacroKind::Bang => format!("{}!", name),
787 MacroKind::Attr => format!("#[{}]", name),
788 MacroKind::Derive => format!("#[derive({})]", name),
790 ExpnKind::AstPass(kind) => kind.descr().to_string(),
791 ExpnKind::Desugaring(kind) => format!("desugaring of {}", kind.descr()),
796 /// The kind of macro invocation or definition.
797 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
798 #[derive(HashStable_Generic)]
800 /// A bang macro `foo!()`.
802 /// An attribute macro `#[foo]`.
804 /// A derive macro `#[derive(Foo)]`
809 pub fn descr(self) -> &'static str {
811 MacroKind::Bang => "macro",
812 MacroKind::Attr => "attribute macro",
813 MacroKind::Derive => "derive macro",
817 pub fn descr_expected(self) -> &'static str {
819 MacroKind::Attr => "attribute",
824 pub fn article(self) -> &'static str {
826 MacroKind::Attr => "an",
832 /// The kind of AST transform.
833 #[derive(Clone, Copy, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
841 fn descr(self) -> &'static str {
843 AstPass::StdImports => "standard library imports",
844 AstPass::TestHarness => "test harness",
845 AstPass::ProcMacroHarness => "proc macro harness",
850 /// The kind of compiler desugaring.
851 #[derive(Clone, Copy, PartialEq, Debug, RustcEncodable, RustcDecodable, HashStable_Generic)]
852 pub enum DesugaringKind {
853 /// We desugar `if c { i } else { e }` to `match $ExprKind::Use(c) { true => i, _ => e }`.
854 /// However, we do not want to blame `c` for unreachability but rather say that `i`
855 /// is unreachable. This desugaring kind allows us to avoid blaming `c`.
856 /// This also applies to `while` loops.
860 /// Desugaring of an `impl Trait` in return type position
861 /// to an `type Foo = impl Trait;` and replacing the
862 /// `impl Trait` with `Foo`.
869 /// A location in the desugaring of a `for` loop
870 #[derive(Clone, Copy, PartialEq, Debug, RustcEncodable, RustcDecodable, HashStable_Generic)]
871 pub enum ForLoopLoc {
876 impl DesugaringKind {
877 /// The description wording should combine well with "desugaring of {}".
878 fn descr(self) -> &'static str {
880 DesugaringKind::CondTemporary => "`if` or `while` condition",
881 DesugaringKind::Async => "`async` block or function",
882 DesugaringKind::Await => "`await` expression",
883 DesugaringKind::QuestionMark => "operator `?`",
884 DesugaringKind::TryBlock => "`try` block",
885 DesugaringKind::OpaqueTy => "`impl Trait`",
886 DesugaringKind::ForLoop(_) => "`for` loop",
891 impl UseSpecializedEncodable for ExpnId {}
892 impl UseSpecializedDecodable for ExpnId {}
895 pub struct HygieneEncodeContext {
896 /// All `SyntaxContexts` for which we have written `SyntaxContextData` into crate metadata.
897 /// This is `None` after we finish encoding `SyntaxContexts`, to ensure
898 /// that we don't accidentally try to encode any more `SyntaxContexts`
899 serialized_ctxts: Lock<FxHashSet<SyntaxContext>>,
900 /// The `SyntaxContexts` that we have serialized (e.g. as a result of encoding `Spans`)
901 /// in the most recent 'round' of serializnig. Serializing `SyntaxContextData`
902 /// may cause us to serialize more `SyntaxContext`s, so serialize in a loop
903 /// until we reach a fixed point.
904 latest_ctxts: Lock<FxHashSet<SyntaxContext>>,
906 serialized_expns: Lock<FxHashSet<ExpnId>>,
908 latest_expns: Lock<FxHashSet<ExpnId>>,
911 impl HygieneEncodeContext {
915 F: FnMut(&mut T, u32, &SyntaxContextData) -> Result<(), R>,
916 G: FnMut(&mut T, u32, &ExpnData) -> Result<(), R>,
923 // When we serialize a `SyntaxContextData`, we may end up serializing
924 // a `SyntaxContext` that we haven't seen before
925 while !self.latest_ctxts.lock().is_empty() || !self.latest_expns.lock().is_empty() {
927 "encode_hygiene: Serializing a round of {:?} SyntaxContextDatas: {:?}",
928 self.latest_ctxts.lock().len(),
932 // Consume the current round of SyntaxContexts.
933 // Drop the lock() temporary early
934 let latest_ctxts = { std::mem::take(&mut *self.latest_ctxts.lock()) };
936 // It's fine to iterate over a HashMap, because the serialization
937 // of the table that we insert data into doesn't depend on insertion
939 for_all_ctxts_in(latest_ctxts.into_iter(), |(index, ctxt, data)| {
940 if self.serialized_ctxts.lock().insert(ctxt) {
941 encode_ctxt(encoder, index, data)?;
946 let latest_expns = { std::mem::take(&mut *self.latest_expns.lock()) };
948 for_all_expns_in(latest_expns.into_iter(), |index, expn, data| {
949 if self.serialized_expns.lock().insert(expn) {
950 encode_expn(encoder, index, data)?;
955 debug!("encode_hygiene: Done serializing SyntaxContextData");
961 /// Additional information used to assist in decoding hygiene data
962 pub struct HygieneDecodeContext {
963 // Maps serialized `SyntaxContext` ids to a `SyntaxContext` in the current
964 // global `HygieneData`. When we deserialize a `SyntaxContext`, we need to create
965 // a new id in the global `HygieneData`. This map tracks the ID we end up picking,
966 // so that multiple occurrences of the same serialized id are decoded to the same
968 remapped_ctxts: Lock<Vec<Option<SyntaxContext>>>,
969 // The same as `remapepd_ctxts`, but for `ExpnId`s
970 remapped_expns: Lock<Vec<Option<ExpnId>>>,
973 pub fn decode_expn_id<
976 F: FnOnce(&mut D, u32) -> Result<ExpnData, D::Error>,
977 G: FnOnce(CrateNum) -> &'a HygieneDecodeContext,
980 mode: ExpnDataDecodeMode<'a, G>,
982 ) -> Result<ExpnId, D::Error> {
983 let index = u32::decode(d)?;
984 let context = match mode {
985 ExpnDataDecodeMode::IncrComp(context) => context,
986 ExpnDataDecodeMode::Metadata(get_context) => {
987 let krate = CrateNum::decode(d)?;
992 // Do this after decoding, so that we decode a `CrateNum`
994 if index == ExpnId::root().as_u32() {
995 debug!("decode_expn_id: deserialized root");
996 return Ok(ExpnId::root());
999 let outer_expns = &context.remapped_expns;
1001 // Ensure that the lock() temporary is dropped early
1003 if let Some(expn_id) = outer_expns.lock().get(index as usize).copied().flatten() {
1008 // Don't decode the data inside `HygieneData::with`, since we need to recursively decode
1010 let mut expn_data = decode_data(d, index)?;
1012 let expn_id = HygieneData::with(|hygiene_data| {
1013 let expn_id = ExpnId(hygiene_data.expn_data.len() as u32);
1015 // If we just deserialized an `ExpnData` owned by
1016 // the local crate, its `orig_id` will be stale,
1017 // so we need to update it to its own value.
1018 // This only happens when we deserialize the incremental cache,
1019 // since a crate will never decode its own metadata.
1020 if expn_data.krate == LOCAL_CRATE {
1021 expn_data.orig_id = Some(expn_id.0);
1024 hygiene_data.expn_data.push(Some(expn_data));
1026 let mut expns = outer_expns.lock();
1027 let new_len = index as usize + 1;
1028 if expns.len() < new_len {
1029 expns.resize(new_len, None);
1031 expns[index as usize] = Some(expn_id);
1038 // Decodes `SyntaxContext`, using the provided `HygieneDecodeContext`
1039 // to track which `SyntaxContext`s we have already decoded.
1040 // The provided closure will be invoked to deserialize a `SyntaxContextData`
1041 // if we haven't already seen the id of the `SyntaxContext` we are deserializing.
1042 pub fn decode_syntax_context<
1044 F: FnOnce(&mut D, u32) -> Result<SyntaxContextData, D::Error>,
1047 context: &HygieneDecodeContext,
1049 ) -> Result<SyntaxContext, D::Error> {
1050 let raw_id: u32 = Decodable::decode(d)?;
1052 debug!("decode_syntax_context: deserialized root");
1053 // The root is special
1054 return Ok(SyntaxContext::root());
1057 let outer_ctxts = &context.remapped_ctxts;
1059 // Ensure that the lock() temporary is dropped early
1061 if let Some(ctxt) = outer_ctxts.lock().get(raw_id as usize).copied().flatten() {
1066 // Allocate and store SyntaxContext id *before* calling the decoder function,
1067 // as the SyntaxContextData may reference itself.
1068 let new_ctxt = HygieneData::with(|hygiene_data| {
1069 let new_ctxt = SyntaxContext(hygiene_data.syntax_context_data.len() as u32);
1070 // Push a dummy SyntaxContextData to ensure that nobody else can get the
1071 // same ID as us. This will be overwritten after call `decode_Data`
1072 hygiene_data.syntax_context_data.push(SyntaxContextData {
1073 outer_expn: ExpnId::root(),
1074 outer_transparency: Transparency::Transparent,
1075 parent: SyntaxContext::root(),
1076 opaque: SyntaxContext::root(),
1077 opaque_and_semitransparent: SyntaxContext::root(),
1078 dollar_crate_name: kw::Invalid,
1080 let mut ctxts = outer_ctxts.lock();
1081 let new_len = raw_id as usize + 1;
1082 if ctxts.len() < new_len {
1083 ctxts.resize(new_len, None);
1085 ctxts[raw_id as usize] = Some(new_ctxt);
1090 // Don't try to decode data while holding the lock, since we need to
1091 // be able to recursively decode a SyntaxContext
1092 let mut ctxt_data = decode_data(d, raw_id)?;
1093 // Reset `dollar_crate_name` so that it will be updated by `update_dollar_crate_names`
1094 // We don't care what the encoding crate set this to - we want to resolve it
1095 // from the perspective of the current compilation session
1096 ctxt_data.dollar_crate_name = kw::DollarCrate;
1098 // Overwrite the dummy data with our decoded SyntaxContextData
1099 HygieneData::with(|hygiene_data| {
1100 let dummy = std::mem::replace(
1101 &mut hygiene_data.syntax_context_data[new_ctxt.as_u32() as usize],
1104 // Make sure nothing weird happening while `decode_data` was running
1105 assert_eq!(dummy.dollar_crate_name, kw::Invalid);
1111 pub fn num_syntax_ctxts() -> usize {
1112 HygieneData::with(|data| data.syntax_context_data.len())
1115 pub fn for_all_ctxts_in<E, F: FnMut((u32, SyntaxContext, &SyntaxContextData)) -> Result<(), E>>(
1116 ctxts: impl Iterator<Item = SyntaxContext>,
1118 ) -> Result<(), E> {
1119 let all_data: Vec<_> = HygieneData::with(|data| {
1120 ctxts.map(|ctxt| (ctxt, data.syntax_context_data[ctxt.0 as usize].clone())).collect()
1122 for (ctxt, data) in all_data.into_iter() {
1123 f((ctxt.0, ctxt, &data))?;
1128 pub fn for_all_expns_in<E, F: FnMut(u32, ExpnId, &ExpnData) -> Result<(), E>>(
1129 expns: impl Iterator<Item = ExpnId>,
1131 ) -> Result<(), E> {
1132 let all_data: Vec<_> = HygieneData::with(|data| {
1133 expns.map(|expn| (expn, data.expn_data[expn.0 as usize].clone())).collect()
1135 for (expn, data) in all_data.into_iter() {
1136 f(expn.0, expn, &data.unwrap_or_else(|| panic!("Missing data for {:?}", expn)))?;
1140 pub fn for_all_data<E, F: FnMut((u32, SyntaxContext, &SyntaxContextData)) -> Result<(), E>>(
1142 ) -> Result<(), E> {
1143 let all_data = HygieneData::with(|data| data.syntax_context_data.clone());
1144 for (i, data) in all_data.into_iter().enumerate() {
1145 f((i as u32, SyntaxContext(i as u32), &data))?;
1150 pub fn for_all_expn_data<E, F: FnMut(u32, &ExpnData) -> Result<(), E>>(mut f: F) -> Result<(), E> {
1151 let all_data = HygieneData::with(|data| data.expn_data.clone());
1152 for (i, data) in all_data.into_iter().enumerate() {
1153 f(i as u32, &data.unwrap_or_else(|| panic!("Missing ExpnData!")))?;
1158 pub fn raw_encode_syntax_context<E: Encoder>(
1159 ctxt: SyntaxContext,
1160 context: &HygieneEncodeContext,
1162 ) -> Result<(), E::Error> {
1163 if !context.serialized_ctxts.lock().contains(&ctxt) {
1164 context.latest_ctxts.lock().insert(ctxt);
1169 pub fn raw_encode_expn_id<E: Encoder>(
1171 context: &HygieneEncodeContext,
1172 mode: ExpnDataEncodeMode,
1174 ) -> Result<(), E::Error> {
1175 // Record the fact that we need to serialize the corresponding
1177 let needs_data = || {
1178 if !context.serialized_expns.lock().contains(&expn) {
1179 context.latest_expns.lock().insert(expn);
1184 ExpnDataEncodeMode::IncrComp => {
1185 // Always serialize the `ExpnData` in incr comp mode
1189 ExpnDataEncodeMode::Metadata => {
1190 let data = expn.expn_data();
1191 // We only need to serialize the ExpnData
1192 // if it comes from this crate.
1193 // We currently don't serialize any hygiene information data for
1194 // proc-macro crates: see the `SpecializedEncoder<Span>` impl
1195 // for crate metadata.
1196 if data.krate == LOCAL_CRATE {
1199 data.orig_id.expect("Missing orig_id").encode(e)?;
1200 data.krate.encode(e)
1205 pub enum ExpnDataEncodeMode {
1210 pub enum ExpnDataDecodeMode<'a, F: FnOnce(CrateNum) -> &'a HygieneDecodeContext> {
1211 IncrComp(&'a HygieneDecodeContext),
1215 impl<'a> ExpnDataDecodeMode<'a, Box<dyn FnOnce(CrateNum) -> &'a HygieneDecodeContext>> {
1216 pub fn incr_comp(ctxt: &'a HygieneDecodeContext) -> Self {
1217 ExpnDataDecodeMode::IncrComp(ctxt)
1221 impl UseSpecializedEncodable for SyntaxContext {}
1222 impl UseSpecializedDecodable for SyntaxContext {}