]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/cstore.rs
Auto merge of #29735 - Amanieu:asm_indirect_constraint, r=pnkfelix
[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 closure_kind(&self, tcx: &ty::ctxt<'tcx>, def_id: DefId)
139                     -> ty::ClosureKind;
140     fn closure_ty(&self, tcx: &ty::ctxt<'tcx>, def_id: DefId)
141                   -> ty::ClosureTy<'tcx>;
142     fn item_variances(&self, def: DefId) -> ty::ItemVariances;
143     fn repr_attrs(&self, def: DefId) -> Vec<attr::ReprAttr>;
144     fn item_type(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
145                  -> ty::TypeScheme<'tcx>;
146     fn item_path(&self, def: DefId) -> Vec<hir_map::PathElem>;
147     fn extern_item_path(&self, def: DefId) -> Vec<hir_map::PathElem>;
148     fn item_name(&self, def: DefId) -> ast::Name;
149     fn item_predicates(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
150                        -> ty::GenericPredicates<'tcx>;
151     fn item_super_predicates(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
152                              -> ty::GenericPredicates<'tcx>;
153     fn item_attrs(&self, def_id: DefId) -> Vec<ast::Attribute>;
154     fn item_symbol(&self, def: DefId) -> String;
155     fn trait_def(&self, tcx: &ty::ctxt<'tcx>, def: DefId)-> ty::TraitDef<'tcx>;
156     fn adt_def(&self, tcx: &ty::ctxt<'tcx>, def: DefId) -> ty::AdtDefMaster<'tcx>;
157     fn method_arg_names(&self, did: DefId) -> Vec<String>;
158     fn inherent_implementations_for_type(&self, def_id: DefId) -> Vec<DefId>;
159
160     // trait info
161     fn implementations_of_trait(&self, def_id: DefId) -> Vec<DefId>;
162     fn provided_trait_methods(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
163                               -> Vec<Rc<ty::Method<'tcx>>>;
164     fn trait_item_def_ids(&self, def: DefId)
165                           -> Vec<ty::ImplOrTraitItemId>;
166
167     // impl info
168     fn impl_items(&self, impl_def_id: DefId) -> Vec<ty::ImplOrTraitItemId>;
169     fn impl_trait_ref(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
170                       -> Option<ty::TraitRef<'tcx>>;
171     fn impl_polarity(&self, def: DefId) -> Option<hir::ImplPolarity>;
172     fn custom_coerce_unsized_kind(&self, def: DefId)
173                                   -> Option<ty::adjustment::CustomCoerceUnsized>;
174     fn associated_consts(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
175                          -> Vec<Rc<ty::AssociatedConst<'tcx>>>;
176
177     // trait/impl-item info
178     fn trait_of_item(&self, tcx: &ty::ctxt<'tcx>, def_id: DefId)
179                      -> Option<DefId>;
180     fn impl_or_trait_item(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
181                           -> ty::ImplOrTraitItem<'tcx>;
182
183     // flags
184     fn is_const_fn(&self, did: DefId) -> bool;
185     fn is_defaulted_trait(&self, did: DefId) -> bool;
186     fn is_impl(&self, did: DefId) -> bool;
187     fn is_default_impl(&self, impl_did: DefId) -> bool;
188     fn is_extern_fn(&self, tcx: &ty::ctxt<'tcx>, did: DefId) -> bool;
189     fn is_static(&self, did: DefId) -> bool;
190     fn is_static_method(&self, did: DefId) -> bool;
191     fn is_statically_included_foreign_item(&self, id: ast::NodeId) -> bool;
192     fn is_typedef(&self, did: DefId) -> bool;
193
194     // crate metadata
195     fn dylib_dependency_formats(&self, cnum: ast::CrateNum)
196                                     -> Vec<(ast::CrateNum, LinkagePreference)>;
197     fn lang_items(&self, cnum: ast::CrateNum) -> Vec<(DefIndex, usize)>;
198     fn missing_lang_items(&self, cnum: ast::CrateNum) -> Vec<lang_items::LangItem>;
199     fn is_staged_api(&self, cnum: ast::CrateNum) -> bool;
200     fn is_explicitly_linked(&self, cnum: ast::CrateNum) -> bool;
201     fn is_allocator(&self, cnum: ast::CrateNum) -> bool;
202     fn crate_attrs(&self, cnum: ast::CrateNum) -> Vec<ast::Attribute>;
203     fn crate_name(&self, cnum: ast::CrateNum) -> String;
204     fn crate_hash(&self, cnum: ast::CrateNum) -> Svh;
205     fn crate_struct_field_attrs(&self, cnum: ast::CrateNum)
206                                 -> FnvHashMap<DefId, Vec<ast::Attribute>>;
207     fn plugin_registrar_fn(&self, cnum: ast::CrateNum) -> Option<DefId>;
208     fn native_libraries(&self, cnum: ast::CrateNum) -> Vec<(NativeLibraryKind, String)>;
209     fn reachable_ids(&self, cnum: ast::CrateNum) -> Vec<DefId>;
210
211     // resolve
212     fn def_path(&self, def: DefId) -> hir_map::DefPath;
213     fn tuple_struct_definition_if_ctor(&self, did: DefId) -> Option<DefId>;
214     fn struct_field_names(&self, def: DefId) -> Vec<ast::Name>;
215     fn item_children(&self, did: DefId) -> Vec<ChildItem>;
216     fn crate_top_level_items(&self, cnum: ast::CrateNum) -> Vec<ChildItem>;
217
218     // misc. metadata
219     fn maybe_get_item_ast(&'tcx self, tcx: &ty::ctxt<'tcx>, def: DefId)
220                           -> FoundAst<'tcx>;
221     fn maybe_get_item_mir(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
222                           -> Option<Mir<'tcx>>;
223     // This is basically a 1-based range of ints, which is a little
224     // silly - I may fix that.
225     fn crates(&self) -> Vec<ast::CrateNum>;
226     fn used_libraries(&self) -> Vec<(String, NativeLibraryKind)>;
227     fn used_link_args(&self) -> Vec<String>;
228
229     // utility functions
230     fn metadata_filename(&self) -> &str;
231     fn metadata_section_name(&self, target: &Target) -> &str;
232     fn encode_type(&self, tcx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> Vec<u8>;
233     fn used_crates(&self, prefer: LinkagePreference) -> Vec<(ast::CrateNum, Option<PathBuf>)>;
234     fn used_crate_source(&self, cnum: ast::CrateNum) -> CrateSource;
235     fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<ast::CrateNum>;
236     fn encode_metadata(&self,
237                        tcx: &ty::ctxt<'tcx>,
238                        reexports: &def::ExportMap,
239                        item_symbols: &RefCell<NodeMap<String>>,
240                        link_meta: &LinkMeta,
241                        reachable: &NodeSet,
242                        mir_map: &NodeMap<Mir<'tcx>>,
243                        krate: &hir::Crate) -> Vec<u8>;
244     fn metadata_encoding_version(&self) -> &[u8];
245 }
246
247 impl InlinedItem {
248     pub fn visit<'ast,V>(&'ast self, visitor: &mut V)
249         where V: Visitor<'ast>
250     {
251         match *self {
252             InlinedItem::Item(ref i) => visitor.visit_item(&**i),
253             InlinedItem::Foreign(ref i) => visitor.visit_foreign_item(&**i),
254             InlinedItem::TraitItem(_, ref ti) => visitor.visit_trait_item(ti),
255             InlinedItem::ImplItem(_, ref ii) => visitor.visit_impl_item(ii),
256         }
257     }
258
259     pub fn visit_ids<O: IdVisitingOperation>(&self, operation: &mut O) {
260         let mut id_visitor = IdVisitor::new(operation);
261         self.visit(&mut id_visitor);
262     }
263 }
264
265 // FIXME: find a better place for this?
266 pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
267     let say = |s: &str| {
268         match (sp, sess) {
269             (_, None) => panic!("{}", s),
270             (Some(sp), Some(sess)) => sess.span_err(sp, s),
271             (None, Some(sess)) => sess.err(s),
272         }
273     };
274     if s.is_empty() {
275         say("crate name must not be empty");
276     }
277     for c in s.chars() {
278         if c.is_alphanumeric() { continue }
279         if c == '_'  { continue }
280         say(&format!("invalid character `{}` in crate name: `{}`", c, s));
281     }
282     match sess {
283         Some(sess) => sess.abort_if_errors(),
284         None => {}
285     }
286 }
287
288 /// A dummy crate store that does not support any non-local crates,
289 /// for test purposes.
290 pub struct DummyCrateStore;
291 #[allow(unused_variables)]
292 impl<'tcx> CrateStore<'tcx> for DummyCrateStore {
293     // item info
294     fn stability(&self, def: DefId) -> Option<attr::Stability> { unimplemented!() }
295     fn closure_kind(&self, tcx: &ty::ctxt<'tcx>, def_id: DefId)
296                     -> ty::ClosureKind  { unimplemented!() }
297     fn closure_ty(&self, tcx: &ty::ctxt<'tcx>, def_id: DefId)
298                   -> ty::ClosureTy<'tcx>  { unimplemented!() }
299     fn item_variances(&self, def: DefId) -> ty::ItemVariances { unimplemented!() }
300     fn repr_attrs(&self, def: DefId) -> Vec<attr::ReprAttr> { unimplemented!() }
301     fn item_type(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
302                  -> ty::TypeScheme<'tcx> { unimplemented!() }
303     fn item_path(&self, def: DefId) -> Vec<hir_map::PathElem> { unimplemented!() }
304     fn extern_item_path(&self, def: DefId) -> Vec<hir_map::PathElem> { unimplemented!() }
305     fn item_name(&self, def: DefId) -> ast::Name { unimplemented!() }
306     fn item_predicates(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
307                        -> ty::GenericPredicates<'tcx> { unimplemented!() }
308     fn item_super_predicates(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
309                              -> ty::GenericPredicates<'tcx> { unimplemented!() }
310     fn item_attrs(&self, def_id: DefId) -> Vec<ast::Attribute> { unimplemented!() }
311     fn item_symbol(&self, def: DefId) -> String { unimplemented!() }
312     fn trait_def(&self, tcx: &ty::ctxt<'tcx>, def: DefId)-> ty::TraitDef<'tcx>
313         { unimplemented!() }
314     fn adt_def(&self, tcx: &ty::ctxt<'tcx>, def: DefId) -> ty::AdtDefMaster<'tcx>
315         { unimplemented!() }
316     fn method_arg_names(&self, did: DefId) -> Vec<String> { unimplemented!() }
317     fn inherent_implementations_for_type(&self, def_id: DefId) -> Vec<DefId> { vec![] }
318
319     // trait info
320     fn implementations_of_trait(&self, def_id: DefId) -> Vec<DefId> { vec![] }
321     fn provided_trait_methods(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
322                               -> Vec<Rc<ty::Method<'tcx>>> { unimplemented!() }
323     fn trait_item_def_ids(&self, def: DefId)
324                           -> Vec<ty::ImplOrTraitItemId> { unimplemented!() }
325
326     // impl info
327     fn impl_items(&self, impl_def_id: DefId) -> Vec<ty::ImplOrTraitItemId>
328         { unimplemented!() }
329     fn impl_trait_ref(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
330                       -> Option<ty::TraitRef<'tcx>> { unimplemented!() }
331     fn impl_polarity(&self, def: DefId) -> Option<hir::ImplPolarity> { unimplemented!() }
332     fn custom_coerce_unsized_kind(&self, def: DefId)
333                                   -> Option<ty::adjustment::CustomCoerceUnsized>
334         { unimplemented!() }
335     fn associated_consts(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
336                          -> Vec<Rc<ty::AssociatedConst<'tcx>>> { unimplemented!() }
337
338     // trait/impl-item info
339     fn trait_of_item(&self, tcx: &ty::ctxt<'tcx>, def_id: DefId)
340                      -> Option<DefId> { unimplemented!() }
341     fn impl_or_trait_item(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
342                           -> ty::ImplOrTraitItem<'tcx> { unimplemented!() }
343
344     // flags
345     fn is_const_fn(&self, did: DefId) -> bool { unimplemented!() }
346     fn is_defaulted_trait(&self, did: DefId) -> bool { unimplemented!() }
347     fn is_impl(&self, did: DefId) -> bool { unimplemented!() }
348     fn is_default_impl(&self, impl_did: DefId) -> bool { unimplemented!() }
349     fn is_extern_fn(&self, tcx: &ty::ctxt<'tcx>, did: DefId) -> bool { unimplemented!() }
350     fn is_static(&self, did: DefId) -> bool { unimplemented!() }
351     fn is_static_method(&self, did: DefId) -> bool { unimplemented!() }
352     fn is_statically_included_foreign_item(&self, id: ast::NodeId) -> bool { false }
353     fn is_typedef(&self, did: DefId) -> bool { unimplemented!() }
354
355     // crate metadata
356     fn dylib_dependency_formats(&self, cnum: ast::CrateNum)
357                                     -> Vec<(ast::CrateNum, LinkagePreference)>
358         { unimplemented!() }
359     fn lang_items(&self, cnum: ast::CrateNum) -> Vec<(DefIndex, usize)>
360         { unimplemented!() }
361     fn missing_lang_items(&self, cnum: ast::CrateNum) -> Vec<lang_items::LangItem>
362         { unimplemented!() }
363     fn is_staged_api(&self, cnum: ast::CrateNum) -> bool { unimplemented!() }
364     fn is_explicitly_linked(&self, cnum: ast::CrateNum) -> bool { unimplemented!() }
365     fn is_allocator(&self, cnum: ast::CrateNum) -> bool { unimplemented!() }
366     fn crate_attrs(&self, cnum: ast::CrateNum) -> Vec<ast::Attribute>
367         { unimplemented!() }
368     fn crate_name(&self, cnum: ast::CrateNum) -> String { unimplemented!() }
369     fn crate_hash(&self, cnum: ast::CrateNum) -> Svh { unimplemented!() }
370     fn crate_struct_field_attrs(&self, cnum: ast::CrateNum)
371                                 -> FnvHashMap<DefId, Vec<ast::Attribute>>
372         { unimplemented!() }
373     fn plugin_registrar_fn(&self, cnum: ast::CrateNum) -> Option<DefId>
374         { unimplemented!() }
375     fn native_libraries(&self, cnum: ast::CrateNum) -> Vec<(NativeLibraryKind, String)>
376         { unimplemented!() }
377     fn reachable_ids(&self, cnum: ast::CrateNum) -> Vec<DefId> { unimplemented!() }
378
379     // resolve
380     fn def_path(&self, def: DefId) -> hir_map::DefPath { unimplemented!() }
381     fn tuple_struct_definition_if_ctor(&self, did: DefId) -> Option<DefId>
382         { unimplemented!() }
383     fn struct_field_names(&self, def: DefId) -> Vec<ast::Name> { unimplemented!() }
384     fn item_children(&self, did: DefId) -> Vec<ChildItem> { unimplemented!() }
385     fn crate_top_level_items(&self, cnum: ast::CrateNum) -> Vec<ChildItem>
386         { unimplemented!() }
387
388     // misc. metadata
389     fn maybe_get_item_ast(&'tcx self, tcx: &ty::ctxt<'tcx>, def: DefId)
390                           -> FoundAst<'tcx> { unimplemented!() }
391     fn maybe_get_item_mir(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
392                           -> Option<Mir<'tcx>> { unimplemented!() }
393
394     // This is basically a 1-based range of ints, which is a little
395     // silly - I may fix that.
396     fn crates(&self) -> Vec<ast::CrateNum> { vec![] }
397     fn used_libraries(&self) -> Vec<(String, NativeLibraryKind)> { vec![] }
398     fn used_link_args(&self) -> Vec<String> { vec![] }
399
400     // utility functions
401     fn metadata_filename(&self) -> &str { unimplemented!() }
402     fn metadata_section_name(&self, target: &Target) -> &str { unimplemented!() }
403     fn encode_type(&self, tcx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> Vec<u8>
404         { unimplemented!() }
405     fn used_crates(&self, prefer: LinkagePreference) -> Vec<(ast::CrateNum, Option<PathBuf>)>
406         { vec![] }
407     fn used_crate_source(&self, cnum: ast::CrateNum) -> CrateSource { unimplemented!() }
408     fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<ast::CrateNum> { None }
409     fn encode_metadata(&self,
410                        tcx: &ty::ctxt<'tcx>,
411                        reexports: &def::ExportMap,
412                        item_symbols: &RefCell<NodeMap<String>>,
413                        link_meta: &LinkMeta,
414                        reachable: &NodeSet,
415                        mir_map: &NodeMap<Mir<'tcx>>,
416                        krate: &hir::Crate) -> Vec<u8> { vec![] }
417     fn metadata_encoding_version(&self) -> &[u8] { unimplemented!() }
418 }
419
420
421 /// Metadata encoding and decoding can make use of thread-local encoding and
422 /// decoding contexts. These allow implementers of serialize::Encodable and
423 /// Decodable to access information and datastructures that would otherwise not
424 /// be available to them. For example, we can automatically translate def-id and
425 /// span information during decoding because the decoding context knows which
426 /// crate the data is decoded from. Or it allows to make ty::Ty decodable
427 /// because the context has access to the ty::ctxt that is needed for creating
428 /// ty::Ty instances.
429 ///
430 /// Note, however, that this only works for RBML-based encoding and decoding at
431 /// the moment.
432 pub mod tls {
433     use rbml::writer::Encoder as RbmlEncoder;
434     use rbml::reader::Decoder as RbmlDecoder;
435     use serialize;
436     use std::mem;
437     use middle::ty::{self, Ty};
438     use middle::subst::Substs;
439     use middle::def_id::DefId;
440
441     pub trait EncodingContext<'tcx> {
442         fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx>;
443         fn encode_ty(&self, rbml_w: &mut RbmlEncoder, t: Ty<'tcx>);
444         fn encode_substs(&self, rbml_w: &mut RbmlEncoder, substs: &Substs<'tcx>);
445     }
446
447     /// Marker type used for the scoped TLS slot.
448     /// The type context cannot be used directly because the scoped TLS
449     /// in libstd doesn't allow types generic over lifetimes.
450     struct TlsPayload;
451
452     scoped_thread_local!(static TLS_ENCODING: TlsPayload);
453
454     /// Execute f after pushing the given EncodingContext onto the TLS stack.
455     pub fn enter_encoding_context<'tcx, F, R>(ecx: &EncodingContext<'tcx>,
456                                               rbml_w: &mut RbmlEncoder,
457                                               f: F) -> R
458         where F: FnOnce(&EncodingContext<'tcx>, &mut RbmlEncoder) -> R
459     {
460         let tls_payload = (ecx as *const _, rbml_w as *mut _);
461         let tls_ptr = &tls_payload as *const _ as *const TlsPayload;
462         TLS_ENCODING.set(unsafe { &*tls_ptr }, || f(ecx, rbml_w))
463     }
464
465     /// Execute f with access to the thread-local encoding context and
466     /// rbml encoder. This function will panic if the encoder passed in and the
467     /// context encoder are not the same.
468     ///
469     /// Note that this method is 'practically' safe due to its checking that the
470     /// encoder passed in is the same as the one in TLS, but it would still be
471     /// possible to construct cases where the EncodingContext is exchanged
472     /// while the same encoder is used, thus working with a wrong context.
473     pub fn with_encoding_context<'tcx, E, F, R>(encoder: &mut E, f: F) -> R
474         where F: FnOnce(&EncodingContext<'tcx>, &mut RbmlEncoder) -> R,
475               E: serialize::Encoder
476     {
477         unsafe {
478             unsafe_with_encoding_context(|ecx, rbml_w| {
479                 assert!(encoder as *mut _ as usize == rbml_w as *mut _ as usize);
480
481                 let ecx: &EncodingContext<'tcx> = mem::transmute(ecx);
482
483                 f(ecx, rbml_w)
484             })
485         }
486     }
487
488     /// Execute f with access to the thread-local encoding context and
489     /// rbml encoder.
490     pub unsafe fn unsafe_with_encoding_context<F, R>(f: F) -> R
491         where F: FnOnce(&EncodingContext, &mut RbmlEncoder) -> R
492     {
493         TLS_ENCODING.with(|tls| {
494             let tls_payload = (tls as *const TlsPayload)
495                                    as *mut (&EncodingContext, &mut RbmlEncoder);
496             f((*tls_payload).0, (*tls_payload).1)
497         })
498     }
499
500     pub trait DecodingContext<'tcx> {
501         fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx>;
502         fn decode_ty(&self, rbml_r: &mut RbmlDecoder) -> ty::Ty<'tcx>;
503         fn decode_substs(&self, rbml_r: &mut RbmlDecoder) -> Substs<'tcx>;
504         fn translate_def_id(&self, def_id: DefId) -> DefId;
505     }
506
507     scoped_thread_local!(static TLS_DECODING: TlsPayload);
508
509     /// Execute f after pushing the given DecodingContext onto the TLS stack.
510     pub fn enter_decoding_context<'tcx, F, R>(dcx: &DecodingContext<'tcx>,
511                                               rbml_r: &mut RbmlDecoder,
512                                               f: F) -> R
513         where F: FnOnce(&DecodingContext<'tcx>, &mut RbmlDecoder) -> R
514     {
515         let tls_payload = (dcx as *const _, rbml_r as *mut _);
516         let tls_ptr = &tls_payload as *const _ as *const TlsPayload;
517         TLS_DECODING.set(unsafe { &*tls_ptr }, || f(dcx, rbml_r))
518     }
519
520     /// Execute f with access to the thread-local decoding context and
521     /// rbml decoder. This function will panic if the decoder passed in and the
522     /// context decoder are not the same.
523     ///
524     /// Note that this method is 'practically' safe due to its checking that the
525     /// decoder passed in is the same as the one in TLS, but it would still be
526     /// possible to construct cases where the DecodingContext is exchanged
527     /// while the same decoder is used, thus working with a wrong context.
528     pub fn with_decoding_context<'decoder, 'tcx, D, F, R>(d: &'decoder mut D, f: F) -> R
529         where D: serialize::Decoder,
530               F: FnOnce(&DecodingContext<'tcx>,
531                         &mut RbmlDecoder) -> R,
532               'tcx: 'decoder
533     {
534         unsafe {
535             unsafe_with_decoding_context(|dcx, rbml_r| {
536                 assert!((d as *mut _ as usize) == (rbml_r as *mut _ as usize));
537
538                 let dcx: &DecodingContext<'tcx> = mem::transmute(dcx);
539
540                 f(dcx, rbml_r)
541             })
542         }
543     }
544
545     /// Execute f with access to the thread-local decoding context and
546     /// rbml decoder.
547     pub unsafe fn unsafe_with_decoding_context<F, R>(f: F) -> R
548         where F: FnOnce(&DecodingContext, &mut RbmlDecoder) -> R
549     {
550         TLS_DECODING.with(|tls| {
551             let tls_payload = (tls as *const TlsPayload)
552                                    as *mut (&DecodingContext, &mut RbmlDecoder);
553             f((*tls_payload).0, (*tls_payload).1)
554         })
555     }
556 }