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