]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/cstore.rs
Auto merge of #30553 - luqmana:mir-match-arm-guards, r=nikomatsakis
[rust.git] / src / librustc / middle / cstore.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
12 // file at the top-level directory of this distribution and at
13 // http://rust-lang.org/COPYRIGHT.
14 //
15 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
16 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
17 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
18 // option. This file may not be copied, modified, or distributed
19 // except according to those terms.
20
21 // the rustc crate store interface. This also includes types that
22 // are *mostly* used as a part of that interface, but these should
23 // probably get a better home if someone can find one.
24
25 use back::svh::Svh;
26 use front::map as hir_map;
27 use middle::def;
28 use middle::lang_items;
29 use middle::ty::{self, Ty};
30 use middle::def_id::{DefId, DefIndex};
31 use mir::repr::Mir;
32 use session::Session;
33 use session::search_paths::PathKind;
34 use util::nodemap::{FnvHashMap, NodeMap, NodeSet};
35 use std::any::Any;
36 use std::cell::RefCell;
37 use std::rc::Rc;
38 use std::path::PathBuf;
39 use syntax::ast;
40 use syntax::ast_util::{IdVisitingOperation};
41 use syntax::attr;
42 use syntax::codemap::Span;
43 use syntax::ptr::P;
44 use rustc_back::target::Target;
45 use rustc_front::hir;
46 use rustc_front::intravisit::Visitor;
47 use rustc_front::util::IdVisitor;
48
49 pub use self::DefLike::{DlDef, DlField, DlImpl};
50 pub use self::NativeLibraryKind::{NativeStatic, NativeFramework, NativeUnknown};
51
52 // lonely orphan structs and enums looking for a better home
53
54 #[derive(Clone, Debug)]
55 pub struct LinkMeta {
56     pub crate_name: String,
57     pub crate_hash: Svh,
58 }
59
60 // Where a crate came from on the local filesystem. One of these two options
61 // must be non-None.
62 #[derive(PartialEq, Clone, Debug)]
63 pub struct CrateSource {
64     pub dylib: Option<(PathBuf, PathKind)>,
65     pub rlib: Option<(PathBuf, PathKind)>,
66     pub cnum: ast::CrateNum,
67 }
68
69 #[derive(Copy, Debug, PartialEq, Clone)]
70 pub enum LinkagePreference {
71     RequireDynamic,
72     RequireStatic,
73 }
74
75 enum_from_u32! {
76     #[derive(Copy, Clone, PartialEq)]
77     pub enum NativeLibraryKind {
78         NativeStatic,    // native static library (.a archive)
79         NativeFramework, // OSX-specific
80         NativeUnknown,   // default way to specify a dynamic library
81     }
82 }
83
84 // Something that a name can resolve to.
85 #[derive(Copy, Clone, Debug)]
86 pub enum DefLike {
87     DlDef(def::Def),
88     DlImpl(DefId),
89     DlField
90 }
91
92 /// The data we save and restore about an inlined item or method.  This is not
93 /// part of the AST that we parse from a file, but it becomes part of the tree
94 /// that we trans.
95 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
96 pub enum InlinedItem {
97     Item(P<hir::Item>),
98     TraitItem(DefId /* impl id */, P<hir::TraitItem>),
99     ImplItem(DefId /* impl id */, P<hir::ImplItem>),
100     Foreign(P<hir::ForeignItem>),
101 }
102
103 /// A borrowed version of `hir::InlinedItem`.
104 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
105 pub enum InlinedItemRef<'a> {
106     Item(&'a hir::Item),
107     TraitItem(DefId, &'a hir::TraitItem),
108     ImplItem(DefId, &'a hir::ImplItem),
109     Foreign(&'a hir::ForeignItem)
110 }
111
112 /// Item definitions in the currently-compiled crate would have the CrateNum
113 /// LOCAL_CRATE in their DefId.
114 pub const LOCAL_CRATE: ast::CrateNum = 0;
115
116 pub struct ChildItem {
117     pub def: DefLike,
118     pub name: ast::Name,
119     pub vis: hir::Visibility
120 }
121
122 pub enum FoundAst<'ast> {
123     Found(&'ast InlinedItem),
124     FoundParent(DefId, &'ast InlinedItem),
125     NotFound,
126 }
127
128 /// A store of Rust crates, through with their metadata
129 /// can be accessed.
130 ///
131 /// The `: Any` bound is a temporary measure that allows access
132 /// to the backing `rustc_metadata::cstore::CStore` object. It
133 /// will be removed in the near future - if you need to access
134 /// internal APIs, please tell us.
135 pub trait CrateStore<'tcx> : Any {
136     // item info
137     fn stability(&self, def: DefId) -> Option<attr::Stability>;
138     fn deprecation(&self, def: DefId) -> Option<attr::Deprecation>;
139     fn closure_kind(&self, tcx: &ty::ctxt<'tcx>, def_id: DefId)
140                     -> ty::ClosureKind;
141     fn closure_ty(&self, tcx: &ty::ctxt<'tcx>, def_id: DefId)
142                   -> ty::ClosureTy<'tcx>;
143     fn item_variances(&self, def: DefId) -> ty::ItemVariances;
144     fn repr_attrs(&self, def: DefId) -> Vec<attr::ReprAttr>;
145     fn item_type(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
146                  -> ty::TypeScheme<'tcx>;
147     fn item_path(&self, def: DefId) -> Vec<hir_map::PathElem>;
148     fn extern_item_path(&self, def: DefId) -> Vec<hir_map::PathElem>;
149     fn item_name(&self, def: DefId) -> ast::Name;
150     fn item_predicates(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
151                        -> ty::GenericPredicates<'tcx>;
152     fn item_super_predicates(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
153                              -> ty::GenericPredicates<'tcx>;
154     fn item_attrs(&self, def_id: DefId) -> Vec<ast::Attribute>;
155     fn item_symbol(&self, def: DefId) -> String;
156     fn trait_def(&self, tcx: &ty::ctxt<'tcx>, def: DefId)-> ty::TraitDef<'tcx>;
157     fn adt_def(&self, tcx: &ty::ctxt<'tcx>, def: DefId) -> ty::AdtDefMaster<'tcx>;
158     fn method_arg_names(&self, did: DefId) -> Vec<String>;
159     fn inherent_implementations_for_type(&self, def_id: DefId) -> Vec<DefId>;
160
161     // trait info
162     fn implementations_of_trait(&self, def_id: DefId) -> Vec<DefId>;
163     fn provided_trait_methods(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
164                               -> Vec<Rc<ty::Method<'tcx>>>;
165     fn trait_item_def_ids(&self, def: DefId)
166                           -> Vec<ty::ImplOrTraitItemId>;
167
168     // impl info
169     fn impl_items(&self, impl_def_id: DefId) -> Vec<ty::ImplOrTraitItemId>;
170     fn impl_trait_ref(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
171                       -> Option<ty::TraitRef<'tcx>>;
172     fn impl_polarity(&self, def: DefId) -> Option<hir::ImplPolarity>;
173     fn custom_coerce_unsized_kind(&self, def: DefId)
174                                   -> Option<ty::adjustment::CustomCoerceUnsized>;
175     fn associated_consts(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
176                          -> Vec<Rc<ty::AssociatedConst<'tcx>>>;
177
178     // trait/impl-item info
179     fn trait_of_item(&self, tcx: &ty::ctxt<'tcx>, def_id: DefId)
180                      -> Option<DefId>;
181     fn impl_or_trait_item(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
182                           -> ty::ImplOrTraitItem<'tcx>;
183
184     // flags
185     fn is_const_fn(&self, did: DefId) -> bool;
186     fn is_defaulted_trait(&self, did: DefId) -> bool;
187     fn is_impl(&self, did: DefId) -> bool;
188     fn is_default_impl(&self, impl_did: DefId) -> bool;
189     fn is_extern_fn(&self, tcx: &ty::ctxt<'tcx>, did: DefId) -> bool;
190     fn is_static(&self, did: DefId) -> bool;
191     fn is_static_method(&self, did: DefId) -> bool;
192     fn is_statically_included_foreign_item(&self, id: ast::NodeId) -> bool;
193     fn is_typedef(&self, did: DefId) -> bool;
194
195     // crate metadata
196     fn dylib_dependency_formats(&self, cnum: ast::CrateNum)
197                                     -> Vec<(ast::CrateNum, LinkagePreference)>;
198     fn lang_items(&self, cnum: ast::CrateNum) -> Vec<(DefIndex, usize)>;
199     fn missing_lang_items(&self, cnum: ast::CrateNum) -> Vec<lang_items::LangItem>;
200     fn is_staged_api(&self, cnum: ast::CrateNum) -> bool;
201     fn is_explicitly_linked(&self, cnum: ast::CrateNum) -> bool;
202     fn is_allocator(&self, cnum: ast::CrateNum) -> bool;
203     fn crate_attrs(&self, cnum: ast::CrateNum) -> Vec<ast::Attribute>;
204     fn crate_name(&self, cnum: ast::CrateNum) -> String;
205     fn crate_hash(&self, cnum: ast::CrateNum) -> Svh;
206     fn crate_struct_field_attrs(&self, cnum: ast::CrateNum)
207                                 -> FnvHashMap<DefId, Vec<ast::Attribute>>;
208     fn plugin_registrar_fn(&self, cnum: ast::CrateNum) -> Option<DefId>;
209     fn native_libraries(&self, cnum: ast::CrateNum) -> Vec<(NativeLibraryKind, String)>;
210     fn reachable_ids(&self, cnum: ast::CrateNum) -> Vec<DefId>;
211
212     // resolve
213     fn def_path(&self, def: DefId) -> hir_map::DefPath;
214     fn tuple_struct_definition_if_ctor(&self, did: DefId) -> Option<DefId>;
215     fn struct_field_names(&self, def: DefId) -> Vec<ast::Name>;
216     fn item_children(&self, did: DefId) -> Vec<ChildItem>;
217     fn crate_top_level_items(&self, cnum: ast::CrateNum) -> Vec<ChildItem>;
218
219     // misc. metadata
220     fn maybe_get_item_ast(&'tcx self, tcx: &ty::ctxt<'tcx>, def: DefId)
221                           -> FoundAst<'tcx>;
222     fn maybe_get_item_mir(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
223                           -> Option<Mir<'tcx>>;
224     // This is basically a 1-based range of ints, which is a little
225     // silly - I may fix that.
226     fn crates(&self) -> Vec<ast::CrateNum>;
227     fn used_libraries(&self) -> Vec<(String, NativeLibraryKind)>;
228     fn used_link_args(&self) -> Vec<String>;
229
230     // utility functions
231     fn metadata_filename(&self) -> &str;
232     fn metadata_section_name(&self, target: &Target) -> &str;
233     fn encode_type(&self, tcx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> Vec<u8>;
234     fn used_crates(&self, prefer: LinkagePreference) -> Vec<(ast::CrateNum, Option<PathBuf>)>;
235     fn used_crate_source(&self, cnum: ast::CrateNum) -> CrateSource;
236     fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<ast::CrateNum>;
237     fn encode_metadata(&self,
238                        tcx: &ty::ctxt<'tcx>,
239                        reexports: &def::ExportMap,
240                        item_symbols: &RefCell<NodeMap<String>>,
241                        link_meta: &LinkMeta,
242                        reachable: &NodeSet,
243                        mir_map: &NodeMap<Mir<'tcx>>,
244                        krate: &hir::Crate) -> Vec<u8>;
245     fn metadata_encoding_version(&self) -> &[u8];
246 }
247
248 impl InlinedItem {
249     pub fn visit<'ast,V>(&'ast self, visitor: &mut V)
250         where V: Visitor<'ast>
251     {
252         match *self {
253             InlinedItem::Item(ref i) => visitor.visit_item(&**i),
254             InlinedItem::Foreign(ref i) => visitor.visit_foreign_item(&**i),
255             InlinedItem::TraitItem(_, ref ti) => visitor.visit_trait_item(ti),
256             InlinedItem::ImplItem(_, ref ii) => visitor.visit_impl_item(ii),
257         }
258     }
259
260     pub fn visit_ids<O: IdVisitingOperation>(&self, operation: &mut O) {
261         let mut id_visitor = IdVisitor::new(operation);
262         self.visit(&mut id_visitor);
263     }
264 }
265
266 // FIXME: find a better place for this?
267 pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
268     let say = |s: &str| {
269         match (sp, sess) {
270             (_, None) => panic!("{}", s),
271             (Some(sp), Some(sess)) => sess.span_err(sp, s),
272             (None, Some(sess)) => sess.err(s),
273         }
274     };
275     if s.is_empty() {
276         say("crate name must not be empty");
277     }
278     for c in s.chars() {
279         if c.is_alphanumeric() { continue }
280         if c == '_'  { continue }
281         say(&format!("invalid character `{}` in crate name: `{}`", c, s));
282     }
283     match sess {
284         Some(sess) => sess.abort_if_errors(),
285         None => {}
286     }
287 }
288
289 /// A dummy crate store that does not support any non-local crates,
290 /// for test purposes.
291 pub struct DummyCrateStore;
292 #[allow(unused_variables)]
293 impl<'tcx> CrateStore<'tcx> for DummyCrateStore {
294     // item info
295     fn stability(&self, def: DefId) -> Option<attr::Stability> { unimplemented!() }
296     fn deprecation(&self, def: DefId) -> Option<attr::Deprecation> { unimplemented!() }
297     fn closure_kind(&self, tcx: &ty::ctxt<'tcx>, def_id: DefId)
298                     -> ty::ClosureKind  { unimplemented!() }
299     fn closure_ty(&self, tcx: &ty::ctxt<'tcx>, def_id: DefId)
300                   -> ty::ClosureTy<'tcx>  { unimplemented!() }
301     fn item_variances(&self, def: DefId) -> ty::ItemVariances { unimplemented!() }
302     fn repr_attrs(&self, def: DefId) -> Vec<attr::ReprAttr> { unimplemented!() }
303     fn item_type(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
304                  -> ty::TypeScheme<'tcx> { unimplemented!() }
305     fn item_path(&self, def: DefId) -> Vec<hir_map::PathElem> { unimplemented!() }
306     fn extern_item_path(&self, def: DefId) -> Vec<hir_map::PathElem> { unimplemented!() }
307     fn item_name(&self, def: DefId) -> ast::Name { unimplemented!() }
308     fn item_predicates(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
309                        -> ty::GenericPredicates<'tcx> { unimplemented!() }
310     fn item_super_predicates(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
311                              -> ty::GenericPredicates<'tcx> { unimplemented!() }
312     fn item_attrs(&self, def_id: DefId) -> Vec<ast::Attribute> { unimplemented!() }
313     fn item_symbol(&self, def: DefId) -> String { unimplemented!() }
314     fn trait_def(&self, tcx: &ty::ctxt<'tcx>, def: DefId)-> ty::TraitDef<'tcx>
315         { unimplemented!() }
316     fn adt_def(&self, tcx: &ty::ctxt<'tcx>, def: DefId) -> ty::AdtDefMaster<'tcx>
317         { unimplemented!() }
318     fn method_arg_names(&self, did: DefId) -> Vec<String> { unimplemented!() }
319     fn inherent_implementations_for_type(&self, def_id: DefId) -> Vec<DefId> { vec![] }
320
321     // trait info
322     fn implementations_of_trait(&self, def_id: DefId) -> Vec<DefId> { vec![] }
323     fn provided_trait_methods(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
324                               -> Vec<Rc<ty::Method<'tcx>>> { unimplemented!() }
325     fn trait_item_def_ids(&self, def: DefId)
326                           -> Vec<ty::ImplOrTraitItemId> { unimplemented!() }
327
328     // impl info
329     fn impl_items(&self, impl_def_id: DefId) -> Vec<ty::ImplOrTraitItemId>
330         { unimplemented!() }
331     fn impl_trait_ref(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
332                       -> Option<ty::TraitRef<'tcx>> { unimplemented!() }
333     fn impl_polarity(&self, def: DefId) -> Option<hir::ImplPolarity> { unimplemented!() }
334     fn custom_coerce_unsized_kind(&self, def: DefId)
335                                   -> Option<ty::adjustment::CustomCoerceUnsized>
336         { unimplemented!() }
337     fn associated_consts(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
338                          -> Vec<Rc<ty::AssociatedConst<'tcx>>> { unimplemented!() }
339
340     // trait/impl-item info
341     fn trait_of_item(&self, tcx: &ty::ctxt<'tcx>, def_id: DefId)
342                      -> Option<DefId> { unimplemented!() }
343     fn impl_or_trait_item(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
344                           -> ty::ImplOrTraitItem<'tcx> { unimplemented!() }
345
346     // flags
347     fn is_const_fn(&self, did: DefId) -> bool { unimplemented!() }
348     fn is_defaulted_trait(&self, did: DefId) -> bool { unimplemented!() }
349     fn is_impl(&self, did: DefId) -> bool { unimplemented!() }
350     fn is_default_impl(&self, impl_did: DefId) -> bool { unimplemented!() }
351     fn is_extern_fn(&self, tcx: &ty::ctxt<'tcx>, did: DefId) -> bool { unimplemented!() }
352     fn is_static(&self, did: DefId) -> bool { unimplemented!() }
353     fn is_static_method(&self, did: DefId) -> bool { unimplemented!() }
354     fn is_statically_included_foreign_item(&self, id: ast::NodeId) -> bool { false }
355     fn is_typedef(&self, did: DefId) -> bool { unimplemented!() }
356
357     // crate metadata
358     fn dylib_dependency_formats(&self, cnum: ast::CrateNum)
359                                     -> Vec<(ast::CrateNum, LinkagePreference)>
360         { unimplemented!() }
361     fn lang_items(&self, cnum: ast::CrateNum) -> Vec<(DefIndex, usize)>
362         { unimplemented!() }
363     fn missing_lang_items(&self, cnum: ast::CrateNum) -> Vec<lang_items::LangItem>
364         { unimplemented!() }
365     fn is_staged_api(&self, cnum: ast::CrateNum) -> bool { unimplemented!() }
366     fn is_explicitly_linked(&self, cnum: ast::CrateNum) -> bool { unimplemented!() }
367     fn is_allocator(&self, cnum: ast::CrateNum) -> bool { unimplemented!() }
368     fn crate_attrs(&self, cnum: ast::CrateNum) -> Vec<ast::Attribute>
369         { unimplemented!() }
370     fn crate_name(&self, cnum: ast::CrateNum) -> String { unimplemented!() }
371     fn crate_hash(&self, cnum: ast::CrateNum) -> Svh { unimplemented!() }
372     fn crate_struct_field_attrs(&self, cnum: ast::CrateNum)
373                                 -> FnvHashMap<DefId, Vec<ast::Attribute>>
374         { unimplemented!() }
375     fn plugin_registrar_fn(&self, cnum: ast::CrateNum) -> Option<DefId>
376         { unimplemented!() }
377     fn native_libraries(&self, cnum: ast::CrateNum) -> Vec<(NativeLibraryKind, String)>
378         { unimplemented!() }
379     fn reachable_ids(&self, cnum: ast::CrateNum) -> Vec<DefId> { unimplemented!() }
380
381     // resolve
382     fn def_path(&self, def: DefId) -> hir_map::DefPath { unimplemented!() }
383     fn tuple_struct_definition_if_ctor(&self, did: DefId) -> Option<DefId>
384         { unimplemented!() }
385     fn struct_field_names(&self, def: DefId) -> Vec<ast::Name> { unimplemented!() }
386     fn item_children(&self, did: DefId) -> Vec<ChildItem> { unimplemented!() }
387     fn crate_top_level_items(&self, cnum: ast::CrateNum) -> Vec<ChildItem>
388         { unimplemented!() }
389
390     // misc. metadata
391     fn maybe_get_item_ast(&'tcx self, tcx: &ty::ctxt<'tcx>, def: DefId)
392                           -> FoundAst<'tcx> { unimplemented!() }
393     fn maybe_get_item_mir(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
394                           -> Option<Mir<'tcx>> { unimplemented!() }
395
396     // This is basically a 1-based range of ints, which is a little
397     // silly - I may fix that.
398     fn crates(&self) -> Vec<ast::CrateNum> { vec![] }
399     fn used_libraries(&self) -> Vec<(String, NativeLibraryKind)> { vec![] }
400     fn used_link_args(&self) -> Vec<String> { vec![] }
401
402     // utility functions
403     fn metadata_filename(&self) -> &str { unimplemented!() }
404     fn metadata_section_name(&self, target: &Target) -> &str { unimplemented!() }
405     fn encode_type(&self, tcx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> Vec<u8>
406         { unimplemented!() }
407     fn used_crates(&self, prefer: LinkagePreference) -> Vec<(ast::CrateNum, Option<PathBuf>)>
408         { vec![] }
409     fn used_crate_source(&self, cnum: ast::CrateNum) -> CrateSource { unimplemented!() }
410     fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<ast::CrateNum> { None }
411     fn encode_metadata(&self,
412                        tcx: &ty::ctxt<'tcx>,
413                        reexports: &def::ExportMap,
414                        item_symbols: &RefCell<NodeMap<String>>,
415                        link_meta: &LinkMeta,
416                        reachable: &NodeSet,
417                        mir_map: &NodeMap<Mir<'tcx>>,
418                        krate: &hir::Crate) -> Vec<u8> { vec![] }
419     fn metadata_encoding_version(&self) -> &[u8] { unimplemented!() }
420 }
421
422
423 /// Metadata encoding and decoding can make use of thread-local encoding and
424 /// decoding contexts. These allow implementers of serialize::Encodable and
425 /// Decodable to access information and datastructures that would otherwise not
426 /// be available to them. For example, we can automatically translate def-id and
427 /// span information during decoding because the decoding context knows which
428 /// crate the data is decoded from. Or it allows to make ty::Ty decodable
429 /// because the context has access to the ty::ctxt that is needed for creating
430 /// ty::Ty instances.
431 ///
432 /// Note, however, that this only works for RBML-based encoding and decoding at
433 /// the moment.
434 pub mod tls {
435     use rbml::opaque::Encoder as OpaqueEncoder;
436     use rbml::opaque::Decoder as OpaqueDecoder;
437     use serialize;
438     use std::mem;
439     use middle::ty::{self, Ty};
440     use middle::subst::Substs;
441     use middle::def_id::DefId;
442
443     pub trait EncodingContext<'tcx> {
444         fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx>;
445         fn encode_ty(&self, encoder: &mut OpaqueEncoder, t: Ty<'tcx>);
446         fn encode_substs(&self, encoder: &mut OpaqueEncoder, substs: &Substs<'tcx>);
447     }
448
449     /// Marker type used for the scoped TLS slot.
450     /// The type context cannot be used directly because the scoped TLS
451     /// in libstd doesn't allow types generic over lifetimes.
452     struct TlsPayload;
453
454     scoped_thread_local!(static TLS_ENCODING: TlsPayload);
455
456     /// Execute f after pushing the given EncodingContext onto the TLS stack.
457     pub fn enter_encoding_context<'tcx, F, R>(ecx: &EncodingContext<'tcx>,
458                                               encoder: &mut OpaqueEncoder,
459                                               f: F) -> R
460         where F: FnOnce(&EncodingContext<'tcx>, &mut OpaqueEncoder) -> R
461     {
462         let tls_payload = (ecx as *const _, encoder as *mut _);
463         let tls_ptr = &tls_payload as *const _ as *const TlsPayload;
464         TLS_ENCODING.set(unsafe { &*tls_ptr }, || f(ecx, encoder))
465     }
466
467     /// Execute f with access to the thread-local encoding context and
468     /// rbml encoder. This function will panic if the encoder passed in and the
469     /// context encoder are not the same.
470     ///
471     /// Note that this method is 'practically' safe due to its checking that the
472     /// encoder passed in is the same as the one in TLS, but it would still be
473     /// possible to construct cases where the EncodingContext is exchanged
474     /// while the same encoder is used, thus working with a wrong context.
475     pub fn with_encoding_context<'tcx, E, F, R>(encoder: &mut E, f: F) -> R
476         where F: FnOnce(&EncodingContext<'tcx>, &mut OpaqueEncoder) -> R,
477               E: serialize::Encoder
478     {
479         unsafe {
480             unsafe_with_encoding_context(|ecx, tls_encoder| {
481                 assert!(encoder as *mut _ as usize == tls_encoder as *mut _ as usize);
482
483                 let ecx: &EncodingContext<'tcx> = mem::transmute(ecx);
484
485                 f(ecx, tls_encoder)
486             })
487         }
488     }
489
490     /// Execute f with access to the thread-local encoding context and
491     /// rbml encoder.
492     pub unsafe fn unsafe_with_encoding_context<F, R>(f: F) -> R
493         where F: FnOnce(&EncodingContext, &mut OpaqueEncoder) -> R
494     {
495         TLS_ENCODING.with(|tls| {
496             let tls_payload = (tls as *const TlsPayload)
497                                    as *mut (&EncodingContext, &mut OpaqueEncoder);
498             f((*tls_payload).0, (*tls_payload).1)
499         })
500     }
501
502     pub trait DecodingContext<'tcx> {
503         fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx>;
504         fn decode_ty(&self, decoder: &mut OpaqueDecoder) -> ty::Ty<'tcx>;
505         fn decode_substs(&self, decoder: &mut OpaqueDecoder) -> Substs<'tcx>;
506         fn translate_def_id(&self, def_id: DefId) -> DefId;
507     }
508
509     scoped_thread_local!(static TLS_DECODING: TlsPayload);
510
511     /// Execute f after pushing the given DecodingContext onto the TLS stack.
512     pub fn enter_decoding_context<'tcx, F, R>(dcx: &DecodingContext<'tcx>,
513                                               decoder: &mut OpaqueDecoder,
514                                               f: F) -> R
515         where F: FnOnce(&DecodingContext<'tcx>, &mut OpaqueDecoder) -> R
516     {
517         let tls_payload = (dcx as *const _, decoder as *mut _);
518         let tls_ptr = &tls_payload as *const _ as *const TlsPayload;
519         TLS_DECODING.set(unsafe { &*tls_ptr }, || f(dcx, decoder))
520     }
521
522     /// Execute f with access to the thread-local decoding context and
523     /// rbml decoder. This function will panic if the decoder passed in and the
524     /// context decoder are not the same.
525     ///
526     /// Note that this method is 'practically' safe due to its checking that the
527     /// decoder passed in is the same as the one in TLS, but it would still be
528     /// possible to construct cases where the DecodingContext is exchanged
529     /// while the same decoder is used, thus working with a wrong context.
530     pub fn with_decoding_context<'decoder, 'tcx, D, F, R>(d: &'decoder mut D, f: F) -> R
531         where D: serialize::Decoder,
532               F: FnOnce(&DecodingContext<'tcx>,
533                         &mut OpaqueDecoder) -> R,
534               'tcx: 'decoder
535     {
536         unsafe {
537             unsafe_with_decoding_context(|dcx, decoder| {
538                 assert!((d as *mut _ as usize) == (decoder as *mut _ as usize));
539
540                 let dcx: &DecodingContext<'tcx> = mem::transmute(dcx);
541
542                 f(dcx, decoder)
543             })
544         }
545     }
546
547     /// Execute f with access to the thread-local decoding context and
548     /// rbml decoder.
549     pub unsafe fn unsafe_with_decoding_context<F, R>(f: F) -> R
550         where F: FnOnce(&DecodingContext, &mut OpaqueDecoder) -> R
551     {
552         TLS_DECODING.with(|tls| {
553             let tls_payload = (tls as *const TlsPayload)
554                                    as *mut (&DecodingContext, &mut OpaqueDecoder);
555             f((*tls_payload).0, (*tls_payload).1)
556         })
557     }
558 }