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.
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.
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.
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.
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.
26 use front::map as hir_map;
27 use middle::def::{self, Def};
28 use middle::lang_items;
29 use middle::ty::{self, Ty, TyCtxt, VariantKind};
30 use middle::def_id::{DefId, DefIndex};
32 use mir::mir_map::MirMap;
34 use session::search_paths::PathKind;
35 use util::nodemap::{FnvHashMap, NodeMap, NodeSet};
37 use std::cell::RefCell;
39 use std::path::PathBuf;
41 use syntax::ast_util::{IdVisitingOperation};
43 use syntax::codemap::Span;
45 use syntax::parse::token::InternedString;
46 use rustc_back::target::Target;
48 use rustc_front::intravisit::Visitor;
49 use rustc_front::util::IdVisitor;
51 pub use self::DefLike::{DlDef, DlField, DlImpl};
52 pub use self::NativeLibraryKind::{NativeStatic, NativeFramework, NativeUnknown};
54 // lonely orphan structs and enums looking for a better home
56 #[derive(Clone, Debug)]
58 pub crate_name: String,
62 // Where a crate came from on the local filesystem. One of these two options
64 #[derive(PartialEq, Clone, Debug)]
65 pub struct CrateSource {
66 pub dylib: Option<(PathBuf, PathKind)>,
67 pub rlib: Option<(PathBuf, PathKind)>,
68 pub cnum: ast::CrateNum,
71 #[derive(Copy, Debug, PartialEq, Clone)]
72 pub enum LinkagePreference {
78 #[derive(Copy, Clone, PartialEq)]
79 pub enum NativeLibraryKind {
80 NativeStatic, // native static library (.a archive)
81 NativeFramework, // OSX-specific
82 NativeUnknown, // default way to specify a dynamic library
86 // Something that a name can resolve to.
87 #[derive(Copy, Clone, Debug)]
94 /// The data we save and restore about an inlined item or method. This is not
95 /// part of the AST that we parse from a file, but it becomes part of the tree
97 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
98 pub enum InlinedItem {
100 TraitItem(DefId /* impl id */, P<hir::TraitItem>),
101 ImplItem(DefId /* impl id */, P<hir::ImplItem>),
102 Foreign(P<hir::ForeignItem>),
105 /// A borrowed version of `hir::InlinedItem`.
106 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
107 pub enum InlinedItemRef<'a> {
109 TraitItem(DefId, &'a hir::TraitItem),
110 ImplItem(DefId, &'a hir::ImplItem),
111 Foreign(&'a hir::ForeignItem)
114 /// Item definitions in the currently-compiled crate would have the CrateNum
115 /// LOCAL_CRATE in their DefId.
116 pub const LOCAL_CRATE: ast::CrateNum = 0;
118 pub struct ChildItem {
121 pub vis: hir::Visibility
124 pub enum FoundAst<'ast> {
125 Found(&'ast InlinedItem),
126 FoundParent(DefId, &'ast hir::Item),
130 /// A store of Rust crates, through with their metadata
133 /// The `: Any` bound is a temporary measure that allows access
134 /// to the backing `rustc_metadata::cstore::CStore` object. It
135 /// will be removed in the near future - if you need to access
136 /// internal APIs, please tell us.
137 pub trait CrateStore<'tcx> : Any {
139 fn stability(&self, def: DefId) -> Option<attr::Stability>;
140 fn deprecation(&self, def: DefId) -> Option<attr::Deprecation>;
141 fn visibility(&self, def: DefId) -> hir::Visibility;
142 fn closure_kind(&self, tcx: &TyCtxt<'tcx>, def_id: DefId)
144 fn closure_ty(&self, tcx: &TyCtxt<'tcx>, def_id: DefId)
145 -> ty::ClosureTy<'tcx>;
146 fn item_variances(&self, def: DefId) -> ty::ItemVariances;
147 fn repr_attrs(&self, def: DefId) -> Vec<attr::ReprAttr>;
148 fn item_type(&self, tcx: &TyCtxt<'tcx>, def: DefId)
149 -> ty::TypeScheme<'tcx>;
150 fn item_path(&self, def: DefId) -> Vec<hir_map::PathElem>;
151 fn extern_item_path(&self, def: DefId) -> Vec<hir_map::PathElem>;
152 fn item_name(&self, def: DefId) -> ast::Name;
153 fn item_predicates(&self, tcx: &TyCtxt<'tcx>, def: DefId)
154 -> ty::GenericPredicates<'tcx>;
155 fn item_super_predicates(&self, tcx: &TyCtxt<'tcx>, def: DefId)
156 -> ty::GenericPredicates<'tcx>;
157 fn item_attrs(&self, def_id: DefId) -> Vec<ast::Attribute>;
158 fn item_symbol(&self, def: DefId) -> String;
159 fn trait_def(&self, tcx: &TyCtxt<'tcx>, def: DefId)-> ty::TraitDef<'tcx>;
160 fn adt_def(&self, tcx: &TyCtxt<'tcx>, def: DefId) -> ty::AdtDefMaster<'tcx>;
161 fn method_arg_names(&self, did: DefId) -> Vec<String>;
162 fn inherent_implementations_for_type(&self, def_id: DefId) -> Vec<DefId>;
165 fn implementations_of_trait(&self, def_id: DefId) -> Vec<DefId>;
166 fn provided_trait_methods(&self, tcx: &TyCtxt<'tcx>, def: DefId)
167 -> Vec<Rc<ty::Method<'tcx>>>;
168 fn trait_item_def_ids(&self, def: DefId)
169 -> Vec<ty::ImplOrTraitItemId>;
172 fn impl_items(&self, impl_def_id: DefId) -> Vec<ty::ImplOrTraitItemId>;
173 fn impl_trait_ref(&self, tcx: &TyCtxt<'tcx>, def: DefId)
174 -> Option<ty::TraitRef<'tcx>>;
175 fn impl_polarity(&self, def: DefId) -> Option<hir::ImplPolarity>;
176 fn custom_coerce_unsized_kind(&self, def: DefId)
177 -> Option<ty::adjustment::CustomCoerceUnsized>;
178 fn associated_consts(&self, tcx: &TyCtxt<'tcx>, def: DefId)
179 -> Vec<Rc<ty::AssociatedConst<'tcx>>>;
180 fn impl_parent(&self, impl_def_id: DefId) -> Option<DefId>;
182 // trait/impl-item info
183 fn trait_of_item(&self, tcx: &TyCtxt<'tcx>, def_id: DefId)
185 fn impl_or_trait_item(&self, tcx: &TyCtxt<'tcx>, def: DefId)
186 -> Option<ty::ImplOrTraitItem<'tcx>>;
189 fn is_const_fn(&self, did: DefId) -> bool;
190 fn is_defaulted_trait(&self, did: DefId) -> bool;
191 fn is_impl(&self, did: DefId) -> bool;
192 fn is_default_impl(&self, impl_did: DefId) -> bool;
193 fn is_extern_item(&self, tcx: &TyCtxt<'tcx>, did: DefId) -> bool;
194 fn is_static_method(&self, did: DefId) -> bool;
195 fn is_statically_included_foreign_item(&self, id: ast::NodeId) -> bool;
196 fn is_typedef(&self, did: DefId) -> bool;
199 fn dylib_dependency_formats(&self, cnum: ast::CrateNum)
200 -> Vec<(ast::CrateNum, LinkagePreference)>;
201 fn lang_items(&self, cnum: ast::CrateNum) -> Vec<(DefIndex, usize)>;
202 fn missing_lang_items(&self, cnum: ast::CrateNum) -> Vec<lang_items::LangItem>;
203 fn is_staged_api(&self, cnum: ast::CrateNum) -> bool;
204 fn is_explicitly_linked(&self, cnum: ast::CrateNum) -> bool;
205 fn is_allocator(&self, cnum: ast::CrateNum) -> bool;
206 fn crate_attrs(&self, cnum: ast::CrateNum) -> Vec<ast::Attribute>;
207 /// The name of the crate as it is referred to in source code of the current
209 fn crate_name(&self, cnum: ast::CrateNum) -> InternedString;
210 /// The name of the crate as it is stored in the crate's metadata.
211 fn original_crate_name(&self, cnum: ast::CrateNum) -> InternedString;
212 fn crate_hash(&self, cnum: ast::CrateNum) -> Svh;
213 fn crate_disambiguator(&self, cnum: ast::CrateNum) -> InternedString;
214 fn crate_struct_field_attrs(&self, cnum: ast::CrateNum)
215 -> FnvHashMap<DefId, Vec<ast::Attribute>>;
216 fn plugin_registrar_fn(&self, cnum: ast::CrateNum) -> Option<DefId>;
217 fn native_libraries(&self, cnum: ast::CrateNum) -> Vec<(NativeLibraryKind, String)>;
218 fn reachable_ids(&self, cnum: ast::CrateNum) -> Vec<DefId>;
221 fn def_path(&self, def: DefId) -> hir_map::DefPath;
222 fn variant_kind(&self, def_id: DefId) -> Option<VariantKind>;
223 fn struct_ctor_def_id(&self, struct_def_id: DefId) -> Option<DefId>;
224 fn tuple_struct_definition_if_ctor(&self, did: DefId) -> Option<DefId>;
225 fn struct_field_names(&self, def: DefId) -> Vec<ast::Name>;
226 fn item_children(&self, did: DefId) -> Vec<ChildItem>;
227 fn crate_top_level_items(&self, cnum: ast::CrateNum) -> Vec<ChildItem>;
230 fn maybe_get_item_ast(&'tcx self, tcx: &TyCtxt<'tcx>, def: DefId)
232 fn maybe_get_item_mir(&self, tcx: &TyCtxt<'tcx>, def: DefId)
233 -> Option<Mir<'tcx>>;
234 fn is_item_mir_available(&self, def: DefId) -> bool;
236 // This is basically a 1-based range of ints, which is a little
237 // silly - I may fix that.
238 fn crates(&self) -> Vec<ast::CrateNum>;
239 fn used_libraries(&self) -> Vec<(String, NativeLibraryKind)>;
240 fn used_link_args(&self) -> Vec<String>;
243 fn metadata_filename(&self) -> &str;
244 fn metadata_section_name(&self, target: &Target) -> &str;
245 fn encode_type(&self,
248 def_id_to_string: fn(&TyCtxt<'tcx>, DefId) -> String)
250 fn used_crates(&self, prefer: LinkagePreference) -> Vec<(ast::CrateNum, Option<PathBuf>)>;
251 fn used_crate_source(&self, cnum: ast::CrateNum) -> CrateSource;
252 fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<ast::CrateNum>;
253 fn encode_metadata(&self,
255 reexports: &def::ExportMap,
256 item_symbols: &RefCell<NodeMap<String>>,
257 link_meta: &LinkMeta,
259 mir_map: &MirMap<'tcx>,
260 krate: &hir::Crate) -> Vec<u8>;
261 fn metadata_encoding_version(&self) -> &[u8];
265 pub fn visit<'ast,V>(&'ast self, visitor: &mut V)
266 where V: Visitor<'ast>
269 InlinedItem::Item(ref i) => visitor.visit_item(&i),
270 InlinedItem::Foreign(ref i) => visitor.visit_foreign_item(&i),
271 InlinedItem::TraitItem(_, ref ti) => visitor.visit_trait_item(ti),
272 InlinedItem::ImplItem(_, ref ii) => visitor.visit_impl_item(ii),
276 pub fn visit_ids<O: IdVisitingOperation>(&self, operation: &mut O) {
277 let mut id_visitor = IdVisitor::new(operation);
278 self.visit(&mut id_visitor);
282 // FIXME: find a better place for this?
283 pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
284 let mut err_count = 0;
286 let mut say = |s: &str| {
288 (_, None) => panic!("{}", s),
289 (Some(sp), Some(sess)) => sess.span_err(sp, s),
290 (None, Some(sess)) => sess.err(s),
295 say("crate name must not be empty");
298 if c.is_alphanumeric() { continue }
299 if c == '_' { continue }
300 say(&format!("invalid character `{}` in crate name: `{}`", c, s));
305 sess.unwrap().abort_if_errors();
309 /// A dummy crate store that does not support any non-local crates,
310 /// for test purposes.
311 pub struct DummyCrateStore;
312 #[allow(unused_variables)]
313 impl<'tcx> CrateStore<'tcx> for DummyCrateStore {
315 fn stability(&self, def: DefId) -> Option<attr::Stability> { unimplemented!() }
316 fn deprecation(&self, def: DefId) -> Option<attr::Deprecation> { unimplemented!() }
317 fn visibility(&self, def: DefId) -> hir::Visibility { unimplemented!() }
318 fn closure_kind(&self, tcx: &TyCtxt<'tcx>, def_id: DefId)
319 -> ty::ClosureKind { unimplemented!() }
320 fn closure_ty(&self, tcx: &TyCtxt<'tcx>, def_id: DefId)
321 -> ty::ClosureTy<'tcx> { unimplemented!() }
322 fn item_variances(&self, def: DefId) -> ty::ItemVariances { unimplemented!() }
323 fn repr_attrs(&self, def: DefId) -> Vec<attr::ReprAttr> { unimplemented!() }
324 fn item_type(&self, tcx: &TyCtxt<'tcx>, def: DefId)
325 -> ty::TypeScheme<'tcx> { unimplemented!() }
326 fn item_path(&self, def: DefId) -> Vec<hir_map::PathElem> { unimplemented!() }
327 fn extern_item_path(&self, def: DefId) -> Vec<hir_map::PathElem> { unimplemented!() }
328 fn item_name(&self, def: DefId) -> ast::Name { unimplemented!() }
329 fn item_predicates(&self, tcx: &TyCtxt<'tcx>, def: DefId)
330 -> ty::GenericPredicates<'tcx> { unimplemented!() }
331 fn item_super_predicates(&self, tcx: &TyCtxt<'tcx>, def: DefId)
332 -> ty::GenericPredicates<'tcx> { unimplemented!() }
333 fn item_attrs(&self, def_id: DefId) -> Vec<ast::Attribute> { unimplemented!() }
334 fn item_symbol(&self, def: DefId) -> String { unimplemented!() }
335 fn trait_def(&self, tcx: &TyCtxt<'tcx>, def: DefId)-> ty::TraitDef<'tcx>
337 fn adt_def(&self, tcx: &TyCtxt<'tcx>, def: DefId) -> ty::AdtDefMaster<'tcx>
339 fn method_arg_names(&self, did: DefId) -> Vec<String> { unimplemented!() }
340 fn inherent_implementations_for_type(&self, def_id: DefId) -> Vec<DefId> { vec![] }
343 fn implementations_of_trait(&self, def_id: DefId) -> Vec<DefId> { vec![] }
344 fn provided_trait_methods(&self, tcx: &TyCtxt<'tcx>, def: DefId)
345 -> Vec<Rc<ty::Method<'tcx>>> { unimplemented!() }
346 fn trait_item_def_ids(&self, def: DefId)
347 -> Vec<ty::ImplOrTraitItemId> { unimplemented!() }
350 fn impl_items(&self, impl_def_id: DefId) -> Vec<ty::ImplOrTraitItemId>
352 fn impl_trait_ref(&self, tcx: &TyCtxt<'tcx>, def: DefId)
353 -> Option<ty::TraitRef<'tcx>> { unimplemented!() }
354 fn impl_polarity(&self, def: DefId) -> Option<hir::ImplPolarity> { unimplemented!() }
355 fn custom_coerce_unsized_kind(&self, def: DefId)
356 -> Option<ty::adjustment::CustomCoerceUnsized>
358 fn associated_consts(&self, tcx: &TyCtxt<'tcx>, def: DefId)
359 -> Vec<Rc<ty::AssociatedConst<'tcx>>> { unimplemented!() }
360 fn impl_parent(&self, def: DefId) -> Option<DefId> { unimplemented!() }
362 // trait/impl-item info
363 fn trait_of_item(&self, tcx: &TyCtxt<'tcx>, def_id: DefId)
364 -> Option<DefId> { unimplemented!() }
365 fn impl_or_trait_item(&self, tcx: &TyCtxt<'tcx>, def: DefId)
366 -> Option<ty::ImplOrTraitItem<'tcx>> { unimplemented!() }
369 fn is_const_fn(&self, did: DefId) -> bool { unimplemented!() }
370 fn is_defaulted_trait(&self, did: DefId) -> bool { unimplemented!() }
371 fn is_impl(&self, did: DefId) -> bool { unimplemented!() }
372 fn is_default_impl(&self, impl_did: DefId) -> bool { unimplemented!() }
373 fn is_extern_item(&self, tcx: &TyCtxt<'tcx>, did: DefId) -> bool { unimplemented!() }
374 fn is_static_method(&self, did: DefId) -> bool { unimplemented!() }
375 fn is_statically_included_foreign_item(&self, id: ast::NodeId) -> bool { false }
376 fn is_typedef(&self, did: DefId) -> bool { unimplemented!() }
379 fn dylib_dependency_formats(&self, cnum: ast::CrateNum)
380 -> Vec<(ast::CrateNum, LinkagePreference)>
382 fn lang_items(&self, cnum: ast::CrateNum) -> Vec<(DefIndex, usize)>
384 fn missing_lang_items(&self, cnum: ast::CrateNum) -> Vec<lang_items::LangItem>
386 fn is_staged_api(&self, cnum: ast::CrateNum) -> bool { unimplemented!() }
387 fn is_explicitly_linked(&self, cnum: ast::CrateNum) -> bool { unimplemented!() }
388 fn is_allocator(&self, cnum: ast::CrateNum) -> bool { unimplemented!() }
389 fn crate_attrs(&self, cnum: ast::CrateNum) -> Vec<ast::Attribute>
391 fn crate_name(&self, cnum: ast::CrateNum) -> InternedString { unimplemented!() }
392 fn original_crate_name(&self, cnum: ast::CrateNum) -> InternedString {
395 fn crate_hash(&self, cnum: ast::CrateNum) -> Svh { unimplemented!() }
396 fn crate_disambiguator(&self, cnum: ast::CrateNum) -> InternedString { unimplemented!() }
397 fn crate_struct_field_attrs(&self, cnum: ast::CrateNum)
398 -> FnvHashMap<DefId, Vec<ast::Attribute>>
400 fn plugin_registrar_fn(&self, cnum: ast::CrateNum) -> Option<DefId>
402 fn native_libraries(&self, cnum: ast::CrateNum) -> Vec<(NativeLibraryKind, String)>
404 fn reachable_ids(&self, cnum: ast::CrateNum) -> Vec<DefId> { unimplemented!() }
407 fn def_path(&self, def: DefId) -> hir_map::DefPath { unimplemented!() }
408 fn variant_kind(&self, def_id: DefId) -> Option<VariantKind> { unimplemented!() }
409 fn struct_ctor_def_id(&self, struct_def_id: DefId) -> Option<DefId>
411 fn tuple_struct_definition_if_ctor(&self, did: DefId) -> Option<DefId>
413 fn struct_field_names(&self, def: DefId) -> Vec<ast::Name> { unimplemented!() }
414 fn item_children(&self, did: DefId) -> Vec<ChildItem> { unimplemented!() }
415 fn crate_top_level_items(&self, cnum: ast::CrateNum) -> Vec<ChildItem>
419 fn maybe_get_item_ast(&'tcx self, tcx: &TyCtxt<'tcx>, def: DefId)
420 -> FoundAst<'tcx> { unimplemented!() }
421 fn maybe_get_item_mir(&self, tcx: &TyCtxt<'tcx>, def: DefId)
422 -> Option<Mir<'tcx>> { unimplemented!() }
423 fn is_item_mir_available(&self, def: DefId) -> bool {
427 // This is basically a 1-based range of ints, which is a little
428 // silly - I may fix that.
429 fn crates(&self) -> Vec<ast::CrateNum> { vec![] }
430 fn used_libraries(&self) -> Vec<(String, NativeLibraryKind)> { vec![] }
431 fn used_link_args(&self) -> Vec<String> { vec![] }
434 fn metadata_filename(&self) -> &str { unimplemented!() }
435 fn metadata_section_name(&self, target: &Target) -> &str { unimplemented!() }
436 fn encode_type(&self,
439 def_id_to_string: fn(&TyCtxt<'tcx>, DefId) -> String)
443 fn used_crates(&self, prefer: LinkagePreference) -> Vec<(ast::CrateNum, Option<PathBuf>)>
445 fn used_crate_source(&self, cnum: ast::CrateNum) -> CrateSource { unimplemented!() }
446 fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<ast::CrateNum> { None }
447 fn encode_metadata(&self,
449 reexports: &def::ExportMap,
450 item_symbols: &RefCell<NodeMap<String>>,
451 link_meta: &LinkMeta,
453 mir_map: &MirMap<'tcx>,
454 krate: &hir::Crate) -> Vec<u8> { vec![] }
455 fn metadata_encoding_version(&self) -> &[u8] { unimplemented!() }
459 /// Metadata encoding and decoding can make use of thread-local encoding and
460 /// decoding contexts. These allow implementers of serialize::Encodable and
461 /// Decodable to access information and datastructures that would otherwise not
462 /// be available to them. For example, we can automatically translate def-id and
463 /// span information during decoding because the decoding context knows which
464 /// crate the data is decoded from. Or it allows to make ty::Ty decodable
465 /// because the context has access to the TyCtxt that is needed for creating
466 /// ty::Ty instances.
468 /// Note, however, that this only works for RBML-based encoding and decoding at
471 use rbml::opaque::Encoder as OpaqueEncoder;
472 use rbml::opaque::Decoder as OpaqueDecoder;
476 use middle::ty::{self, Ty, TyCtxt};
477 use middle::subst::Substs;
478 use middle::def_id::DefId;
480 pub trait EncodingContext<'tcx> {
481 fn tcx<'a>(&'a self) -> &'a TyCtxt<'tcx>;
482 fn encode_ty(&self, encoder: &mut OpaqueEncoder, t: Ty<'tcx>);
483 fn encode_substs(&self, encoder: &mut OpaqueEncoder, substs: &Substs<'tcx>);
486 /// Marker type used for the TLS slot.
487 /// The type context cannot be used directly because the TLS
488 /// in libstd doesn't allow types generic over lifetimes.
492 static TLS_ENCODING: Cell<Option<*const TlsPayload>> = Cell::new(None)
495 /// Execute f after pushing the given EncodingContext onto the TLS stack.
496 pub fn enter_encoding_context<'tcx, F, R>(ecx: &EncodingContext<'tcx>,
497 encoder: &mut OpaqueEncoder,
499 where F: FnOnce(&EncodingContext<'tcx>, &mut OpaqueEncoder) -> R
501 let tls_payload = (ecx as *const _, encoder as *mut _);
502 let tls_ptr = &tls_payload as *const _ as *const TlsPayload;
503 TLS_ENCODING.with(|tls| {
504 let prev = tls.get();
505 tls.set(Some(tls_ptr));
506 let ret = f(ecx, encoder);
512 /// Execute f with access to the thread-local encoding context and
513 /// rbml encoder. This function will panic if the encoder passed in and the
514 /// context encoder are not the same.
516 /// Note that this method is 'practically' safe due to its checking that the
517 /// encoder passed in is the same as the one in TLS, but it would still be
518 /// possible to construct cases where the EncodingContext is exchanged
519 /// while the same encoder is used, thus working with a wrong context.
520 pub fn with_encoding_context<'tcx, E, F, R>(encoder: &mut E, f: F) -> R
521 where F: FnOnce(&EncodingContext<'tcx>, &mut OpaqueEncoder) -> R,
522 E: serialize::Encoder
525 unsafe_with_encoding_context(|ecx, tls_encoder| {
526 assert!(encoder as *mut _ as usize == tls_encoder as *mut _ as usize);
528 let ecx: &EncodingContext<'tcx> = mem::transmute(ecx);
535 /// Execute f with access to the thread-local encoding context and
537 pub unsafe fn unsafe_with_encoding_context<F, R>(f: F) -> R
538 where F: FnOnce(&EncodingContext, &mut OpaqueEncoder) -> R
540 TLS_ENCODING.with(|tls| {
541 let tls = tls.get().unwrap();
542 let tls_payload = tls as *mut (&EncodingContext, &mut OpaqueEncoder);
543 f((*tls_payload).0, (*tls_payload).1)
547 pub trait DecodingContext<'tcx> {
548 fn tcx<'a>(&'a self) -> &'a TyCtxt<'tcx>;
549 fn decode_ty(&self, decoder: &mut OpaqueDecoder) -> ty::Ty<'tcx>;
550 fn decode_substs(&self, decoder: &mut OpaqueDecoder) -> Substs<'tcx>;
551 fn translate_def_id(&self, def_id: DefId) -> DefId;
555 static TLS_DECODING: Cell<Option<*const TlsPayload>> = Cell::new(None)
558 /// Execute f after pushing the given DecodingContext onto the TLS stack.
559 pub fn enter_decoding_context<'tcx, F, R>(dcx: &DecodingContext<'tcx>,
560 decoder: &mut OpaqueDecoder,
562 where F: FnOnce(&DecodingContext<'tcx>, &mut OpaqueDecoder) -> R
564 let tls_payload = (dcx as *const _, decoder as *mut _);
565 let tls_ptr = &tls_payload as *const _ as *const TlsPayload;
566 TLS_DECODING.with(|tls| {
567 let prev = tls.get();
568 tls.set(Some(tls_ptr));
569 let ret = f(dcx, decoder);
575 /// Execute f with access to the thread-local decoding context and
576 /// rbml decoder. This function will panic if the decoder passed in and the
577 /// context decoder are not the same.
579 /// Note that this method is 'practically' safe due to its checking that the
580 /// decoder passed in is the same as the one in TLS, but it would still be
581 /// possible to construct cases where the DecodingContext is exchanged
582 /// while the same decoder is used, thus working with a wrong context.
583 pub fn with_decoding_context<'decoder, 'tcx, D, F, R>(d: &'decoder mut D, f: F) -> R
584 where D: serialize::Decoder,
585 F: FnOnce(&DecodingContext<'tcx>,
586 &mut OpaqueDecoder) -> R,
590 unsafe_with_decoding_context(|dcx, decoder| {
591 assert!((d as *mut _ as usize) == (decoder as *mut _ as usize));
593 let dcx: &DecodingContext<'tcx> = mem::transmute(dcx);
600 /// Execute f with access to the thread-local decoding context and
602 pub unsafe fn unsafe_with_decoding_context<F, R>(f: F) -> R
603 where F: FnOnce(&DecodingContext, &mut OpaqueDecoder) -> R
605 TLS_DECODING.with(|tls| {
606 let tls = tls.get().unwrap();
607 let tls_payload = tls as *mut (&DecodingContext, &mut OpaqueDecoder);
608 f((*tls_payload).0, (*tls_payload).1)