提交 91e7239d 编写于 作者: E Eduard Burtescu

rustc_metadata: combine DecodeContext and rbml::reader::Decoder.

上级 97864d41
......@@ -495,68 +495,4 @@ fn metadata_encoding_version(&self) -> &[u8] { bug!("metadata_encoding_version")
pub trait MacroLoader {
fn load_crate(&mut self, extern_crate: &ast::Item, allows_macros: bool) -> Vec<LoadedMacro>;
}
/// Metadata encoding and decoding can make use of thread-local encoding and
/// decoding contexts. These allow implementers of serialize::Encodable and
/// Decodable to access information and datastructures that would otherwise not
/// be available to them. For example, we can automatically translate def-id and
/// span information during decoding because the decoding context knows which
/// crate the data is decoded from. Or it allows to make ty::Ty decodable
/// because the context has access to the TyCtxt that is needed for creating
/// ty::Ty instances.
///
/// Note, however, that this only works for RBML-based encoding and decoding at
/// the moment.
pub mod tls {
use rbml::opaque::Decoder as OpaqueDecoder;
use std::cell::Cell;
use ty::{Ty, TyCtxt};
use ty::subst::Substs;
use hir::def_id::DefId;
/// Marker type used for the TLS slot.
/// The type context cannot be used directly because the TLS
/// in libstd doesn't allow types generic over lifetimes.
struct TlsPayload;
pub trait DecodingContext<'tcx> {
fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx>;
fn decode_ty(&self, decoder: &mut OpaqueDecoder) -> Ty<'tcx>;
fn decode_substs(&self, decoder: &mut OpaqueDecoder) -> &'tcx Substs<'tcx>;
fn translate_def_id(&self, def_id: DefId) -> DefId;
}
thread_local! {
static TLS_DECODING: Cell<Option<*const TlsPayload>> = Cell::new(None)
}
/// Execute f after pushing the given DecodingContext onto the TLS stack.
pub fn enter_decoding_context<'tcx, F, R>(dcx: &DecodingContext<'tcx>, f: F) -> R
where F: FnOnce(&DecodingContext<'tcx>) -> R
{
let tls_payload = dcx as *const _;
let tls_ptr = &tls_payload as *const _ as *const TlsPayload;
TLS_DECODING.with(|tls| {
let prev = tls.get();
tls.set(Some(tls_ptr));
let ret = f(dcx);
tls.set(prev);
ret
})
}
/// Execute f with access to the thread-local decoding context.
/// FIXME(eddyb) This is horribly unsound as it allows the
/// caler to pick any lifetime for 'tcx, including 'static.
pub fn with_decoding_context<'tcx, F, R>(f: F) -> R
where F: FnOnce(&DecodingContext<'tcx>) -> R,
{
unsafe {
TLS_DECODING.with(|tls| {
let tls = tls.get().unwrap();
f(*(tls as *mut &DecodingContext))
})
}
}
}
}
\ No newline at end of file
......@@ -20,7 +20,6 @@
use hir::map as ast_map;
use session::Session;
use util::nodemap::{FnvHashMap, NodeMap, NodeSet};
use middle::cstore::InlinedItem;
use ty;
use std::cell::RefCell;
......@@ -1256,19 +1255,3 @@ pub fn resolve_crate(sess: &Session, map: &ast_map::Map) -> RegionMaps {
}
return maps;
}
pub fn resolve_inlined_item(sess: &Session,
region_maps: &RegionMaps,
item: &InlinedItem) {
let mut visitor = RegionResolutionVisitor {
sess: sess,
region_maps: region_maps,
cx: Context {
root_id: None,
parent: ROOT_CODE_EXTENT,
var_parent: ROOT_CODE_EXTENT
},
terminating_scopes: NodeSet()
};
item.visit(&mut visitor);
}
......@@ -21,7 +21,7 @@
use dep_graph::{self, DepNode};
use hir::map as ast_map;
use middle;
use middle::cstore::{self, LOCAL_CRATE};
use middle::cstore::LOCAL_CRATE;
use hir::def::{Def, PathResolution, ExportMap};
use hir::def_id::DefId;
use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem, FnOnceTraitLangItem};
......@@ -34,7 +34,7 @@
use util::nodemap::NodeSet;
use util::nodemap::FnvHashMap;
use serialize::{self, Encodable, Encoder, Decodable, Decoder};
use serialize::{self, Encodable, Encoder};
use std::borrow::Cow;
use std::cell::Cell;
use std::hash::{Hash, Hasher};
......@@ -1487,17 +1487,7 @@ fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
}
}
impl<'tcx> Decodable for AdtDef<'tcx> {
fn decode<D: Decoder>(d: &mut D) -> Result<AdtDef<'tcx>, D::Error> {
let def_id: DefId = Decodable::decode(d)?;
cstore::tls::with_decoding_context(|dcx| {
let def_id = dcx.translate_def_id(def_id);
Ok(dcx.tcx().lookup_adt_def(def_id))
})
}
}
impl<'tcx> serialize::UseSpecializedDecodable for AdtDef<'tcx> {}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum AdtKind { Struct, Union, Enum }
......
......@@ -10,7 +10,6 @@
//! This module contains TypeVariants and its major components
use middle::cstore;
use hir::def_id::DefId;
use middle::region;
use ty::subst::Substs;
......@@ -25,7 +24,7 @@
use syntax::ast::{self, Name};
use syntax::parse::token::{keywords, InternedString};
use serialize::{Decodable, Decoder, Encodable, Encoder};
use serialize;
use hir;
......@@ -253,7 +252,7 @@ pub enum TypeVariants<'tcx> {
/// closure C wind up influencing the decisions we ought to make for
/// closure C (which would then require fixed point iteration to
/// handle). Plus it fixes an ICE. :P
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable)]
pub struct ClosureSubsts<'tcx> {
/// Lifetime and type parameters from the enclosing function.
/// These are separated out because trans wants to pass them around
......@@ -266,23 +265,7 @@ pub struct ClosureSubsts<'tcx> {
pub upvar_tys: &'tcx [Ty<'tcx>]
}
impl<'tcx> Encodable for ClosureSubsts<'tcx> {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
(self.func_substs, self.upvar_tys).encode(s)
}
}
impl<'tcx> Decodable for ClosureSubsts<'tcx> {
fn decode<D: Decoder>(d: &mut D) -> Result<ClosureSubsts<'tcx>, D::Error> {
let (func_substs, upvar_tys) = Decodable::decode(d)?;
cstore::tls::with_decoding_context(|dcx| {
Ok(ClosureSubsts {
func_substs: func_substs,
upvar_tys: dcx.tcx().mk_type_list(upvar_tys)
})
})
}
}
impl<'tcx> serialize::UseSpecializedDecodable for ClosureSubsts<'tcx> {}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct TraitObject<'tcx> {
......@@ -663,14 +646,7 @@ pub enum Region {
ReErased,
}
impl<'tcx> Decodable for &'tcx Region {
fn decode<D: Decoder>(d: &mut D) -> Result<&'tcx Region, D::Error> {
let r = Decodable::decode(d)?;
cstore::tls::with_decoding_context(|dcx| {
Ok(dcx.tcx().mk_region(r))
})
}
}
impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Region {}
#[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
pub struct EarlyBoundRegion {
......
此差异已折叠。
......@@ -10,8 +10,6 @@
#![allow(non_camel_case_types, non_upper_case_globals)]
pub use self::astencode_tag::*;
// RBML enum definitions and utils shared by the encoder and decoder
//
// 0x00..0x1f: reserved for RBML generic type tags
......@@ -97,33 +95,30 @@ impl items contain tag_item_impl_item elements, and classes
pub const tag_items_data_item_reexport_name: usize = 0x48;
// used to encode crate_ctxt side tables
enum_from_u32! {
#[derive(Copy, Clone, PartialEq)]
#[repr(usize)]
pub enum astencode_tag { // Reserves 0x50 -- 0x6f
tag_ast = 0x50,
tag_tree = 0x51,
tag_mir = 0x52,
tag_table = 0x53,
// GAP 0x54, 0x55
tag_table_def = 0x56,
tag_table_node_type = 0x57,
tag_table_item_subst = 0x58,
tag_table_freevars = 0x59,
// GAP 0x5a, 0x5b, 0x5c, 0x5d, 0x5e
tag_table_method_map = 0x5f,
// GAP 0x60
tag_table_adjustments = 0x61,
// GAP 0x62, 0x63, 0x64, 0x65
tag_table_upvar_capture_map = 0x66,
// GAP 0x67, 0x68
tag_table_const_qualif = 0x69,
tag_table_cast_kinds = 0x6a,
}
}
pub const tag_ast: usize = 0x50;
pub const tag_tree: usize = 0x51;
pub const tag_mir: usize = 0x52;
pub const tag_table: usize = 0x53;
pub const tag_id_range: usize = 0x54;
// GAP 0x55
pub const tag_table_def: usize = 0x56;
pub const tag_table_node_type: usize = 0x57;
pub const tag_table_item_subst: usize = 0x58;
pub const tag_table_freevars: usize = 0x59;
// GAP 0x5a, 0x5b, 0x5c, 0x5d, 0x5e
pub const tag_table_method_map: usize = 0x5f;
// GAP 0x60
pub const tag_table_adjustments: usize = 0x61;
// GAP 0x62, 0x63, 0x64, 0x65
pub const tag_table_upvar_capture_map: usize = 0x66;
// GAP 0x67, 0x68
pub const tag_table_const_qualif: usize = 0x69;
pub const tag_table_cast_kinds: usize = 0x6a;
pub const tag_item_trait_item_sort: usize = 0x70;
......
......@@ -20,7 +20,6 @@
use def_key;
use encoder::def_to_u64;
use index;
use tls_context;
use tydecode::TyDecoder;
use rustc::hir::def_id::CRATE_DEF_INDEX;
......@@ -29,15 +28,17 @@
use rustc::hir::map::DefKey;
use rustc::util::nodemap::FnvHashMap;
use rustc::hir;
use rustc::hir::intravisit::IdRange;
use rustc::session::config::PanicStrategy;
use middle::cstore::{InlinedItem, LinkagePreference};
use middle::cstore::{DefLike, DlDef, DlField, DlImpl, tls};
use middle::cstore::{DefLike, DlDef, DlField, DlImpl};
use rustc::hir::def::Def;
use rustc::hir::def_id::{DefId, DefIndex};
use middle::lang_items;
use rustc::ty::{ImplContainer, TraitContainer};
use rustc::ty::{self, AdtKind, Ty, TyCtxt, TypeFoldable, VariantKind};
use rustc::ty::subst::Substs;
use rustc_const_math::ConstInt;
......@@ -47,12 +48,13 @@
use std::cell::Cell;
use std::io;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use std::str;
use rbml::reader;
use rbml;
use rustc_serialize::Decodable;
use rustc_serialize::{Decodable, Decoder, SpecializedDecoder};
use syntax::attr;
use syntax::parse::token;
use syntax::ast;
......@@ -60,6 +62,106 @@
use syntax::print::pprust;
use syntax_pos::{self, Span, BytePos, NO_EXPANSION};
pub struct DecodeContext<'a, 'tcx: 'a> {
pub rbml_r: rbml::reader::Decoder<'a>,
pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
pub cdata: &'a cstore::CrateMetadata,
pub from_id_range: IdRange,
pub to_id_range: IdRange,
// Cache the last used filemap for translating spans as an optimization.
pub last_filemap_index: Cell<usize>,
}
impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
cdata: &'a cstore::CrateMetadata,
from_id_range: IdRange,
doc: rbml::Doc<'a>)
-> DecodeContext<'a, 'tcx> {
// Handle the case of an empty range:
let to_id_range = if from_id_range.empty() {
from_id_range
} else {
let cnt = from_id_range.max - from_id_range.min;
let to_id_min = tcx.sess.reserve_node_ids(cnt);
let to_id_max = to_id_min + cnt;
IdRange { min: to_id_min, max: to_id_max }
};
DecodeContext {
rbml_r: reader::Decoder::new(doc),
cdata: cdata,
tcx: tcx,
from_id_range: from_id_range,
to_id_range: to_id_range,
last_filemap_index: Cell::new(0)
}
}
fn read_ty_encoded<F, R>(&mut self, op: F) -> R
where F: for<'x> FnOnce(&mut TyDecoder<'x,'tcx>) -> R
{
self.read_opaque(|this, doc| {
Ok(op(&mut TyDecoder::with_doc(
this.tcx, this.cdata.cnum, doc,
&mut |d| this.tr_def_id(d))))
}).unwrap()
}
}
impl<'a, 'tcx> Deref for DecodeContext<'a, 'tcx> {
type Target = rbml::reader::Decoder<'a>;
fn deref(&self) -> &Self::Target {
&self.rbml_r
}
}
impl<'a, 'tcx> DerefMut for DecodeContext<'a, 'tcx> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.rbml_r
}
}
// FIXME(#36588) These impls are horribly unsound as they allow
// the caller to pick any lifetime for 'tcx, including 'static,
// by using the unspecialized proxies to them.
impl<'a, 'tcx> SpecializedDecoder<Ty<'tcx>> for DecodeContext<'a, 'tcx> {
fn specialized_decode(&mut self) -> Result<Ty<'tcx>, Self::Error> {
Ok(self.read_ty_encoded(|d| d.parse_ty()))
}
}
impl<'a, 'tcx> SpecializedDecoder<&'tcx Substs<'tcx>> for DecodeContext<'a, 'tcx> {
fn specialized_decode(&mut self) -> Result<&'tcx Substs<'tcx>, Self::Error> {
Ok(self.read_ty_encoded(|d| d.parse_substs()))
}
}
impl<'a, 'tcx> SpecializedDecoder<&'tcx ty::Region> for DecodeContext<'a, 'tcx> {
fn specialized_decode(&mut self) -> Result<&'tcx ty::Region, Self::Error> {
let r = ty::Region::decode(self)?;
Ok(self.tcx.mk_region(r))
}
}
impl<'a, 'tcx> SpecializedDecoder<ty::ClosureSubsts<'tcx>> for DecodeContext<'a, 'tcx> {
fn specialized_decode(&mut self) -> Result<ty::ClosureSubsts<'tcx>, Self::Error> {
Ok(ty::ClosureSubsts {
func_substs: Decodable::decode(this)?,
upvar_tys: this.tcx.mk_type_list(Decodable::decode(this)?)
})
}
}
impl<'a, 'tcx> SpecializedDecoder<ty::AdtDef<'tcx>> for DecodeContext<'a, 'tcx> {
fn specialized_decode(&mut self) -> Result<ty::AdtDef<'tcx>, Self::Error> {
let def_id = DefId::decode(self)?;
let def_id = translate_def_id(self.cdata, def_id);
Ok(self.tcx.lookup_adt_def(def_id))
}
}
pub type Cmd<'a> = &'a CrateMetadata;
impl CrateMetadata {
......@@ -796,17 +898,13 @@ pub fn maybe_get_item_mir<'a, 'tcx>(cdata: Cmd,
let item_doc = cdata.lookup_item(id);
return reader::maybe_get_doc(item_doc, tag_mir as usize).map(|mir_doc| {
let dcx = tls_context::DecodingContext {
crate_metadata: cdata,
tcx: tcx,
};
let mut decoder = reader::Decoder::new(mir_doc);
let mut dcx = DecodeContext::new(tcx, cdata,
IdRange { min: 0, max: 0 },
mir_doc);
let mut mir = tls::enter_decoding_context(&dcx, |_| {
Decodable::decode(&mut decoder)
}).unwrap();
let mut mir = Decodable::decode(&mut dcx).unwrap();
assert!(decoder.position() == mir_doc.end);
assert!(dcx.rbml_r.position() == mir_doc.end);
let mut def_id_and_span_translator = MirDefIdAndSpanTranslator {
crate_metadata: cdata,
......
......@@ -35,7 +35,7 @@
use rustc::session::config::{self, PanicStrategy, CrateTypeRustcMacro};
use rustc::util::nodemap::{FnvHashMap, NodeSet};
use rustc_serialize::{Encodable, SpecializedEncoder, SpecializedDecoder};
use rustc_serialize::{Encodable, SpecializedEncoder};
use std::cell::RefCell;
use std::io::prelude::*;
use std::io::{Cursor, SeekFrom};
......@@ -97,30 +97,6 @@ fn specialized_encode(&mut self, substs: &&'tcx Substs<'tcx>) -> Result<(), Self
}
}
/// FIXME(#31844) This is horribly unsound as it allows the
/// caller to pick any lifetime for 'tcx, including 'static.
impl<'a, 'tcx> SpecializedDecoder<Ty<'tcx>> for ::rbml::reader::Decoder<'a> {
fn specialized_decode(&mut self) -> Result<Ty<'tcx>, Self::Error> {
self.read_opaque(|opaque_decoder, _| {
::middle::cstore::tls::with_decoding_context(|dcx| {
Ok(dcx.decode_ty(opaque_decoder))
})
})
}
}
/// FIXME(#31844) This is horribly unsound as it allows the
/// caller to pick any lifetime for 'tcx, including 'static.
impl<'a, 'tcx> SpecializedDecoder<&'tcx Substs<'tcx>> for ::rbml::reader::Decoder<'a> {
fn specialized_decode(&mut self) -> Result<&'tcx Substs<'tcx>, Self::Error> {
self.read_opaque(|opaque_decoder, _| {
::middle::cstore::tls::with_decoding_context(|dcx| {
Ok(dcx.decode_substs(opaque_decoder))
})
})
}
}
fn encode_name(ecx: &mut EncodeContext, name: Name) {
ecx.wr_tagged_str(tag_paths_data_name, &name.as_str());
}
......
......@@ -61,9 +61,6 @@ pub mod rbml {
pub use rustc::middle;
#[macro_use]
mod macros;
pub mod diagnostics;
pub mod astencode;
......@@ -80,6 +77,5 @@ pub mod rbml {
pub mod index;
pub mod loader;
pub mod macro_import;
pub mod tls_context;
__build_diagnostic_array! { librustc_metadata, DIAGNOSTICS }
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
macro_rules! enum_from_u32 {
($(#[$attr:meta])* pub enum $name:ident {
$($variant:ident = $e:expr,)*
}) => {
$(#[$attr])*
pub enum $name {
$($variant = $e),*
}
impl $name {
pub fn from_u32(u: u32) -> Option<$name> {
$(if u == $name::$variant as u32 {
return Some($name::$variant)
})*
None
}
}
};
($(#[$attr:meta])* pub enum $name:ident {
$($variant:ident,)*
}) => {
$(#[$attr])*
pub enum $name {
$($variant,)*
}
impl $name {
pub fn from_u32(u: u32) -> Option<$name> {
$(if u == $name::$variant as u32 {
return Some($name::$variant)
})*
None
}
}
}
}
......@@ -555,20 +555,6 @@ fn next_doc(&mut self, exp_tag: EbmlEncoderTag) -> DecodeResult<Doc<'doc>> {
Ok(r_doc)
}
fn push_doc<T, F>(&mut self, exp_tag: EbmlEncoderTag, f: F) -> DecodeResult<T>
where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
{
let d = self.next_doc(exp_tag)?;
let old_parent = self.parent;
let old_pos = self.pos;
self.parent = d;
self.pos = d.start;
let r = f(self)?;
self.parent = old_parent;
self.pos = old_pos;
Ok(r)
}
fn _next_sub(&mut self) -> DecodeResult<usize> {
// empty vector/map optimization
if self.parent.is_empty() {
......@@ -670,14 +656,6 @@ fn next_int(&mut self,
Ok(r)
}
pub fn read_opaque<R, F>(&mut self, op: F) -> DecodeResult<R>
where F: FnOnce(&mut opaque::Decoder, Doc) -> DecodeResult<R>
{
let doc = self.next_doc(EsOpaque)?;
let result = op(&mut doc.opaque(), doc)?;
Ok(result)
}
pub fn position(&self) -> usize {
self.pos
}
......@@ -687,7 +665,30 @@ pub fn advance(&mut self, bytes: usize) {
}
}
impl<'doc> serialize::Decoder for Decoder<'doc> {
impl<'doc, 'tcx> ::decoder::DecodeContext<'doc, 'tcx> {
pub fn read_opaque<R, F>(&mut self, op: F) -> DecodeResult<R>
where F: FnOnce(&mut Self, Doc) -> DecodeResult<R>
{
let doc = self.next_doc(EsOpaque)?;
op(self, doc)
}
fn push_doc<T, F>(&mut self, exp_tag: EbmlEncoderTag, f: F) -> DecodeResult<T>
where F: FnOnce(&mut Self) -> DecodeResult<T>
{
let d = self.next_doc(exp_tag)?;
let old_parent = self.parent;
let old_pos = self.pos;
self.parent = d;
self.pos = d.start;
let r = f(self)?;
self.parent = old_parent;
self.pos = old_pos;
Ok(r)
}
}
impl<'doc, 'tcx> serialize::Decoder for ::decoder::DecodeContext<'doc, 'tcx> {
type Error = Error;
fn read_nil(&mut self) -> DecodeResult<()> {
Ok(())
......@@ -757,7 +758,7 @@ fn read_str(&mut self) -> DecodeResult<String> {
// Compound types:
fn read_enum<T, F>(&mut self, name: &str, f: F) -> DecodeResult<T>
where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
where F: FnOnce(&mut Self) -> DecodeResult<T>
{
debug!("read_enum({})", name);
......@@ -775,7 +776,7 @@ fn read_enum<T, F>(&mut self, name: &str, f: F) -> DecodeResult<T>
}
fn read_enum_variant<T, F>(&mut self, _: &[&str], mut f: F) -> DecodeResult<T>
where F: FnMut(&mut Decoder<'doc>, usize) -> DecodeResult<T>
where F: FnMut(&mut Self, usize) -> DecodeResult<T>
{
debug!("read_enum_variant()");
let idx = self._next_sub()?;
......@@ -785,14 +786,14 @@ fn read_enum_variant<T, F>(&mut self, _: &[&str], mut f: F) -> DecodeResult<T>
}
fn read_enum_variant_arg<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T>
where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
where F: FnOnce(&mut Self) -> DecodeResult<T>
{
debug!("read_enum_variant_arg(idx={})", idx);
f(self)
}
fn read_enum_struct_variant<T, F>(&mut self, _: &[&str], mut f: F) -> DecodeResult<T>
where F: FnMut(&mut Decoder<'doc>, usize) -> DecodeResult<T>
where F: FnMut(&mut Self, usize) -> DecodeResult<T>
{
debug!("read_enum_struct_variant()");
let idx = self._next_sub()?;
......@@ -806,28 +807,28 @@ fn read_enum_struct_variant_field<T, F>(&mut self,
idx: usize,
f: F)
-> DecodeResult<T>
where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
where F: FnOnce(&mut Self) -> DecodeResult<T>
{
debug!("read_enum_struct_variant_arg(name={}, idx={})", name, idx);
f(self)
}
fn read_struct<T, F>(&mut self, name: &str, _: usize, f: F) -> DecodeResult<T>
where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
where F: FnOnce(&mut Self) -> DecodeResult<T>
{
debug!("read_struct(name={})", name);
f(self)
}
fn read_struct_field<T, F>(&mut self, name: &str, idx: usize, f: F) -> DecodeResult<T>
where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
where F: FnOnce(&mut Self) -> DecodeResult<T>
{
debug!("read_struct_field(name={}, idx={})", name, idx);
f(self)
}
fn read_tuple<T, F>(&mut self, tuple_len: usize, f: F) -> DecodeResult<T>
where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
where F: FnOnce(&mut Self) -> DecodeResult<T>
{
debug!("read_tuple()");
self.read_seq(move |d, len| {
......@@ -843,28 +844,28 @@ fn read_tuple<T, F>(&mut self, tuple_len: usize, f: F) -> DecodeResult<T>
}
fn read_tuple_arg<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T>
where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
where F: FnOnce(&mut Self) -> DecodeResult<T>
{
debug!("read_tuple_arg(idx={})", idx);
self.read_seq_elt(idx, f)
}
fn read_tuple_struct<T, F>(&mut self, name: &str, len: usize, f: F) -> DecodeResult<T>
where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
where F: FnOnce(&mut Self) -> DecodeResult<T>
{
debug!("read_tuple_struct(name={})", name);
self.read_tuple(len, f)
}
fn read_tuple_struct_arg<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T>
where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
where F: FnOnce(&mut Self) -> DecodeResult<T>
{
debug!("read_tuple_struct_arg(idx={})", idx);
self.read_tuple_arg(idx, f)
}
fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T>
where F: FnMut(&mut Decoder<'doc>, bool) -> DecodeResult<T>
where F: FnMut(&mut Self, bool) -> DecodeResult<T>
{
debug!("read_option()");
self.read_enum("Option", move |this| {
......@@ -879,7 +880,7 @@ fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T>
}
fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T>
where F: FnOnce(&mut Decoder<'doc>, usize) -> DecodeResult<T>
where F: FnOnce(&mut Self, usize) -> DecodeResult<T>
{
debug!("read_seq()");
self.push_doc(EsVec, move |d| {
......@@ -890,14 +891,14 @@ fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T>
}
fn read_seq_elt<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T>
where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
where F: FnOnce(&mut Self) -> DecodeResult<T>
{
debug!("read_seq_elt(idx={})", idx);
self.push_doc(EsVecElt, f)
}
fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T>
where F: FnOnce(&mut Decoder<'doc>, usize) -> DecodeResult<T>
where F: FnOnce(&mut Self, usize) -> DecodeResult<T>
{
debug!("read_map()");
self.push_doc(EsMap, move |d| {
......@@ -908,14 +909,14 @@ fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T>
}
fn read_map_elt_key<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T>
where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
where F: FnOnce(&mut Self) -> DecodeResult<T>
{
debug!("read_map_elt_key(idx={})", idx);
self.push_doc(EsMapKey, f)
}
fn read_map_elt_val<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T>
where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>
where F: FnOnce(&mut Self) -> DecodeResult<T>
{
debug!("read_map_elt_val(idx={})", idx);
self.push_doc(EsMapVal, f)
......
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// This module provides implementations for the thread-local encoding and
// decoding context traits in rustc::middle::cstore::tls.
use rbml::opaque::Decoder as OpaqueDecoder;
use rustc::middle::cstore::tls;
use rustc::hir::def_id::DefId;
use rustc::ty::subst::Substs;
use rustc::ty::{Ty, TyCtxt};
use decoder::{self, Cmd};
use tydecode::TyDecoder;
pub struct DecodingContext<'a, 'tcx: 'a> {
pub crate_metadata: Cmd<'a>,
pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
}
impl<'a, 'tcx: 'a> tls::DecodingContext<'tcx> for DecodingContext<'a, 'tcx> {
fn tcx<'s>(&'s self) -> TyCtxt<'s, 'tcx, 'tcx> {
self.tcx
}
fn decode_ty(&self, decoder: &mut OpaqueDecoder) -> Ty<'tcx> {
let def_id_convert = &mut |did| {
decoder::translate_def_id(self.crate_metadata, did)
};
let starting_position = decoder.position();
let mut ty_decoder = TyDecoder::new(
self.crate_metadata.data.as_slice(),
self.crate_metadata.cnum,
starting_position,
self.tcx,
def_id_convert);
let ty = ty_decoder.parse_ty();
let end_position = ty_decoder.position();
// We can just reuse the tydecode implementation for parsing types, but
// we have to make sure to leave the rbml reader at the position just
// after the type.
decoder.advance(end_position - starting_position);
ty
}
fn decode_substs(&self, decoder: &mut OpaqueDecoder) -> &'tcx Substs<'tcx> {
let def_id_convert = &mut |did| {
decoder::translate_def_id(self.crate_metadata, did)
};
let starting_position = decoder.position();
let mut ty_decoder = TyDecoder::new(
self.crate_metadata.data.as_slice(),
self.crate_metadata.cnum,
starting_position,
self.tcx,
def_id_convert);
let substs = ty_decoder.parse_substs();
let end_position = ty_decoder.position();
decoder.advance(end_position - starting_position);
substs
}
fn translate_def_id(&self, def_id: DefId) -> DefId {
decoder::translate_def_id(self.crate_metadata, def_id)
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册