]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_pos/hygiene.rs
Add `HygieneData::apply_mark_with_transparency`.
[rust.git] / src / libsyntax_pos / hygiene.rs
1 //! Machinery for hygienic macros, inspired by the `MTWT[1]` paper.
2 //!
3 //! `[1]` Matthew Flatt, Ryan Culpepper, David Darais, and Robert Bruce Findler. 2012.
4 //! *Macros that work together: Compile-time bindings, partial expansion,
5 //! and definition contexts*. J. Funct. Program. 22, 2 (March 2012), 181-216.
6 //! DOI=10.1017/S0956796812000093 <https://doi.org/10.1017/S0956796812000093>
7
8 use crate::GLOBALS;
9 use crate::Span;
10 use crate::edition::Edition;
11 use crate::symbol::{kw, Symbol};
12
13 use serialize::{Encodable, Decodable, Encoder, Decoder};
14 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
15 use rustc_data_structures::sync::Lrc;
16 use std::{fmt, mem};
17
18 /// A SyntaxContext represents a chain of macro expansions (represented by marks).
19 #[derive(Clone, Copy, PartialEq, Eq, Default, PartialOrd, Ord, Hash)]
20 pub struct SyntaxContext(u32);
21
22 #[derive(Copy, Clone, Debug)]
23 struct SyntaxContextData {
24     outer_mark: Mark,
25     transparency: Transparency,
26     prev_ctxt: SyntaxContext,
27     /// This context, but with all transparent and semi-transparent marks filtered away.
28     opaque: SyntaxContext,
29     /// This context, but with all transparent marks filtered away.
30     opaque_and_semitransparent: SyntaxContext,
31     /// Name of the crate to which `$crate` with this context would resolve.
32     dollar_crate_name: Symbol,
33 }
34
35 /// A mark is a unique ID associated with a macro expansion.
36 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
37 pub struct Mark(u32);
38
39 #[derive(Clone, Debug)]
40 struct MarkData {
41     parent: Mark,
42     default_transparency: Transparency,
43     expn_info: Option<ExpnInfo>,
44 }
45
46 /// A property of a macro expansion that determines how identifiers
47 /// produced by that expansion are resolved.
48 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
49 pub enum Transparency {
50     /// Identifier produced by a transparent expansion is always resolved at call-site.
51     /// Call-site spans in procedural macros, hygiene opt-out in `macro` should use this.
52     Transparent,
53     /// Identifier produced by a semi-transparent expansion may be resolved
54     /// either at call-site or at definition-site.
55     /// If it's a local variable, label or `$crate` then it's resolved at def-site.
56     /// Otherwise it's resolved at call-site.
57     /// `macro_rules` macros behave like this, built-in macros currently behave like this too,
58     /// but that's an implementation detail.
59     SemiTransparent,
60     /// Identifier produced by an opaque expansion is always resolved at definition-site.
61     /// Def-site spans in procedural macros, identifiers from `macro` by default use this.
62     Opaque,
63 }
64
65 impl Mark {
66     pub fn fresh(parent: Mark) -> Self {
67         HygieneData::with(|data| {
68             data.marks.push(MarkData {
69                 parent,
70                 // By default expansions behave like `macro_rules`.
71                 default_transparency: Transparency::SemiTransparent,
72                 expn_info: None,
73             });
74             Mark(data.marks.len() as u32 - 1)
75         })
76     }
77
78     /// The mark of the theoretical expansion that generates freshly parsed, unexpanded AST.
79     #[inline]
80     pub fn root() -> Self {
81         Mark(0)
82     }
83
84     #[inline]
85     pub fn as_u32(self) -> u32 {
86         self.0
87     }
88
89     #[inline]
90     pub fn from_u32(raw: u32) -> Mark {
91         Mark(raw)
92     }
93
94     #[inline]
95     pub fn parent(self) -> Mark {
96         HygieneData::with(|data| data.marks[self.0 as usize].parent)
97     }
98
99     #[inline]
100     pub fn expn_info(self) -> Option<ExpnInfo> {
101         HygieneData::with(|data| data.expn_info(self))
102     }
103
104     #[inline]
105     pub fn set_expn_info(self, info: ExpnInfo) {
106         HygieneData::with(|data| data.marks[self.0 as usize].expn_info = Some(info))
107     }
108
109     #[inline]
110     pub fn set_default_transparency(self, transparency: Transparency) {
111         assert_ne!(self, Mark::root());
112         HygieneData::with(|data| data.marks[self.0 as usize].default_transparency = transparency)
113     }
114
115     pub fn is_descendant_of(self, ancestor: Mark) -> bool {
116         HygieneData::with(|data| data.is_descendant_of(self, ancestor))
117     }
118
119     /// `mark.outer_is_descendant_of(ctxt)` is equivalent to but faster than
120     /// `mark.is_descendant_of(ctxt.outer())`.
121     pub fn outer_is_descendant_of(self, ctxt: SyntaxContext) -> bool {
122         HygieneData::with(|data| data.is_descendant_of(self, data.outer(ctxt)))
123     }
124
125     /// Computes a mark such that both input marks are descendants of (or equal to) the returned
126     /// mark. That is, the following holds:
127     ///
128     /// ```rust
129     /// let la = least_ancestor(a, b);
130     /// assert!(a.is_descendant_of(la))
131     /// assert!(b.is_descendant_of(la))
132     /// ```
133     pub fn least_ancestor(mut a: Mark, mut b: Mark) -> Mark {
134         HygieneData::with(|data| {
135             // Compute the path from a to the root
136             let mut a_path = FxHashSet::<Mark>::default();
137             while a != Mark::root() {
138                 a_path.insert(a);
139                 a = data.marks[a.0 as usize].parent;
140             }
141
142             // While the path from b to the root hasn't intersected, move up the tree
143             while !a_path.contains(&b) {
144                 b = data.marks[b.0 as usize].parent;
145             }
146
147             b
148         })
149     }
150
151     // Used for enabling some compatibility fallback in resolve.
152     #[inline]
153     pub fn looks_like_proc_macro_derive(self) -> bool {
154         HygieneData::with(|data| {
155             let mark_data = &data.marks[self.0 as usize];
156             if mark_data.default_transparency == Transparency::Opaque {
157                 if let Some(expn_info) = &mark_data.expn_info {
158                     if let ExpnFormat::MacroAttribute(name) = expn_info.format {
159                         if name.as_str().starts_with("derive(") {
160                             return true;
161                         }
162                     }
163                 }
164             }
165             false
166         })
167     }
168 }
169
170 #[derive(Debug)]
171 crate struct HygieneData {
172     marks: Vec<MarkData>,
173     syntax_contexts: Vec<SyntaxContextData>,
174     markings: FxHashMap<(SyntaxContext, Mark, Transparency), SyntaxContext>,
175 }
176
177 impl HygieneData {
178     crate fn new() -> Self {
179         HygieneData {
180             marks: vec![MarkData {
181                 parent: Mark::root(),
182                 // If the root is opaque, then loops searching for an opaque mark
183                 // will automatically stop after reaching it.
184                 default_transparency: Transparency::Opaque,
185                 expn_info: None,
186             }],
187             syntax_contexts: vec![SyntaxContextData {
188                 outer_mark: Mark::root(),
189                 transparency: Transparency::Opaque,
190                 prev_ctxt: SyntaxContext(0),
191                 opaque: SyntaxContext(0),
192                 opaque_and_semitransparent: SyntaxContext(0),
193                 dollar_crate_name: kw::DollarCrate,
194             }],
195             markings: FxHashMap::default(),
196         }
197     }
198
199     fn with<T, F: FnOnce(&mut HygieneData) -> T>(f: F) -> T {
200         GLOBALS.with(|globals| f(&mut *globals.hygiene_data.borrow_mut()))
201     }
202
203     fn expn_info(&self, mark: Mark) -> Option<ExpnInfo> {
204         self.marks[mark.0 as usize].expn_info.clone()
205     }
206
207     fn is_descendant_of(&self, mut mark: Mark, ancestor: Mark) -> bool {
208         while mark != ancestor {
209             if mark == Mark::root() {
210                 return false;
211             }
212             mark = self.marks[mark.0 as usize].parent;
213         }
214         true
215     }
216
217     fn default_transparency(&self, mark: Mark) -> Transparency {
218         self.marks[mark.0 as usize].default_transparency
219     }
220
221     fn modern(&self, ctxt: SyntaxContext) -> SyntaxContext {
222         self.syntax_contexts[ctxt.0 as usize].opaque
223     }
224
225     fn modern_and_legacy(&self, ctxt: SyntaxContext) -> SyntaxContext {
226         self.syntax_contexts[ctxt.0 as usize].opaque_and_semitransparent
227     }
228
229     fn outer(&self, ctxt: SyntaxContext) -> Mark {
230         self.syntax_contexts[ctxt.0 as usize].outer_mark
231     }
232
233     fn transparency(&self, ctxt: SyntaxContext) -> Transparency {
234         self.syntax_contexts[ctxt.0 as usize].transparency
235     }
236
237     fn prev_ctxt(&self, ctxt: SyntaxContext) -> SyntaxContext {
238         self.syntax_contexts[ctxt.0 as usize].prev_ctxt
239     }
240
241     fn remove_mark(&self, ctxt: &mut SyntaxContext) -> Mark {
242         let outer_mark = self.syntax_contexts[ctxt.0 as usize].outer_mark;
243         *ctxt = self.prev_ctxt(*ctxt);
244         outer_mark
245     }
246
247     fn marks(&self, mut ctxt: SyntaxContext) -> Vec<(Mark, Transparency)> {
248         let mut marks = Vec::new();
249         while ctxt != SyntaxContext::empty() {
250             let outer_mark = self.outer(ctxt);
251             let transparency = self.transparency(ctxt);
252             let prev_ctxt = self.prev_ctxt(ctxt);
253             marks.push((outer_mark, transparency));
254             ctxt = prev_ctxt;
255         }
256         marks.reverse();
257         marks
258     }
259
260     fn adjust(&self, ctxt: &mut SyntaxContext, expansion: Mark) -> Option<Mark> {
261         let mut scope = None;
262         while !self.is_descendant_of(expansion, self.outer(*ctxt)) {
263             scope = Some(self.remove_mark(ctxt));
264         }
265         scope
266     }
267
268     fn apply_mark_with_transparency(&mut self, ctxt: SyntaxContext, mark: Mark,
269                                     transparency: Transparency) -> SyntaxContext {
270         assert_ne!(mark, Mark::root());
271         if transparency == Transparency::Opaque {
272             return self.apply_mark_internal(ctxt, mark, transparency);
273         }
274
275         let call_site_ctxt =
276             self.expn_info(mark).map_or(SyntaxContext::empty(), |info| info.call_site.ctxt());
277         let mut call_site_ctxt = if transparency == Transparency::SemiTransparent {
278             self.modern(call_site_ctxt)
279         } else {
280             self.modern_and_legacy(call_site_ctxt)
281         };
282
283         if call_site_ctxt == SyntaxContext::empty() {
284             return self.apply_mark_internal(ctxt, mark, transparency);
285         }
286
287         // Otherwise, `mark` is a macros 1.0 definition and the call site is in a
288         // macros 2.0 expansion, i.e., a macros 1.0 invocation is in a macros 2.0 definition.
289         //
290         // In this case, the tokens from the macros 1.0 definition inherit the hygiene
291         // at their invocation. That is, we pretend that the macros 1.0 definition
292         // was defined at its invocation (i.e., inside the macros 2.0 definition)
293         // so that the macros 2.0 definition remains hygienic.
294         //
295         // See the example at `test/run-pass/hygiene/legacy_interaction.rs`.
296         for (mark, transparency) in self.marks(ctxt) {
297             call_site_ctxt = self.apply_mark_internal(call_site_ctxt, mark, transparency);
298         }
299         self.apply_mark_internal(call_site_ctxt, mark, transparency)
300     }
301
302     fn apply_mark_internal(&mut self, ctxt: SyntaxContext, mark: Mark, transparency: Transparency)
303                            -> SyntaxContext {
304         let syntax_contexts = &mut self.syntax_contexts;
305         let mut opaque = syntax_contexts[ctxt.0 as usize].opaque;
306         let mut opaque_and_semitransparent =
307             syntax_contexts[ctxt.0 as usize].opaque_and_semitransparent;
308
309         if transparency >= Transparency::Opaque {
310             let prev_ctxt = opaque;
311             opaque = *self.markings.entry((prev_ctxt, mark, transparency)).or_insert_with(|| {
312                 let new_opaque = SyntaxContext(syntax_contexts.len() as u32);
313                 syntax_contexts.push(SyntaxContextData {
314                     outer_mark: mark,
315                     transparency,
316                     prev_ctxt,
317                     opaque: new_opaque,
318                     opaque_and_semitransparent: new_opaque,
319                     dollar_crate_name: kw::DollarCrate,
320                 });
321                 new_opaque
322             });
323         }
324
325         if transparency >= Transparency::SemiTransparent {
326             let prev_ctxt = opaque_and_semitransparent;
327             opaque_and_semitransparent =
328                     *self.markings.entry((prev_ctxt, mark, transparency)).or_insert_with(|| {
329                 let new_opaque_and_semitransparent =
330                     SyntaxContext(syntax_contexts.len() as u32);
331                 syntax_contexts.push(SyntaxContextData {
332                     outer_mark: mark,
333                     transparency,
334                     prev_ctxt,
335                     opaque,
336                     opaque_and_semitransparent: new_opaque_and_semitransparent,
337                     dollar_crate_name: kw::DollarCrate,
338                 });
339                 new_opaque_and_semitransparent
340             });
341         }
342
343         let prev_ctxt = ctxt;
344         *self.markings.entry((prev_ctxt, mark, transparency)).or_insert_with(|| {
345             let new_opaque_and_semitransparent_and_transparent =
346                 SyntaxContext(syntax_contexts.len() as u32);
347             syntax_contexts.push(SyntaxContextData {
348                 outer_mark: mark,
349                 transparency,
350                 prev_ctxt,
351                 opaque,
352                 opaque_and_semitransparent,
353                 dollar_crate_name: kw::DollarCrate,
354             });
355             new_opaque_and_semitransparent_and_transparent
356         })
357     }
358 }
359
360 pub fn clear_markings() {
361     HygieneData::with(|data| data.markings = FxHashMap::default());
362 }
363
364 impl SyntaxContext {
365     #[inline]
366     pub const fn empty() -> Self {
367         SyntaxContext(0)
368     }
369
370     #[inline]
371     crate fn as_u32(self) -> u32 {
372         self.0
373     }
374
375     #[inline]
376     crate fn from_u32(raw: u32) -> SyntaxContext {
377         SyntaxContext(raw)
378     }
379
380     // Allocate a new SyntaxContext with the given ExpnInfo. This is used when
381     // deserializing Spans from the incr. comp. cache.
382     // FIXME(mw): This method does not restore MarkData::parent or
383     // SyntaxContextData::prev_ctxt or SyntaxContextData::opaque. These things
384     // don't seem to be used after HIR lowering, so everything should be fine
385     // as long as incremental compilation does not kick in before that.
386     pub fn allocate_directly(expansion_info: ExpnInfo) -> Self {
387         HygieneData::with(|data| {
388             data.marks.push(MarkData {
389                 parent: Mark::root(),
390                 default_transparency: Transparency::SemiTransparent,
391                 expn_info: Some(expansion_info),
392             });
393
394             let mark = Mark(data.marks.len() as u32 - 1);
395
396             data.syntax_contexts.push(SyntaxContextData {
397                 outer_mark: mark,
398                 transparency: Transparency::SemiTransparent,
399                 prev_ctxt: SyntaxContext::empty(),
400                 opaque: SyntaxContext::empty(),
401                 opaque_and_semitransparent: SyntaxContext::empty(),
402                 dollar_crate_name: kw::DollarCrate,
403             });
404             SyntaxContext(data.syntax_contexts.len() as u32 - 1)
405         })
406     }
407
408     /// Extend a syntax context with a given mark and default transparency for that mark.
409     pub fn apply_mark(self, mark: Mark) -> SyntaxContext {
410         assert_ne!(mark, Mark::root());
411         self.apply_mark_with_transparency(
412             mark, HygieneData::with(|data| data.default_transparency(mark))
413         )
414     }
415
416     /// Extend a syntax context with a given mark and transparency
417     pub fn apply_mark_with_transparency(self, mark: Mark, transparency: Transparency)
418                                         -> SyntaxContext {
419         HygieneData::with(|data| data.apply_mark_with_transparency(self, mark, transparency))
420     }
421
422     /// Pulls a single mark off of the syntax context. This effectively moves the
423     /// context up one macro definition level. That is, if we have a nested macro
424     /// definition as follows:
425     ///
426     /// ```rust
427     /// macro_rules! f {
428     ///    macro_rules! g {
429     ///        ...
430     ///    }
431     /// }
432     /// ```
433     ///
434     /// and we have a SyntaxContext that is referring to something declared by an invocation
435     /// of g (call it g1), calling remove_mark will result in the SyntaxContext for the
436     /// invocation of f that created g1.
437     /// Returns the mark that was removed.
438     pub fn remove_mark(&mut self) -> Mark {
439         HygieneData::with(|data| data.remove_mark(self))
440     }
441
442     pub fn marks(self) -> Vec<(Mark, Transparency)> {
443         HygieneData::with(|data| data.marks(self))
444     }
445
446     /// Adjust this context for resolution in a scope created by the given expansion.
447     /// For example, consider the following three resolutions of `f`:
448     ///
449     /// ```rust
450     /// mod foo { pub fn f() {} } // `f`'s `SyntaxContext` is empty.
451     /// m!(f);
452     /// macro m($f:ident) {
453     ///     mod bar {
454     ///         pub fn f() {} // `f`'s `SyntaxContext` has a single `Mark` from `m`.
455     ///         pub fn $f() {} // `$f`'s `SyntaxContext` is empty.
456     ///     }
457     ///     foo::f(); // `f`'s `SyntaxContext` has a single `Mark` from `m`
458     ///     //^ Since `mod foo` is outside this expansion, `adjust` removes the mark from `f`,
459     ///     //| and it resolves to `::foo::f`.
460     ///     bar::f(); // `f`'s `SyntaxContext` has a single `Mark` from `m`
461     ///     //^ Since `mod bar` not outside this expansion, `adjust` does not change `f`,
462     ///     //| and it resolves to `::bar::f`.
463     ///     bar::$f(); // `f`'s `SyntaxContext` is empty.
464     ///     //^ Since `mod bar` is not outside this expansion, `adjust` does not change `$f`,
465     ///     //| and it resolves to `::bar::$f`.
466     /// }
467     /// ```
468     /// This returns the expansion whose definition scope we use to privacy check the resolution,
469     /// or `None` if we privacy check as usual (i.e., not w.r.t. a macro definition scope).
470     pub fn adjust(&mut self, expansion: Mark) -> Option<Mark> {
471         HygieneData::with(|data| data.adjust(self, expansion))
472     }
473
474     /// Adjust this context for resolution in a scope created by the given expansion
475     /// via a glob import with the given `SyntaxContext`.
476     /// For example:
477     ///
478     /// ```rust
479     /// m!(f);
480     /// macro m($i:ident) {
481     ///     mod foo {
482     ///         pub fn f() {} // `f`'s `SyntaxContext` has a single `Mark` from `m`.
483     ///         pub fn $i() {} // `$i`'s `SyntaxContext` is empty.
484     ///     }
485     ///     n(f);
486     ///     macro n($j:ident) {
487     ///         use foo::*;
488     ///         f(); // `f`'s `SyntaxContext` has a mark from `m` and a mark from `n`
489     ///         //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::f`.
490     ///         $i(); // `$i`'s `SyntaxContext` has a mark from `n`
491     ///         //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::$i`.
492     ///         $j(); // `$j`'s `SyntaxContext` has a mark from `m`
493     ///         //^ This cannot be glob-adjusted, so this is a resolution error.
494     ///     }
495     /// }
496     /// ```
497     /// This returns `None` if the context cannot be glob-adjusted.
498     /// Otherwise, it returns the scope to use when privacy checking (see `adjust` for details).
499     pub fn glob_adjust(&mut self, expansion: Mark, glob_span: Span) -> Option<Option<Mark>> {
500         let mut scope = None;
501         let mut glob_ctxt = glob_span.ctxt().modern();
502         while !expansion.outer_is_descendant_of(glob_ctxt) {
503             scope = Some(glob_ctxt.remove_mark());
504             if self.remove_mark() != scope.unwrap() {
505                 return None;
506             }
507         }
508         if self.adjust(expansion).is_some() {
509             return None;
510         }
511         Some(scope)
512     }
513
514     /// Undo `glob_adjust` if possible:
515     ///
516     /// ```rust
517     /// if let Some(privacy_checking_scope) = self.reverse_glob_adjust(expansion, glob_ctxt) {
518     ///     assert!(self.glob_adjust(expansion, glob_ctxt) == Some(privacy_checking_scope));
519     /// }
520     /// ```
521     pub fn reverse_glob_adjust(&mut self, expansion: Mark, glob_span: Span)
522                                -> Option<Option<Mark>> {
523         if self.adjust(expansion).is_some() {
524             return None;
525         }
526
527         let mut glob_ctxt = glob_span.ctxt().modern();
528         let mut marks = Vec::new();
529         while !expansion.outer_is_descendant_of(glob_ctxt) {
530             marks.push(glob_ctxt.remove_mark());
531         }
532
533         let scope = marks.last().cloned();
534         while let Some(mark) = marks.pop() {
535             *self = self.apply_mark(mark);
536         }
537         Some(scope)
538     }
539
540     #[inline]
541     pub fn modern(self) -> SyntaxContext {
542         HygieneData::with(|data| data.modern(self))
543     }
544
545     #[inline]
546     pub fn modern_and_legacy(self) -> SyntaxContext {
547         HygieneData::with(|data| data.modern_and_legacy(self))
548     }
549
550     #[inline]
551     pub fn outer(self) -> Mark {
552         HygieneData::with(|data| data.outer(self))
553     }
554
555     /// `ctxt.outer_expn_info()` is equivalent to but faster than
556     /// `ctxt.outer().expn_info()`.
557     #[inline]
558     pub fn outer_expn_info(self) -> Option<ExpnInfo> {
559         HygieneData::with(|data| data.expn_info(data.outer(self)))
560     }
561
562     pub fn dollar_crate_name(self) -> Symbol {
563         HygieneData::with(|data| data.syntax_contexts[self.0 as usize].dollar_crate_name)
564     }
565
566     pub fn set_dollar_crate_name(self, dollar_crate_name: Symbol) {
567         HygieneData::with(|data| {
568             let prev_dollar_crate_name = mem::replace(
569                 &mut data.syntax_contexts[self.0 as usize].dollar_crate_name, dollar_crate_name
570             );
571             assert!(dollar_crate_name == prev_dollar_crate_name ||
572                     prev_dollar_crate_name == kw::DollarCrate,
573                     "$crate name is reset for a syntax context");
574         })
575     }
576 }
577
578 impl fmt::Debug for SyntaxContext {
579     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
580         write!(f, "#{}", self.0)
581     }
582 }
583
584 /// Extra information for tracking spans of macro and syntax sugar expansion
585 #[derive(Clone, Hash, Debug, RustcEncodable, RustcDecodable)]
586 pub struct ExpnInfo {
587     /// The location of the actual macro invocation or syntax sugar , e.g.
588     /// `let x = foo!();` or `if let Some(y) = x {}`
589     ///
590     /// This may recursively refer to other macro invocations, e.g., if
591     /// `foo!()` invoked `bar!()` internally, and there was an
592     /// expression inside `bar!`; the call_site of the expression in
593     /// the expansion would point to the `bar!` invocation; that
594     /// call_site span would have its own ExpnInfo, with the call_site
595     /// pointing to the `foo!` invocation.
596     pub call_site: Span,
597     /// The span of the macro definition itself. The macro may not
598     /// have a sensible definition span (e.g., something defined
599     /// completely inside libsyntax) in which case this is None.
600     /// This span serves only informational purpose and is not used for resolution.
601     pub def_site: Option<Span>,
602     /// The format with which the macro was invoked.
603     pub format: ExpnFormat,
604     /// List of #[unstable]/feature-gated features that the macro is allowed to use
605     /// internally without forcing the whole crate to opt-in
606     /// to them.
607     pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
608     /// Whether the macro is allowed to use `unsafe` internally
609     /// even if the user crate has `#![forbid(unsafe_code)]`.
610     pub allow_internal_unsafe: bool,
611     /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`)
612     /// for a given macro.
613     pub local_inner_macros: bool,
614     /// Edition of the crate in which the macro is defined.
615     pub edition: Edition,
616 }
617
618 /// The source of expansion.
619 #[derive(Clone, Hash, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
620 pub enum ExpnFormat {
621     /// e.g., #[derive(...)] <item>
622     MacroAttribute(Symbol),
623     /// e.g., `format!()`
624     MacroBang(Symbol),
625     /// Desugaring done by the compiler during HIR lowering.
626     CompilerDesugaring(CompilerDesugaringKind)
627 }
628
629 impl ExpnFormat {
630     pub fn name(&self) -> Symbol {
631         match *self {
632             ExpnFormat::MacroBang(name) | ExpnFormat::MacroAttribute(name) => name,
633             ExpnFormat::CompilerDesugaring(kind) => kind.name(),
634         }
635     }
636 }
637
638 /// The kind of compiler desugaring.
639 #[derive(Clone, Copy, Hash, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
640 pub enum CompilerDesugaringKind {
641     /// We desugar `if c { i } else { e }` to `match $ExprKind::Use(c) { true => i, _ => e }`.
642     /// However, we do not want to blame `c` for unreachability but rather say that `i`
643     /// is unreachable. This desugaring kind allows us to avoid blaming `c`.
644     IfTemporary,
645     QuestionMark,
646     TryBlock,
647     /// Desugaring of an `impl Trait` in return type position
648     /// to an `existential type Foo: Trait;` and replacing the
649     /// `impl Trait` with `Foo`.
650     ExistentialReturnType,
651     Async,
652     Await,
653     ForLoop,
654 }
655
656 impl CompilerDesugaringKind {
657     pub fn name(self) -> Symbol {
658         Symbol::intern(match self {
659             CompilerDesugaringKind::IfTemporary => "if",
660             CompilerDesugaringKind::Async => "async",
661             CompilerDesugaringKind::Await => "await",
662             CompilerDesugaringKind::QuestionMark => "?",
663             CompilerDesugaringKind::TryBlock => "try block",
664             CompilerDesugaringKind::ExistentialReturnType => "existential type",
665             CompilerDesugaringKind::ForLoop => "for loop",
666         })
667     }
668 }
669
670 impl Encodable for SyntaxContext {
671     fn encode<E: Encoder>(&self, _: &mut E) -> Result<(), E::Error> {
672         Ok(()) // FIXME(jseyfried) intercrate hygiene
673     }
674 }
675
676 impl Decodable for SyntaxContext {
677     fn decode<D: Decoder>(_: &mut D) -> Result<SyntaxContext, D::Error> {
678         Ok(SyntaxContext::empty()) // FIXME(jseyfried) intercrate hygiene
679     }
680 }