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;
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.
83 pub(crate) const NUM_TRANSPARENCIES: usize = 3;
86 pub fn fresh(expn_data: Option<ExpnData>) -> Self {
87 HygieneData::with(|data| data.fresh_expn(expn_data))
90 /// The ID of the theoretical expansion that generates freshly parsed, unexpanded AST.
92 pub fn root() -> Self {
97 pub fn as_u32(self) -> u32 {
102 pub fn from_u32(raw: u32) -> ExpnId {
107 pub fn expn_data(self) -> ExpnData {
108 HygieneData::with(|data| data.expn_data(self).clone())
112 pub fn set_expn_data(self, mut expn_data: ExpnData) {
113 HygieneData::with(|data| {
114 let old_expn_data = &mut data.expn_data[self.0 as usize];
115 assert!(old_expn_data.is_none(), "expansion data is reset for an expansion ID");
116 expn_data.orig_id.replace(self.as_u32()).expect_none("orig_id should be None");
117 *old_expn_data = Some(expn_data);
121 pub fn is_descendant_of(self, ancestor: ExpnId) -> bool {
122 HygieneData::with(|data| data.is_descendant_of(self, ancestor))
125 /// `expn_id.outer_expn_is_descendant_of(ctxt)` is equivalent to but faster than
126 /// `expn_id.is_descendant_of(ctxt.outer_expn())`.
127 pub fn outer_expn_is_descendant_of(self, ctxt: SyntaxContext) -> bool {
128 HygieneData::with(|data| data.is_descendant_of(self, data.outer_expn(ctxt)))
131 /// Returns span for the macro which originally caused this expansion to happen.
133 /// Stops backtracing at include! boundary.
134 pub fn expansion_cause(mut self) -> Option<Span> {
135 let mut last_macro = None;
137 let expn_data = self.expn_data();
138 // Stop going up the backtrace once include! is encountered
139 if expn_data.is_root()
140 || expn_data.kind == ExpnKind::Macro(MacroKind::Bang, sym::include)
144 self = expn_data.call_site.ctxt().outer_expn();
145 last_macro = Some(expn_data.call_site);
152 pub struct HygieneData {
153 /// Each expansion should have an associated expansion data, but sometimes there's a delay
154 /// between creation of an expansion ID and obtaining its data (e.g. macros are collected
155 /// first and then resolved later), so we use an `Option` here.
156 expn_data: Vec<Option<ExpnData>>,
157 syntax_context_data: Vec<SyntaxContextData>,
158 syntax_context_map: FxHashMap<(SyntaxContext, ExpnId, Transparency), SyntaxContext>,
162 crate fn new(edition: Edition) -> Self {
163 let mut root_data = ExpnData::default(
167 Some(DefId::local(CRATE_DEF_INDEX)),
169 root_data.orig_id = Some(0);
172 expn_data: vec![Some(root_data)],
173 syntax_context_data: vec![SyntaxContextData {
174 outer_expn: ExpnId::root(),
175 outer_transparency: Transparency::Opaque,
176 parent: SyntaxContext(0),
177 opaque: SyntaxContext(0),
178 opaque_and_semitransparent: SyntaxContext(0),
179 dollar_crate_name: kw::DollarCrate,
181 syntax_context_map: FxHashMap::default(),
185 pub fn with<T, F: FnOnce(&mut HygieneData) -> T>(f: F) -> T {
186 SESSION_GLOBALS.with(|session_globals| f(&mut *session_globals.hygiene_data.borrow_mut()))
189 fn fresh_expn(&mut self, mut expn_data: Option<ExpnData>) -> ExpnId {
190 let raw_id = self.expn_data.len() as u32;
191 if let Some(data) = expn_data.as_mut() {
192 data.orig_id.replace(raw_id).expect_none("orig_id should be None");
194 self.expn_data.push(expn_data);
198 fn expn_data(&self, expn_id: ExpnId) -> &ExpnData {
199 self.expn_data[expn_id.0 as usize].as_ref().expect("no expansion data for an expansion ID")
202 fn is_descendant_of(&self, mut expn_id: ExpnId, ancestor: ExpnId) -> bool {
203 while expn_id != ancestor {
204 if expn_id == ExpnId::root() {
207 expn_id = self.expn_data(expn_id).parent;
212 fn normalize_to_macros_2_0(&self, ctxt: SyntaxContext) -> SyntaxContext {
213 self.syntax_context_data[ctxt.0 as usize].opaque
216 fn normalize_to_macro_rules(&self, ctxt: SyntaxContext) -> SyntaxContext {
217 self.syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent
220 fn outer_expn(&self, ctxt: SyntaxContext) -> ExpnId {
221 self.syntax_context_data[ctxt.0 as usize].outer_expn
224 fn outer_mark(&self, ctxt: SyntaxContext) -> (ExpnId, Transparency) {
225 let data = &self.syntax_context_data[ctxt.0 as usize];
226 (data.outer_expn, data.outer_transparency)
229 fn parent_ctxt(&self, ctxt: SyntaxContext) -> SyntaxContext {
230 self.syntax_context_data[ctxt.0 as usize].parent
233 fn remove_mark(&self, ctxt: &mut SyntaxContext) -> (ExpnId, Transparency) {
234 let outer_mark = self.outer_mark(*ctxt);
235 *ctxt = self.parent_ctxt(*ctxt);
239 fn marks(&self, mut ctxt: SyntaxContext) -> Vec<(ExpnId, Transparency)> {
240 let mut marks = Vec::new();
241 while ctxt != SyntaxContext::root() {
242 debug!("marks: getting parent of {:?}", ctxt);
243 marks.push(self.outer_mark(ctxt));
244 ctxt = self.parent_ctxt(ctxt);
250 fn walk_chain(&self, mut span: Span, to: SyntaxContext) -> Span {
251 debug!("walk_chain({:?}, {:?})", span, to);
252 debug!("walk_chain: span ctxt = {:?}", span.ctxt());
253 while span.from_expansion() && span.ctxt() != to {
254 let outer_expn = self.outer_expn(span.ctxt());
255 debug!("walk_chain({:?}): outer_expn={:?}", span, outer_expn);
256 let expn_data = self.expn_data(outer_expn);
257 debug!("walk_chain({:?}): expn_data={:?}", span, expn_data);
258 span = expn_data.call_site;
263 fn adjust(&self, ctxt: &mut SyntaxContext, expn_id: ExpnId) -> Option<ExpnId> {
264 let mut scope = None;
265 while !self.is_descendant_of(expn_id, self.outer_expn(*ctxt)) {
266 scope = Some(self.remove_mark(ctxt).0);
275 transparency: Transparency,
277 assert_ne!(expn_id, ExpnId::root());
278 if transparency == Transparency::Opaque {
279 return self.apply_mark_internal(ctxt, expn_id, transparency);
282 let call_site_ctxt = self.expn_data(expn_id).call_site.ctxt();
283 let mut call_site_ctxt = if transparency == Transparency::SemiTransparent {
284 self.normalize_to_macros_2_0(call_site_ctxt)
286 self.normalize_to_macro_rules(call_site_ctxt)
289 if call_site_ctxt == SyntaxContext::root() {
290 return self.apply_mark_internal(ctxt, expn_id, transparency);
293 // Otherwise, `expn_id` is a macros 1.0 definition and the call site is in a
294 // macros 2.0 expansion, i.e., a macros 1.0 invocation is in a macros 2.0 definition.
296 // In this case, the tokens from the macros 1.0 definition inherit the hygiene
297 // at their invocation. That is, we pretend that the macros 1.0 definition
298 // was defined at its invocation (i.e., inside the macros 2.0 definition)
299 // so that the macros 2.0 definition remains hygienic.
301 // See the example at `test/ui/hygiene/legacy_interaction.rs`.
302 for (expn_id, transparency) in self.marks(ctxt) {
303 call_site_ctxt = self.apply_mark_internal(call_site_ctxt, expn_id, transparency);
305 self.apply_mark_internal(call_site_ctxt, expn_id, transparency)
308 fn apply_mark_internal(
312 transparency: Transparency,
314 let syntax_context_data = &mut self.syntax_context_data;
315 let mut opaque = syntax_context_data[ctxt.0 as usize].opaque;
316 let mut opaque_and_semitransparent =
317 syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent;
319 if transparency >= Transparency::Opaque {
323 .entry((parent, expn_id, transparency))
325 let new_opaque = SyntaxContext(syntax_context_data.len() as u32);
326 syntax_context_data.push(SyntaxContextData {
328 outer_transparency: transparency,
331 opaque_and_semitransparent: new_opaque,
332 dollar_crate_name: kw::DollarCrate,
338 if transparency >= Transparency::SemiTransparent {
339 let parent = opaque_and_semitransparent;
340 opaque_and_semitransparent = *self
342 .entry((parent, expn_id, transparency))
344 let new_opaque_and_semitransparent =
345 SyntaxContext(syntax_context_data.len() as u32);
346 syntax_context_data.push(SyntaxContextData {
348 outer_transparency: transparency,
351 opaque_and_semitransparent: new_opaque_and_semitransparent,
352 dollar_crate_name: kw::DollarCrate,
354 new_opaque_and_semitransparent
359 *self.syntax_context_map.entry((parent, expn_id, transparency)).or_insert_with(|| {
360 let new_opaque_and_semitransparent_and_transparent =
361 SyntaxContext(syntax_context_data.len() as u32);
362 syntax_context_data.push(SyntaxContextData {
364 outer_transparency: transparency,
367 opaque_and_semitransparent,
368 dollar_crate_name: kw::DollarCrate,
370 new_opaque_and_semitransparent_and_transparent
375 pub fn clear_syntax_context_map() {
376 HygieneData::with(|data| data.syntax_context_map = FxHashMap::default());
379 pub fn walk_chain(span: Span, to: SyntaxContext) -> Span {
380 HygieneData::with(|data| data.walk_chain(span, to))
383 pub fn update_dollar_crate_names(mut get_name: impl FnMut(SyntaxContext) -> Symbol) {
384 // The new contexts that need updating are at the end of the list and have `$crate` as a name.
385 let (len, to_update) = HygieneData::with(|data| {
387 data.syntax_context_data.len(),
388 data.syntax_context_data
391 .take_while(|scdata| scdata.dollar_crate_name == kw::DollarCrate)
395 // The callback must be called from outside of the `HygieneData` lock,
396 // since it will try to acquire it too.
397 let range_to_update = len - to_update..len;
399 range_to_update.clone().map(|idx| get_name(SyntaxContext::from_u32(idx as u32))).collect();
400 HygieneData::with(|data| {
401 range_to_update.zip(names.into_iter()).for_each(|(idx, name)| {
402 data.syntax_context_data[idx].dollar_crate_name = name;
407 pub fn debug_hygiene_data(verbose: bool) -> String {
408 HygieneData::with(|data| {
410 format!("{:#?}", data)
412 let mut s = String::from("");
413 s.push_str("Expansions:");
414 data.expn_data.iter().enumerate().for_each(|(id, expn_info)| {
415 let expn_info = expn_info.as_ref().expect("no expansion data for an expansion ID");
417 "\n{}: parent: {:?}, call_site_ctxt: {:?}, def_site_ctxt: {:?}, kind: {:?}",
420 expn_info.call_site.ctxt(),
421 expn_info.def_site.ctxt(),
425 s.push_str("\n\nSyntaxContexts:");
426 data.syntax_context_data.iter().enumerate().for_each(|(id, ctxt)| {
428 "\n#{}: parent: {:?}, outer_mark: ({:?}, {:?})",
429 id, ctxt.parent, ctxt.outer_expn, ctxt.outer_transparency,
439 pub const fn root() -> Self {
444 crate fn as_u32(self) -> u32 {
449 crate fn from_u32(raw: u32) -> SyntaxContext {
453 /// Extend a syntax context with a given expansion and transparency.
454 crate fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> SyntaxContext {
455 HygieneData::with(|data| data.apply_mark(self, expn_id, transparency))
458 /// Pulls a single mark off of the syntax context. This effectively moves the
459 /// context up one macro definition level. That is, if we have a nested macro
460 /// definition as follows:
470 /// and we have a SyntaxContext that is referring to something declared by an invocation
471 /// of g (call it g1), calling remove_mark will result in the SyntaxContext for the
472 /// invocation of f that created g1.
473 /// Returns the mark that was removed.
474 pub fn remove_mark(&mut self) -> ExpnId {
475 HygieneData::with(|data| data.remove_mark(self).0)
478 pub fn marks(self) -> Vec<(ExpnId, Transparency)> {
479 HygieneData::with(|data| data.marks(self))
482 /// Adjust this context for resolution in a scope created by the given expansion.
483 /// For example, consider the following three resolutions of `f`:
486 /// mod foo { pub fn f() {} } // `f`'s `SyntaxContext` is empty.
488 /// macro m($f:ident) {
490 /// pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
491 /// pub fn $f() {} // `$f`'s `SyntaxContext` is empty.
493 /// foo::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
494 /// //^ Since `mod foo` is outside this expansion, `adjust` removes the mark from `f`,
495 /// //| and it resolves to `::foo::f`.
496 /// bar::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
497 /// //^ Since `mod bar` not outside this expansion, `adjust` does not change `f`,
498 /// //| and it resolves to `::bar::f`.
499 /// bar::$f(); // `f`'s `SyntaxContext` is empty.
500 /// //^ Since `mod bar` is not outside this expansion, `adjust` does not change `$f`,
501 /// //| and it resolves to `::bar::$f`.
504 /// This returns the expansion whose definition scope we use to privacy check the resolution,
505 /// or `None` if we privacy check as usual (i.e., not w.r.t. a macro definition scope).
506 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
507 HygieneData::with(|data| data.adjust(self, expn_id))
510 /// Like `SyntaxContext::adjust`, but also normalizes `self` to macros 2.0.
511 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
512 HygieneData::with(|data| {
513 *self = data.normalize_to_macros_2_0(*self);
514 data.adjust(self, expn_id)
518 /// Adjust this context for resolution in a scope created by the given expansion
519 /// via a glob import with the given `SyntaxContext`.
524 /// macro m($i:ident) {
526 /// pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
527 /// pub fn $i() {} // `$i`'s `SyntaxContext` is empty.
530 /// macro n($j:ident) {
532 /// f(); // `f`'s `SyntaxContext` has a mark from `m` and a mark from `n`
533 /// //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::f`.
534 /// $i(); // `$i`'s `SyntaxContext` has a mark from `n`
535 /// //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::$i`.
536 /// $j(); // `$j`'s `SyntaxContext` has a mark from `m`
537 /// //^ This cannot be glob-adjusted, so this is a resolution error.
541 /// This returns `None` if the context cannot be glob-adjusted.
542 /// Otherwise, it returns the scope to use when privacy checking (see `adjust` for details).
543 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
544 HygieneData::with(|data| {
545 let mut scope = None;
546 let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
547 while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
548 scope = Some(data.remove_mark(&mut glob_ctxt).0);
549 if data.remove_mark(self).0 != scope.unwrap() {
553 if data.adjust(self, expn_id).is_some() {
560 /// Undo `glob_adjust` if possible:
563 /// if let Some(privacy_checking_scope) = self.reverse_glob_adjust(expansion, glob_ctxt) {
564 /// assert!(self.glob_adjust(expansion, glob_ctxt) == Some(privacy_checking_scope));
567 pub fn reverse_glob_adjust(
571 ) -> Option<Option<ExpnId>> {
572 HygieneData::with(|data| {
573 if data.adjust(self, expn_id).is_some() {
577 let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
578 let mut marks = Vec::new();
579 while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
580 marks.push(data.remove_mark(&mut glob_ctxt));
583 let scope = marks.last().map(|mark| mark.0);
584 while let Some((expn_id, transparency)) = marks.pop() {
585 *self = data.apply_mark(*self, expn_id, transparency);
591 pub fn hygienic_eq(self, other: SyntaxContext, expn_id: ExpnId) -> bool {
592 HygieneData::with(|data| {
593 let mut self_normalized = data.normalize_to_macros_2_0(self);
594 data.adjust(&mut self_normalized, expn_id);
595 self_normalized == data.normalize_to_macros_2_0(other)
600 pub fn normalize_to_macros_2_0(self) -> SyntaxContext {
601 HygieneData::with(|data| data.normalize_to_macros_2_0(self))
605 pub fn normalize_to_macro_rules(self) -> SyntaxContext {
606 HygieneData::with(|data| data.normalize_to_macro_rules(self))
610 pub fn outer_expn(self) -> ExpnId {
611 HygieneData::with(|data| data.outer_expn(self))
614 /// `ctxt.outer_expn_data()` is equivalent to but faster than
615 /// `ctxt.outer_expn().expn_data()`.
617 pub fn outer_expn_data(self) -> ExpnData {
618 HygieneData::with(|data| data.expn_data(data.outer_expn(self)).clone())
622 pub fn outer_mark_with_data(self) -> (ExpnId, Transparency, ExpnData) {
623 HygieneData::with(|data| {
624 let (expn_id, transparency) = data.outer_mark(self);
625 (expn_id, transparency, data.expn_data(expn_id).clone())
629 pub fn dollar_crate_name(self) -> Symbol {
630 HygieneData::with(|data| data.syntax_context_data[self.0 as usize].dollar_crate_name)
634 impl fmt::Debug for SyntaxContext {
635 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
636 write!(f, "#{}", self.0)
641 /// Creates a fresh expansion with given properties.
642 /// Expansions are normally created by macros, but in some cases expansions are created for
643 /// other compiler-generated code to set per-span properties like allowed unstable features.
644 /// The returned span belongs to the created expansion and has the new properties,
645 /// but its location is inherited from the current span.
646 pub fn fresh_expansion(self, expn_data: ExpnData) -> Span {
647 self.fresh_expansion_with_transparency(expn_data, Transparency::Transparent)
650 pub fn fresh_expansion_with_transparency(
653 transparency: Transparency,
655 HygieneData::with(|data| {
656 let expn_id = data.fresh_expn(Some(expn_data));
657 self.with_ctxt(data.apply_mark(SyntaxContext::root(), expn_id, transparency))
662 /// A subset of properties from both macro definition and macro call available through global data.
663 /// Avoid using this if you have access to the original definition or call structures.
664 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable_Generic)]
665 pub struct ExpnData {
666 // --- The part unique to each expansion.
667 /// The kind of this expansion - macro or compiler desugaring.
669 /// The expansion that produced this expansion.
670 #[stable_hasher(ignore)]
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 if let ExpnKind::Root = self.kind { true } else { false }
767 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, 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, RustcEncodable, RustcDecodable, 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, RustcEncodable, RustcDecodable, 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, RustcEncodable, RustcDecodable, 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, RustcEncodable, RustcDecodable, 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",
889 impl UseSpecializedEncodable for ExpnId {}
890 impl UseSpecializedDecodable for ExpnId {}
892 /// Additional information used to assist in decoding hygiene data
893 pub struct HygieneContext {
894 // Maps serialized `SyntaxContext` ids to a `SyntaxContext` in the current
895 // global `HygieneData`. When we deserialize a `SyntaxContext`, we need to create
896 // a new id in the global `HygieneData`. This map tracks the ID we end up picking,
897 // so that multiple occurences of the same serialized id are decoded to the same
899 remapped_ctxts: Lock<Vec<Option<SyntaxContext>>>,
900 // The same as `remapepd_ctxts`, but for `ExpnId`s
901 remapped_expns: Lock<Vec<Option<ExpnId>>>,
904 impl HygieneContext {
905 pub fn new() -> HygieneContext {
907 remapped_ctxts: Lock::new(Vec::new()),
908 remapped_expns: Lock::new(Vec::new()),
913 pub fn decode_expn_id<
916 F: FnOnce(&mut D, u32) -> Result<ExpnData, D::Error>,
917 G: FnOnce(CrateNum) -> &'a HygieneContext,
920 mode: ExpnDataDecodeMode<'a, G>,
922 ) -> Result<ExpnId, D::Error> {
923 let index = u32::decode(d)?;
924 let context = match mode {
925 ExpnDataDecodeMode::IncrComp(context) => context,
926 ExpnDataDecodeMode::Metadata(get_context) => {
927 let krate = CrateNum::decode(d)?;
932 // Do this after decoding, so that we decode a `CrateNum`
934 if index == ExpnId::root().as_u32() {
935 debug!("decode_expn_id: deserialized root");
936 return Ok(ExpnId::root());
939 let outer_expns = &context.remapped_expns;
941 // Ensure that the lock() temporary is dropped early
943 if let Some(expn_id) = outer_expns.lock().get(index as usize).copied().flatten() {
948 // Don't decode the data inside `HygieneData::with`, since we need to recursively decode
950 let mut expn_data = decode_data(d, index)?;
952 let expn_id = HygieneData::with(|hygiene_data| {
953 let expn_id = ExpnId(hygiene_data.expn_data.len() as u32);
955 // If we just deserialized an `ExpnData` owned by
956 // the local crate, its `orig_id` will be stale,
957 // so we need to update it to its own value.
958 // This only happens when we deserialize the incremental cache,
959 // since a crate will never decode its own metadata.
960 if expn_data.krate == LOCAL_CRATE {
961 expn_data.orig_id = Some(expn_id.0);
964 hygiene_data.expn_data.push(Some(expn_data));
966 // Drop lock() temporary early
968 let mut expns = outer_expns.lock();
969 let new_len = index as usize + 1;
970 if expns.len() < new_len {
971 expns.resize(new_len, None);
973 expns[index as usize] = Some(expn_id);
980 // Decodes `SyntaxContext`, using the provided `HygieneContext`
981 // to track which `SyntaxContext`s we have already decoded.
982 // The provided closure will be invoked to deserialize a `SyntaxContextData`
983 // if we haven't already seen the id of the `SyntaxContext` we are deserializing.
984 pub fn decode_syntax_context<
986 F: FnOnce(&mut D, u32) -> Result<SyntaxContextData, D::Error>,
989 context: &HygieneContext,
991 ) -> Result<SyntaxContext, D::Error> {
992 let raw_id: u32 = Decodable::decode(d)?;
994 debug!("decode_syntax_context: deserialized root");
995 // The root is special
996 return Ok(SyntaxContext::root());
999 let outer_ctxts = &context.remapped_ctxts;
1001 // Ensure that the lock() temporary is dropped early
1003 if let Some(ctxt) = outer_ctxts.lock().get(raw_id as usize).copied().flatten() {
1008 // Allocate and store SyntaxContext id *before* calling the decoder function,
1009 // as the SyntaxContextData may reference itself.
1010 let new_ctxt = HygieneData::with(|hygiene_data| {
1011 let new_ctxt = SyntaxContext(hygiene_data.syntax_context_data.len() as u32);
1012 // Push a dummy SyntaxContextData to ensure that nobody else can get the
1013 // same ID as us. This will be overwritten after call `decode_Data`
1014 hygiene_data.syntax_context_data.push(SyntaxContextData {
1015 outer_expn: ExpnId::root(),
1016 outer_transparency: Transparency::Transparent,
1017 parent: SyntaxContext::root(),
1018 opaque: SyntaxContext::root(),
1019 opaque_and_semitransparent: SyntaxContext::root(),
1020 dollar_crate_name: kw::Invalid,
1022 // Ensure that the lock() temporary is dropped early
1024 let mut ctxts = outer_ctxts.lock();
1025 let new_len = raw_id as usize + 1;
1026 if ctxts.len() < new_len {
1027 ctxts.resize(new_len, None);
1029 ctxts[raw_id as usize] = Some(new_ctxt);
1034 // Don't try to decode data while holding the lock, since we need to
1035 // be able to recursively decode a SyntaxContext
1036 let mut ctxt_data = decode_data(d, raw_id)?;
1037 // Reset `dollar_crate_name` so that it will be updated by `update_dollar_crate_names`
1038 // We don't care what the encoding crate set this to - we want to resolve it
1039 // from the perspective of the current compilation session
1040 ctxt_data.dollar_crate_name = kw::DollarCrate;
1042 // Overwrite the dummy data with our decoded SyntaxContextData
1043 HygieneData::with(|hygiene_data| {
1044 let dummy = std::mem::replace(
1045 &mut hygiene_data.syntax_context_data[new_ctxt.as_u32() as usize],
1048 // Make sure nothing weird happening while `decode_data` was running
1049 assert_eq!(dummy.dollar_crate_name, kw::Invalid);
1052 return Ok(new_ctxt);
1055 pub fn num_syntax_ctxts() -> usize {
1056 HygieneData::with(|data| data.syntax_context_data.len())
1059 pub fn for_all_data_in<E, F: FnMut((u32, SyntaxContext, &SyntaxContextData)) -> Result<(), E>>(
1060 ctxts: impl Iterator<Item = SyntaxContext>,
1062 ) -> Result<(), E> {
1063 let all_data: Vec<_> = HygieneData::with(|data| {
1064 ctxts.map(|ctxt| (ctxt, data.syntax_context_data[ctxt.0 as usize].clone())).collect()
1066 for (ctxt, data) in all_data.into_iter() {
1067 f((ctxt.0, ctxt, &data))?;
1072 pub fn for_all_data<E, F: FnMut((u32, SyntaxContext, &SyntaxContextData)) -> Result<(), E>>(
1074 ) -> Result<(), E> {
1075 let all_data = HygieneData::with(|data| data.syntax_context_data.clone());
1076 for (i, data) in all_data.into_iter().enumerate() {
1077 f((i as u32, SyntaxContext(i as u32), &data))?;
1082 pub fn for_all_expn_data<E, F: FnMut(u32, &ExpnData) -> Result<(), E>>(mut f: F) -> Result<(), E> {
1083 let all_data = HygieneData::with(|data| data.expn_data.clone());
1084 for (i, data) in all_data.into_iter().enumerate() {
1085 f(i as u32, &data.unwrap_or_else(|| panic!("Missing ExpnData!")))?;
1090 pub fn raw_encode_syntax_context<E: Encoder>(
1091 ctxt: SyntaxContext,
1093 ) -> Result<(), E::Error> {
1097 pub fn raw_encode_expn_id<E: Encoder>(
1099 mode: ExpnDataEncodeMode,
1101 ) -> Result<(), E::Error> {
1103 ExpnDataEncodeMode::IncrComp => expn.0.encode(e),
1104 ExpnDataEncodeMode::Metadata => {
1105 let data = expn.expn_data();
1106 data.orig_id.expect("Missing orig_id").encode(e)?;
1107 data.krate.encode(e)
1112 pub enum ExpnDataEncodeMode {
1117 pub enum ExpnDataDecodeMode<'a, F: FnOnce(CrateNum) -> &'a HygieneContext> {
1118 IncrComp(&'a HygieneContext),
1122 impl<'a> ExpnDataDecodeMode<'a, Box<dyn FnOnce(CrateNum) -> &'a HygieneContext>> {
1123 pub fn incr_comp(ctxt: &'a HygieneContext) -> Self {
1124 ExpnDataDecodeMode::IncrComp(ctxt)
1128 impl UseSpecializedEncodable for SyntaxContext {}
1129 impl UseSpecializedDecodable for SyntaxContext {}