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