rustc_metadata: go only through rustc_serialize in astencode.

This commit is contained in:
Eduard Burtescu 2016-08-31 14:00:29 +03:00
parent 91e7239db4
commit fc363cb482
70 changed files with 605 additions and 1212 deletions

View file

@ -8,12 +8,59 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use middle::cstore::LOCAL_CRATE;
use ty;
use syntax::ast::CrateNum;
use rustc_data_structures::indexed_vec::Idx;
use serialize;
use std::fmt;
use std::u32;
#[derive(Clone, Copy, Eq, Ord, PartialOrd, PartialEq, RustcEncodable, Hash, Debug)]
pub struct CrateNum(u32);
impl Idx for CrateNum {
fn new(value: usize) -> Self {
assert!(value < (u32::MAX) as usize);
CrateNum(value as u32)
}
fn index(self) -> usize {
self.0 as usize
}
}
/// Item definitions in the currently-compiled crate would have the CrateNum
/// LOCAL_CRATE in their DefId.
pub const LOCAL_CRATE: CrateNum = CrateNum(0);
impl CrateNum {
pub fn new(x: usize) -> CrateNum {
assert!(x < (u32::MAX as usize));
CrateNum(x as u32)
}
pub fn from_u32(x: u32) -> CrateNum {
CrateNum(x)
}
pub fn as_usize(&self) -> usize {
self.0 as usize
}
pub fn as_u32(&self) -> u32 {
self.0
}
}
impl fmt::Display for CrateNum {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl serialize::UseSpecializedDecodable for CrateNum {}
/// A DefIndex is an index into the hir-map for a crate, identifying a
/// particular definition. It should really be considered an interned
/// shorthand for a particular DefPath.
@ -46,8 +93,7 @@ pub const CRATE_DEF_INDEX: DefIndex = DefIndex(0);
/// A DefId identifies a particular *definition*, by combining a crate
/// index and a def index.
#[derive(Clone, Eq, Ord, PartialOrd, PartialEq, RustcEncodable,
RustcDecodable, Hash, Copy)]
#[derive(Clone, Eq, Ord, PartialOrd, PartialEq, RustcEncodable, RustcDecodable, Hash, Copy)]
pub struct DefId {
pub krate: CrateNum,
pub index: DefIndex,

View file

@ -881,8 +881,8 @@ pub struct IdRange {
impl IdRange {
pub fn max() -> IdRange {
IdRange {
min: u32::MAX,
max: u32::MIN,
min: NodeId::from_u32(u32::MAX),
max: NodeId::from_u32(u32::MIN),
}
}
@ -896,7 +896,7 @@ impl IdRange {
pub fn add(&mut self, id: NodeId) {
self.min = cmp::min(self.min, id);
self.max = cmp::max(self.max, id + 1);
self.max = cmp::max(self.max, NodeId::from_u32(id.as_u32() + 1));
}
}

View file

@ -61,7 +61,7 @@ use syntax_pos::Span;
pub struct LoweringContext<'a> {
crate_root: Option<&'static str>,
// Use to assign ids to hir nodes that do not directly correspond to an ast node
sess: Option<&'a Session>,
sess: &'a Session,
// As we walk the AST we must keep track of the current 'parent' def id (in
// the form of a DefIndex) so that if we create a new node which introduces
// a definition, then we can properly create the def id.
@ -101,22 +101,13 @@ pub fn lower_crate(sess: &Session,
} else {
Some("std")
},
sess: Some(sess),
sess: sess,
parent_def: None,
resolver: resolver,
}.lower_crate(krate)
}
impl<'a> LoweringContext<'a> {
pub fn testing_context(resolver: &'a mut Resolver) -> Self {
LoweringContext {
crate_root: None,
sess: None,
parent_def: None,
resolver: resolver,
}
}
fn lower_crate(&mut self, c: &Crate) -> hir::Crate {
struct ItemLowerer<'lcx, 'interner: 'lcx> {
items: BTreeMap<NodeId, hir::Item>,
@ -147,12 +138,11 @@ impl<'a> LoweringContext<'a> {
}
fn next_id(&self) -> NodeId {
self.sess.map(Session::next_node_id).unwrap_or(0)
self.sess.next_node_id()
}
fn diagnostic(&self) -> &errors::Handler {
self.sess.map(Session::diagnostic)
.unwrap_or_else(|| panic!("this lowerer cannot emit diagnostics"))
self.sess.diagnostic()
}
fn str_to_ident(&self, s: &'static str) -> Name {

View file

@ -63,10 +63,10 @@ impl<'ast> NodeCollector<'ast> {
fn insert_entry(&mut self, id: NodeId, entry: MapEntry<'ast>) {
debug!("ast_map: {:?} => {:?}", id, entry);
let len = self.map.len();
if id as usize >= len {
self.map.extend(repeat(NotPresent).take(id as usize - len + 1));
if id.as_usize() >= len {
self.map.extend(repeat(NotPresent).take(id.as_usize() - len + 1));
}
self.map[id as usize] = entry;
self.map[id.as_usize()] = entry;
}
fn insert(&mut self, id: NodeId, node: Node<'ast>) {

View file

@ -8,8 +8,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use middle::cstore::LOCAL_CRATE;
use hir::def_id::{DefId, DefIndex};
use hir::def_id::{CrateNum, DefId, DefIndex, LOCAL_CRATE};
use hir::map::def_collector::DefCollector;
use rustc_data_structures::fnv::FnvHashMap;
use std::fmt::Write;
@ -70,7 +69,7 @@ pub struct DefPath {
pub data: Vec<DisambiguatedDefPathData>,
/// what krate root is this path relative to?
pub krate: ast::CrateNum,
pub krate: CrateNum,
}
impl DefPath {
@ -78,7 +77,7 @@ impl DefPath {
self.krate == LOCAL_CRATE
}
pub fn make<FN>(start_krate: ast::CrateNum,
pub fn make<FN>(start_krate: CrateNum,
start_index: DefIndex,
mut get_key: FN) -> DefPath
where FN: FnMut(DefIndex) -> DefKey

View file

@ -22,17 +22,15 @@ use middle::cstore::InlinedItem as II;
use hir::def_id::{CRATE_DEF_INDEX, DefId, DefIndex};
use syntax::abi::Abi;
use syntax::ast::{self, Name, NodeId, DUMMY_NODE_ID, };
use syntax::ast::{self, Name, NodeId, CRATE_NODE_ID};
use syntax::codemap::Spanned;
use syntax_pos::Span;
use hir::*;
use hir::fold::Folder;
use hir::print as pprust;
use arena::TypedArena;
use std::cell::RefCell;
use std::cmp;
use std::io;
use std::mem;
@ -240,7 +238,7 @@ impl<'ast> Map<'ast> {
let mut id = id0;
if !self.is_inlined_node_id(id) {
loop {
match map[id as usize] {
match map[id.as_usize()] {
EntryItem(_, item) => {
let def_id = self.local_def_id(item.id);
// NB ^~~~~~~
@ -295,7 +293,7 @@ impl<'ast> Map<'ast> {
// reading from an inlined def-id is really a read out of
// the metadata from which we loaded the item.
loop {
match map[id as usize] {
match map[id.as_usize()] {
EntryItem(p, _) |
EntryForeignItem(p, _) |
EntryTraitItem(p, _) |
@ -373,7 +371,7 @@ impl<'ast> Map<'ast> {
}
fn find_entry(&self, id: NodeId) -> Option<MapEntry<'ast>> {
self.map.borrow().get(id as usize).cloned()
self.map.borrow().get(id.as_usize()).cloned()
}
pub fn krate(&self) -> &'ast Crate {
@ -456,8 +454,8 @@ impl<'ast> Map<'ast> {
let mut id = start_id;
loop {
let parent_node = self.get_parent_node(id);
if parent_node == 0 {
return Ok(0);
if parent_node == CRATE_NODE_ID {
return Ok(CRATE_NODE_ID);
}
if parent_node == id {
return Err(id);
@ -680,7 +678,7 @@ impl<'ast> Map<'ast> {
map: self,
item_name: parts.last().unwrap(),
in_which: &parts[..parts.len() - 1],
idx: 0,
idx: CRATE_NODE_ID,
}
}
@ -801,10 +799,10 @@ impl<'a, 'ast> Iterator for NodesMatchingSuffix<'a, 'ast> {
fn next(&mut self) -> Option<NodeId> {
loop {
let idx = self.idx;
if idx as usize >= self.map.entry_count() {
if idx.as_usize() >= self.map.entry_count() {
return None;
}
self.idx += 1;
self.idx = NodeId::from_u32(self.idx.as_u32() + 1);
let name = match self.map.find_entry(idx) {
Some(EntryItem(_, n)) => n.name(),
Some(EntryForeignItem(_, n))=> n.name(),
@ -832,57 +830,6 @@ impl Named for Variant_ { fn name(&self) -> Name { self.name } }
impl Named for TraitItem { fn name(&self) -> Name { self.name } }
impl Named for ImplItem { fn name(&self) -> Name { self.name } }
pub trait FoldOps {
fn new_id(&self, id: NodeId) -> NodeId {
id
}
fn new_def_id(&self, def_id: DefId) -> DefId {
def_id
}
fn new_span(&self, span: Span) -> Span {
span
}
}
/// A Folder that updates IDs and Span's according to fold_ops.
pub struct IdAndSpanUpdater<F> {
fold_ops: F,
min_id_assigned: NodeId,
max_id_assigned: NodeId,
}
impl<F: FoldOps> IdAndSpanUpdater<F> {
pub fn new(fold_ops: F) -> IdAndSpanUpdater<F> {
IdAndSpanUpdater {
fold_ops: fold_ops,
min_id_assigned: ::std::u32::MAX,
max_id_assigned: ::std::u32::MIN,
}
}
pub fn id_range(&self) -> intravisit::IdRange {
intravisit::IdRange {
min: self.min_id_assigned,
max: self.max_id_assigned + 1,
}
}
}
impl<F: FoldOps> Folder for IdAndSpanUpdater<F> {
fn new_id(&mut self, id: NodeId) -> NodeId {
let id = self.fold_ops.new_id(id);
self.min_id_assigned = cmp::min(self.min_id_assigned, id);
self.max_id_assigned = cmp::max(self.max_id_assigned, id);
id
}
fn new_span(&mut self, span: Span) -> Span {
self.fold_ops.new_span(span)
}
}
pub fn map_crate<'ast>(forest: &'ast mut Forest,
definitions: Definitions)
-> Map<'ast> {
@ -906,7 +853,7 @@ pub fn map_crate<'ast>(forest: &'ast mut Forest,
entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
}
let local_node_id_watermark = map.len() as NodeId;
let local_node_id_watermark = NodeId::new(map.len());
let local_def_id_watermark = definitions.len();
Map {
@ -921,36 +868,15 @@ pub fn map_crate<'ast>(forest: &'ast mut Forest,
/// Used for items loaded from external crate that are being inlined into this
/// crate.
pub fn map_decoded_item<'ast, F: FoldOps>(map: &Map<'ast>,
parent_def_path: DefPath,
parent_def_id: DefId,
ii: InlinedItem,
fold_ops: F)
-> &'ast InlinedItem {
pub fn map_decoded_item<'ast>(map: &Map<'ast>,
parent_def_path: DefPath,
parent_def_id: DefId,
ii: InlinedItem,
ii_parent_id: NodeId)
-> &'ast InlinedItem {
let _ignore = map.forest.dep_graph.in_ignore();
let mut fld = IdAndSpanUpdater::new(fold_ops);
let ii = match ii {
II::Item(d, i) => II::Item(fld.fold_ops.new_def_id(d),
i.map(|i| fld.fold_item(i))),
II::TraitItem(d, ti) => {
II::TraitItem(fld.fold_ops.new_def_id(d),
ti.map(|ti| fld.fold_trait_item(ti)))
}
II::ImplItem(d, ii) => {
II::ImplItem(fld.fold_ops.new_def_id(d),
ii.map(|ii| fld.fold_impl_item(ii)))
}
};
let ii = map.forest.inlined_items.alloc(ii);
let ii_parent_id = fld.new_id(DUMMY_NODE_ID);
// Assert that the ii_parent_id is the last NodeId in our reserved range
assert!(ii_parent_id == fld.max_id_assigned);
// Assert that we did not violate the invariant that all inlined HIR items
// have NodeIds greater than or equal to `local_node_id_watermark`
assert!(fld.min_id_assigned >= map.local_node_id_watermark);
let defs = &mut *map.definitions.borrow_mut();
let mut def_collector = DefCollector::extend(ii_parent_id,

View file

@ -63,9 +63,8 @@ pub fn maybe_print_constraints_for<'a, 'gcx, 'tcx>(
return;
}
let requested_node: Option<ast::NodeId> = env::var("RUST_REGION_GRAPH_NODE")
.ok()
.and_then(|s| s.parse().ok());
let requested_node = env::var("RUST_REGION_GRAPH_NODE")
.ok().and_then(|s| s.parse().map(ast::NodeId::new).ok());
if requested_node.is_some() && requested_node != Some(subject_node) {
return;

View file

@ -23,7 +23,7 @@
// probably get a better home if someone can find one.
use hir::def::{self, Def};
use hir::def_id::{DefId, DefIndex};
use hir::def_id::{CrateNum, DefId, DefIndex};
use hir::map as hir_map;
use hir::map::definitions::DefKey;
use hir::svh::Svh;
@ -64,7 +64,7 @@ pub struct LinkMeta {
pub struct CrateSource {
pub dylib: Option<(PathBuf, PathKind)>,
pub rlib: Option<(PathBuf, PathKind)>,
pub cnum: ast::CrateNum,
pub cnum: CrateNum,
}
#[derive(Copy, Debug, PartialEq, Clone)]
@ -101,17 +101,13 @@ pub enum InlinedItem {
}
/// A borrowed version of `hir::InlinedItem`.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, Hash, Debug)]
pub enum InlinedItemRef<'a> {
Item(DefId, &'a hir::Item),
TraitItem(DefId, &'a hir::TraitItem),
ImplItem(DefId, &'a hir::ImplItem)
}
/// Item definitions in the currently-compiled crate would have the CrateNum
/// LOCAL_CRATE in their DefId.
pub const LOCAL_CRATE: ast::CrateNum = 0;
#[derive(Copy, Clone)]
pub struct ChildItem {
pub def: DefLike,
@ -203,35 +199,35 @@ pub trait CrateStore<'tcx> {
fn is_typedef(&self, did: DefId) -> bool;
// crate metadata
fn dylib_dependency_formats(&self, cnum: ast::CrateNum)
-> Vec<(ast::CrateNum, LinkagePreference)>;
fn lang_items(&self, cnum: ast::CrateNum) -> Vec<(DefIndex, usize)>;
fn missing_lang_items(&self, cnum: ast::CrateNum) -> Vec<lang_items::LangItem>;
fn is_staged_api(&self, cnum: ast::CrateNum) -> bool;
fn is_explicitly_linked(&self, cnum: ast::CrateNum) -> bool;
fn is_allocator(&self, cnum: ast::CrateNum) -> bool;
fn is_panic_runtime(&self, cnum: ast::CrateNum) -> bool;
fn is_compiler_builtins(&self, cnum: ast::CrateNum) -> bool;
fn panic_strategy(&self, cnum: ast::CrateNum) -> PanicStrategy;
fn extern_crate(&self, cnum: ast::CrateNum) -> Option<ExternCrate>;
fn crate_attrs(&self, cnum: ast::CrateNum) -> Vec<ast::Attribute>;
fn dylib_dependency_formats(&self, cnum: CrateNum)
-> Vec<(CrateNum, LinkagePreference)>;
fn lang_items(&self, cnum: CrateNum) -> Vec<(DefIndex, usize)>;
fn missing_lang_items(&self, cnum: CrateNum) -> Vec<lang_items::LangItem>;
fn is_staged_api(&self, cnum: CrateNum) -> bool;
fn is_explicitly_linked(&self, cnum: CrateNum) -> bool;
fn is_allocator(&self, cnum: CrateNum) -> bool;
fn is_panic_runtime(&self, cnum: CrateNum) -> bool;
fn is_compiler_builtins(&self, cnum: CrateNum) -> bool;
fn panic_strategy(&self, cnum: CrateNum) -> PanicStrategy;
fn extern_crate(&self, cnum: CrateNum) -> Option<ExternCrate>;
fn crate_attrs(&self, cnum: CrateNum) -> Vec<ast::Attribute>;
/// The name of the crate as it is referred to in source code of the current
/// crate.
fn crate_name(&self, cnum: ast::CrateNum) -> InternedString;
fn crate_name(&self, cnum: CrateNum) -> InternedString;
/// The name of the crate as it is stored in the crate's metadata.
fn original_crate_name(&self, cnum: ast::CrateNum) -> InternedString;
fn crate_hash(&self, cnum: ast::CrateNum) -> Svh;
fn crate_disambiguator(&self, cnum: ast::CrateNum) -> InternedString;
fn crate_struct_field_attrs(&self, cnum: ast::CrateNum)
fn original_crate_name(&self, cnum: CrateNum) -> InternedString;
fn crate_hash(&self, cnum: CrateNum) -> Svh;
fn crate_disambiguator(&self, cnum: CrateNum) -> InternedString;
fn crate_struct_field_attrs(&self, cnum: CrateNum)
-> FnvHashMap<DefId, Vec<ast::Attribute>>;
fn plugin_registrar_fn(&self, cnum: ast::CrateNum) -> Option<DefId>;
fn native_libraries(&self, cnum: ast::CrateNum) -> Vec<(NativeLibraryKind, String)>;
fn reachable_ids(&self, cnum: ast::CrateNum) -> Vec<DefId>;
fn is_no_builtins(&self, cnum: ast::CrateNum) -> bool;
fn plugin_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>;
fn native_libraries(&self, cnum: CrateNum) -> Vec<(NativeLibraryKind, String)>;
fn reachable_ids(&self, cnum: CrateNum) -> Vec<DefId>;
fn is_no_builtins(&self, cnum: CrateNum) -> bool;
// resolve
fn def_index_for_def_key(&self,
cnum: ast::CrateNum,
cnum: CrateNum,
def: DefKey)
-> Option<DefIndex>;
fn def_key(&self, def: DefId) -> hir_map::DefKey;
@ -241,7 +237,7 @@ pub trait CrateStore<'tcx> {
fn tuple_struct_definition_if_ctor(&self, did: DefId) -> Option<DefId>;
fn struct_field_names(&self, def: DefId) -> Vec<ast::Name>;
fn item_children(&self, did: DefId) -> Vec<ChildItem>;
fn crate_top_level_items(&self, cnum: ast::CrateNum) -> Vec<ChildItem>;
fn crate_top_level_items(&self, cnum: CrateNum) -> Vec<ChildItem>;
// misc. metadata
fn maybe_get_item_ast<'a>(&'tcx self, tcx: TyCtxt<'a, 'tcx, 'tcx>, def: DefId)
@ -255,7 +251,7 @@ pub trait CrateStore<'tcx> {
// This is basically a 1-based range of ints, which is a little
// silly - I may fix that.
fn crates(&self) -> Vec<ast::CrateNum>;
fn crates(&self) -> Vec<CrateNum>;
fn used_libraries(&self) -> Vec<(String, NativeLibraryKind)>;
fn used_link_args(&self) -> Vec<String>;
@ -267,9 +263,9 @@ pub trait CrateStore<'tcx> {
ty: Ty<'tcx>,
def_id_to_string: for<'b> fn(TyCtxt<'b, 'tcx, 'tcx>, DefId) -> String)
-> Vec<u8>;
fn used_crates(&self, prefer: LinkagePreference) -> Vec<(ast::CrateNum, Option<PathBuf>)>;
fn used_crate_source(&self, cnum: ast::CrateNum) -> CrateSource;
fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<ast::CrateNum>;
fn used_crates(&self, prefer: LinkagePreference) -> Vec<(CrateNum, Option<PathBuf>)>;
fn used_crate_source(&self, cnum: CrateNum) -> CrateSource;
fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<CrateNum>;
fn encode_metadata<'a>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
reexports: &def::ExportMap,
link_meta: &LinkMeta,
@ -360,7 +356,7 @@ impl<'tcx> CrateStore<'tcx> for DummyCrateStore {
fn trait_item_def_ids(&self, def: DefId)
-> Vec<ty::ImplOrTraitItemId> { bug!("trait_item_def_ids") }
fn def_index_for_def_key(&self,
cnum: ast::CrateNum,
cnum: CrateNum,
def: DefKey)
-> Option<DefIndex> {
None
@ -396,40 +392,40 @@ impl<'tcx> CrateStore<'tcx> for DummyCrateStore {
fn is_typedef(&self, did: DefId) -> bool { bug!("is_typedef") }
// crate metadata
fn dylib_dependency_formats(&self, cnum: ast::CrateNum)
-> Vec<(ast::CrateNum, LinkagePreference)>
fn dylib_dependency_formats(&self, cnum: CrateNum)
-> Vec<(CrateNum, LinkagePreference)>
{ bug!("dylib_dependency_formats") }
fn lang_items(&self, cnum: ast::CrateNum) -> Vec<(DefIndex, usize)>
fn lang_items(&self, cnum: CrateNum) -> Vec<(DefIndex, usize)>
{ bug!("lang_items") }
fn missing_lang_items(&self, cnum: ast::CrateNum) -> Vec<lang_items::LangItem>
fn missing_lang_items(&self, cnum: CrateNum) -> Vec<lang_items::LangItem>
{ bug!("missing_lang_items") }
fn is_staged_api(&self, cnum: ast::CrateNum) -> bool { bug!("is_staged_api") }
fn is_explicitly_linked(&self, cnum: ast::CrateNum) -> bool { bug!("is_explicitly_linked") }
fn is_allocator(&self, cnum: ast::CrateNum) -> bool { bug!("is_allocator") }
fn is_panic_runtime(&self, cnum: ast::CrateNum) -> bool { bug!("is_panic_runtime") }
fn is_compiler_builtins(&self, cnum: ast::CrateNum) -> bool { bug!("is_compiler_builtins") }
fn panic_strategy(&self, cnum: ast::CrateNum) -> PanicStrategy {
fn is_staged_api(&self, cnum: CrateNum) -> bool { bug!("is_staged_api") }
fn is_explicitly_linked(&self, cnum: CrateNum) -> bool { bug!("is_explicitly_linked") }
fn is_allocator(&self, cnum: CrateNum) -> bool { bug!("is_allocator") }
fn is_panic_runtime(&self, cnum: CrateNum) -> bool { bug!("is_panic_runtime") }
fn is_compiler_builtins(&self, cnum: CrateNum) -> bool { bug!("is_compiler_builtins") }
fn panic_strategy(&self, cnum: CrateNum) -> PanicStrategy {
bug!("panic_strategy")
}
fn extern_crate(&self, cnum: ast::CrateNum) -> Option<ExternCrate> { bug!("extern_crate") }
fn crate_attrs(&self, cnum: ast::CrateNum) -> Vec<ast::Attribute>
fn extern_crate(&self, cnum: CrateNum) -> Option<ExternCrate> { bug!("extern_crate") }
fn crate_attrs(&self, cnum: CrateNum) -> Vec<ast::Attribute>
{ bug!("crate_attrs") }
fn crate_name(&self, cnum: ast::CrateNum) -> InternedString { bug!("crate_name") }
fn original_crate_name(&self, cnum: ast::CrateNum) -> InternedString {
fn crate_name(&self, cnum: CrateNum) -> InternedString { bug!("crate_name") }
fn original_crate_name(&self, cnum: CrateNum) -> InternedString {
bug!("original_crate_name")
}
fn crate_hash(&self, cnum: ast::CrateNum) -> Svh { bug!("crate_hash") }
fn crate_disambiguator(&self, cnum: ast::CrateNum)
fn crate_hash(&self, cnum: CrateNum) -> Svh { bug!("crate_hash") }
fn crate_disambiguator(&self, cnum: CrateNum)
-> InternedString { bug!("crate_disambiguator") }
fn crate_struct_field_attrs(&self, cnum: ast::CrateNum)
fn crate_struct_field_attrs(&self, cnum: CrateNum)
-> FnvHashMap<DefId, Vec<ast::Attribute>>
{ bug!("crate_struct_field_attrs") }
fn plugin_registrar_fn(&self, cnum: ast::CrateNum) -> Option<DefId>
fn plugin_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>
{ bug!("plugin_registrar_fn") }
fn native_libraries(&self, cnum: ast::CrateNum) -> Vec<(NativeLibraryKind, String)>
fn native_libraries(&self, cnum: CrateNum) -> Vec<(NativeLibraryKind, String)>
{ bug!("native_libraries") }
fn reachable_ids(&self, cnum: ast::CrateNum) -> Vec<DefId> { bug!("reachable_ids") }
fn is_no_builtins(&self, cnum: ast::CrateNum) -> bool { bug!("is_no_builtins") }
fn reachable_ids(&self, cnum: CrateNum) -> Vec<DefId> { bug!("reachable_ids") }
fn is_no_builtins(&self, cnum: CrateNum) -> bool { bug!("is_no_builtins") }
// resolve
fn def_key(&self, def: DefId) -> hir_map::DefKey { bug!("def_key") }
@ -443,7 +439,7 @@ impl<'tcx> CrateStore<'tcx> for DummyCrateStore {
{ bug!("tuple_struct_definition_if_ctor") }
fn struct_field_names(&self, def: DefId) -> Vec<ast::Name> { bug!("struct_field_names") }
fn item_children(&self, did: DefId) -> Vec<ChildItem> { bug!("item_children") }
fn crate_top_level_items(&self, cnum: ast::CrateNum) -> Vec<ChildItem>
fn crate_top_level_items(&self, cnum: CrateNum) -> Vec<ChildItem>
{ bug!("crate_top_level_items") }
// misc. metadata
@ -466,7 +462,7 @@ impl<'tcx> CrateStore<'tcx> for DummyCrateStore {
// This is basically a 1-based range of ints, which is a little
// silly - I may fix that.
fn crates(&self) -> Vec<ast::CrateNum> { vec![] }
fn crates(&self) -> Vec<CrateNum> { vec![] }
fn used_libraries(&self) -> Vec<(String, NativeLibraryKind)> { vec![] }
fn used_link_args(&self) -> Vec<String> { vec![] }
@ -480,10 +476,10 @@ impl<'tcx> CrateStore<'tcx> for DummyCrateStore {
-> Vec<u8> {
bug!("encode_type")
}
fn used_crates(&self, prefer: LinkagePreference) -> Vec<(ast::CrateNum, Option<PathBuf>)>
fn used_crates(&self, prefer: LinkagePreference) -> Vec<(CrateNum, Option<PathBuf>)>
{ vec![] }
fn used_crate_source(&self, cnum: ast::CrateNum) -> CrateSource { bug!("used_crate_source") }
fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<ast::CrateNum> { None }
fn used_crate_source(&self, cnum: CrateNum) -> CrateSource { bug!("used_crate_source") }
fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<CrateNum> { None }
fn encode_metadata<'a>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
reexports: &def::ExportMap,
link_meta: &LinkMeta,

View file

@ -112,10 +112,10 @@ impl<'a, 'tcx, O:DataFlowOperator> pprust::PpAnn for DataFlowContext<'a, 'tcx, O
ps: &mut pprust::State,
node: pprust::AnnNode) -> io::Result<()> {
let id = match node {
pprust::NodeName(_) => 0,
pprust::NodeName(_) => ast::CRATE_NODE_ID,
pprust::NodeExpr(expr) => expr.id,
pprust::NodeBlock(blk) => blk.id,
pprust::NodeItem(_) | pprust::NodeSubItem(_) => 0,
pprust::NodeItem(_) | pprust::NodeSubItem(_) => ast::CRATE_NODE_ID,
pprust::NodePat(pat) => pat.id
};

View file

@ -61,7 +61,7 @@
//! Additionally, the algorithm is geared towards finding *any* solution rather
//! than finding a number of solutions (there are normally quite a few).
use syntax::ast;
use hir::def_id::CrateNum;
use session;
use session::config::{self, PanicStrategy};
@ -169,9 +169,9 @@ fn calculate_type(sess: &session::Session,
}
// Collect what we've got so far in the return vector.
let last_crate = sess.cstore.crates().len() as ast::CrateNum;
let last_crate = sess.cstore.crates().len();
let mut ret = (1..last_crate+1).map(|cnum| {
match formats.get(&cnum) {
match formats.get(&CrateNum::new(cnum)) {
Some(&RequireDynamic) => Linkage::Dynamic,
Some(&RequireStatic) => Linkage::IncludedFromDylib,
None => Linkage::NotLinked,
@ -191,7 +191,7 @@ fn calculate_type(sess: &session::Session,
assert!(src.rlib.is_some());
info!("adding staticlib: {}", sess.cstore.crate_name(cnum));
add_library(sess, cnum, RequireStatic, &mut formats);
ret[cnum as usize - 1] = Linkage::Static;
ret[cnum.as_usize() - 1] = Linkage::Static;
}
}
@ -213,7 +213,7 @@ fn calculate_type(sess: &session::Session,
// For situations like this, we perform one last pass over the dependencies,
// making sure that everything is available in the requested format.
for (cnum, kind) in ret.iter().enumerate() {
let cnum = (cnum + 1) as ast::CrateNum;
let cnum = CrateNum::new(cnum + 1);
let src = sess.cstore.used_crate_source(cnum);
match *kind {
Linkage::NotLinked |
@ -237,9 +237,9 @@ fn calculate_type(sess: &session::Session,
}
fn add_library(sess: &session::Session,
cnum: ast::CrateNum,
cnum: CrateNum,
link: LinkagePreference,
m: &mut FnvHashMap<ast::CrateNum, LinkagePreference>) {
m: &mut FnvHashMap<CrateNum, LinkagePreference>) {
match m.get(&cnum) {
Some(&link2) => {
// If the linkages differ, then we'd have two copies of the library
@ -269,9 +269,9 @@ fn attempt_static(sess: &session::Session) -> Option<DependencyList> {
// All crates are available in an rlib format, so we're just going to link
// everything in explicitly so long as it's actually required.
let last_crate = sess.cstore.crates().len() as ast::CrateNum;
let last_crate = sess.cstore.crates().len();
let mut ret = (1..last_crate+1).map(|cnum| {
if sess.cstore.is_explicitly_linked(cnum) {
if sess.cstore.is_explicitly_linked(CrateNum::new(cnum)) {
Linkage::Static
} else {
Linkage::NotLinked
@ -298,11 +298,11 @@ fn attempt_static(sess: &session::Session) -> Option<DependencyList> {
// a required dependency) in one of the session's field. If this field is not
// set then this compilation doesn't actually need the dependency and we can
// also skip this step entirely.
fn activate_injected_dep(injected: Option<ast::CrateNum>,
fn activate_injected_dep(injected: Option<CrateNum>,
list: &mut DependencyList,
replaces_injected: &Fn(ast::CrateNum) -> bool) {
replaces_injected: &Fn(CrateNum) -> bool) {
for (i, slot) in list.iter().enumerate() {
let cnum = (i + 1) as ast::CrateNum;
let cnum = CrateNum::new(i + 1);
if !replaces_injected(cnum) {
continue
}
@ -311,7 +311,7 @@ fn activate_injected_dep(injected: Option<ast::CrateNum>,
}
}
if let Some(injected) = injected {
let idx = injected as usize - 1;
let idx = injected.as_usize() - 1;
assert_eq!(list[idx], Linkage::NotLinked);
list[idx] = Linkage::Static;
}
@ -329,7 +329,7 @@ fn verify_ok(sess: &session::Session, list: &[Linkage]) {
if let Linkage::NotLinked = *linkage {
continue
}
let cnum = (i + 1) as ast::CrateNum;
let cnum = CrateNum::new(i + 1);
if sess.cstore.is_allocator(cnum) {
if let Some(prev) = allocator {
let prev_name = sess.cstore.crate_name(prev);
@ -380,7 +380,7 @@ fn verify_ok(sess: &session::Session, list: &[Linkage]) {
if desired_strategy == PanicStrategy::Abort {
continue
}
let cnum = (i + 1) as ast::CrateNum;
let cnum = CrateNum::new(i + 1);
let found_strategy = sess.cstore.panic_strategy(cnum);
if desired_strategy == found_strategy {
continue

View file

@ -17,9 +17,8 @@ use dep_graph::DepNode;
use hir::map as hir_map;
use session::Session;
use lint;
use middle::cstore::LOCAL_CRATE;
use hir::def::Def;
use hir::def_id::{CRATE_DEF_INDEX, DefId, DefIndex};
use hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId, DefIndex, LOCAL_CRATE};
use ty::{self, TyCtxt, AdtKind};
use middle::privacy::AccessLevels;
use syntax::parse::token::InternedString;
@ -103,7 +102,7 @@ pub struct Index<'tcx> {
depr_map: DefIdMap<Option<DeprecationEntry>>,
/// Maps for each crate whether it is part of the staged API.
staged_api: FnvHashMap<ast::CrateNum, bool>
staged_api: FnvHashMap<CrateNum, bool>
}
// A private tree-walker for producing an Index.

View file

@ -9,7 +9,7 @@
// except according to those terms.
use dep_graph::DepGraph;
use hir::def_id::DefIndex;
use hir::def_id::{CrateNum, DefIndex};
use hir::svh::Svh;
use lint;
use middle::cstore::CrateStore;
@ -93,8 +93,8 @@ pub struct Session {
/// The metadata::creader module may inject an allocator/panic_runtime
/// dependency if it didn't already find one, and this tracks what was
/// injected.
pub injected_allocator: Cell<Option<ast::CrateNum>>,
pub injected_panic_runtime: Cell<Option<ast::CrateNum>>,
pub injected_allocator: Cell<Option<CrateNum>>,
pub injected_panic_runtime: Cell<Option<CrateNum>>,
/// Map from imported macro spans (which consist of
/// the localized span for the macro body) to the
@ -266,11 +266,13 @@ impl Session {
}
lints.insert(id, vec!((lint_id, sp, msg)));
}
pub fn reserve_node_ids(&self, count: ast::NodeId) -> ast::NodeId {
pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
let id = self.next_node_id.get();
match id.checked_add(count) {
Some(next) => self.next_node_id.set(next),
match id.as_usize().checked_add(count) {
Some(next) => {
self.next_node_id.set(ast::NodeId::new(next));
}
None => bug!("Input too large, ran out of node ids!")
}
@ -545,7 +547,7 @@ pub fn build_session_(sopts: config::Options,
crate_disambiguator: RefCell::new(token::intern("").as_str()),
features: RefCell::new(feature_gate::Features::new()),
recursion_limit: Cell::new(64),
next_node_id: Cell::new(1),
next_node_id: Cell::new(NodeId::new(1)),
injected_allocator: Cell::new(None),
injected_panic_runtime: Cell::new(None),
imported_macro_spans: RefCell::new(HashMap::new()),

View file

@ -12,8 +12,7 @@
use super::{SelectionContext, Obligation, ObligationCause};
use middle::cstore::LOCAL_CRATE;
use hir::def_id::DefId;
use hir::def_id::{DefId, LOCAL_CRATE};
use ty::{self, Ty, TyCtxt};
use infer::{InferCtxt, TypeOrigin};
use syntax_pos::DUMMY_SP;

View file

@ -571,7 +571,7 @@ impl<'tcx> ObligationCause<'tcx> {
}
pub fn dummy() -> ObligationCause<'tcx> {
ObligationCause { span: DUMMY_SP, body_id: 0, code: MiscObligation }
ObligationCause { span: DUMMY_SP, body_id: ast::CRATE_NODE_ID, code: MiscObligation }
}
}

View file

@ -19,7 +19,7 @@ use syntax_pos::Span;
use hir;
#[derive(Copy, Clone)]
#[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
pub enum AutoAdjustment<'tcx> {
AdjustNeverToAny(Ty<'tcx>), // go from ! to any type
AdjustReifyFnPointer, // go from a fn-item type to a fn-pointer type
@ -90,7 +90,7 @@ pub enum AutoAdjustment<'tcx> {
/// unsize: Some(Box<[i32]>),
/// }
/// ```
#[derive(Copy, Clone)]
#[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
pub struct AutoDerefRef<'tcx> {
/// Step 1. Apply a number of dereferences, producing an lvalue.
pub autoderefs: usize,
@ -122,7 +122,7 @@ impl<'tcx> AutoDerefRef<'tcx> {
}
#[derive(Copy, Clone, PartialEq, Debug)]
#[derive(Copy, Clone, PartialEq, Debug, RustcEncodable, RustcDecodable)]
pub enum AutoRef<'tcx> {
/// Convert from T to &T.
AutoPtr(&'tcx ty::Region, hir::Mutability),

View file

@ -13,10 +13,9 @@
use dep_graph::{DepGraph, DepTrackingMap};
use session::Session;
use middle;
use middle::cstore::LOCAL_CRATE;
use hir::TraitMap;
use hir::def::DefMap;
use hir::def_id::{DefId, DefIndex};
use hir::def_id::{CrateNum, DefId, DefIndex, LOCAL_CRATE};
use hir::map as ast_map;
use hir::map::{DefKey, DefPath, DefPathData, DisambiguatedDefPathData};
use middle::free_region::FreeRegionMap;
@ -512,7 +511,7 @@ impl<'tcx> GlobalCtxt<'tcx> {
}
impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
pub fn crate_name(self, cnum: ast::CrateNum) -> token::InternedString {
pub fn crate_name(self, cnum: CrateNum) -> token::InternedString {
if cnum == LOCAL_CRATE {
self.crate_name.clone()
} else {
@ -520,7 +519,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
}
}
pub fn crate_disambiguator(self, cnum: ast::CrateNum) -> token::InternedString {
pub fn crate_disambiguator(self, cnum: CrateNum) -> token::InternedString {
if cnum == LOCAL_CRATE {
self.sess.local_crate_disambiguator()
} else {
@ -533,7 +532,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
/// relative to `krate`.
///
/// Returns `None` if there is no `DefIndex` with that key.
pub fn def_index_for_def_key(self, krate: ast::CrateNum, key: DefKey)
pub fn def_index_for_def_key(self, krate: CrateNum, key: DefKey)
-> Option<DefIndex> {
if krate == LOCAL_CRATE {
self.map.def_index_for_def_key(key)

View file

@ -9,8 +9,7 @@
// except according to those terms.
use hir::map::DefPathData;
use middle::cstore::LOCAL_CRATE;
use hir::def_id::{DefId, CRATE_DEF_INDEX};
use hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
use ty::{self, Ty, TyCtxt};
use syntax::ast;
use syntax::parse::token;
@ -67,7 +66,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
/// Returns the "path" to a particular crate. This can proceed in
/// various ways, depending on the `root_mode` of the `buffer`.
/// (See `RootMode` enum for more details.)
pub fn push_krate_path<T>(self, buffer: &mut T, cnum: ast::CrateNum)
pub fn push_krate_path<T>(self, buffer: &mut T, cnum: CrateNum)
where T: ItemPathBuffer
{
match *buffer.root_mode() {

View file

@ -367,7 +367,7 @@ impl Integer {
/// signed discriminant range and #[repr] attribute.
/// N.B.: u64 values above i64::MAX will be treated as signed, but
/// that shouldn't affect anything, other than maybe debuginfo.
pub fn repr_discr(tcx: TyCtxt, hint: attr::ReprAttr, min: i64, max: i64)
pub fn repr_discr(tcx: TyCtxt, ty: Ty, hint: attr::ReprAttr, min: i64, max: i64)
-> (Integer, bool) {
// Theoretically, negative values could be larger in unsigned representation
// than the unsigned representation of the signed minimum. However, if there
@ -377,11 +377,12 @@ impl Integer {
let signed_fit = cmp::max(Integer::fit_signed(min), Integer::fit_signed(max));
let at_least = match hint {
attr::ReprInt(span, ity) => {
attr::ReprInt(ity) => {
let discr = Integer::from_attr(&tcx.data_layout, ity);
let fit = if ity.is_signed() { signed_fit } else { unsigned_fit };
if discr < fit {
span_bug!(span, "representation hint insufficient for discriminant range")
bug!("Integer::repr_discr: `#[repr]` hint too small for \
discriminant range of enum `{}", ty)
}
return (discr, ity.is_signed());
}
@ -397,10 +398,10 @@ impl Integer {
}
attr::ReprAny => I8,
attr::ReprPacked => {
bug!("Integer::repr_discr: found #[repr(packed)] on an enum");
bug!("Integer::repr_discr: found #[repr(packed)] on enum `{}", ty);
}
attr::ReprSimd => {
bug!("Integer::repr_discr: found #[repr(simd)] on an enum");
bug!("Integer::repr_discr: found #[repr(simd)] on enum `{}", ty);
}
};
@ -962,7 +963,7 @@ impl<'a, 'gcx, 'tcx> Layout {
if x > max { max = x; }
}
let (discr, signed) = Integer::repr_discr(tcx, hint, min, max);
let (discr, signed) = Integer::repr_discr(tcx, ty, hint, min, max);
return success(CEnum {
discr: discr,
signed: signed,
@ -1052,7 +1053,7 @@ impl<'a, 'gcx, 'tcx> Layout {
// The general case.
let discr_max = (variants.len() - 1) as i64;
assert!(discr_max >= 0);
let (min_ity, _) = Integer::repr_discr(tcx, hint, 0, discr_max);
let (min_ity, _) = Integer::repr_discr(tcx, ty, hint, 0, discr_max);
let mut align = dl.aggregate_align;
let mut size = Size::from_bytes(0);

View file

@ -21,9 +21,8 @@ pub use self::fold::TypeFoldable;
use dep_graph::{self, DepNode};
use hir::map as ast_map;
use middle;
use middle::cstore::LOCAL_CRATE;
use hir::def::{Def, PathResolution, ExportMap};
use hir::def_id::DefId;
use hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem, FnOnceTraitLangItem};
use middle::region::{CodeExtent, ROOT_CODE_EXTENT};
use traits;
@ -42,7 +41,7 @@ use std::iter;
use std::rc::Rc;
use std::slice;
use std::vec::IntoIter;
use syntax::ast::{self, CrateNum, Name, NodeId};
use syntax::ast::{self, Name, NodeId};
use syntax::attr;
use syntax::parse::token::InternedString;
use syntax_pos::{DUMMY_SP, Span};
@ -425,7 +424,7 @@ pub enum Variance {
Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
}
#[derive(Clone, Copy, Debug)]
#[derive(Clone, Copy, Debug, RustcDecodable, RustcEncodable)]
pub struct MethodCallee<'tcx> {
/// Impl method ID, for inherent methods, or trait method ID, otherwise.
pub def_id: DefId,
@ -627,7 +626,7 @@ pub enum BorrowKind {
/// Information describing the capture of an upvar. This is computed
/// during `typeck`, specifically by `regionck`.
#[derive(PartialEq, Clone, Debug, Copy)]
#[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable)]
pub enum UpvarCapture<'tcx> {
/// Upvar is captured by value. This is always true when the
/// closure is labeled `move`, but can also be true in other cases
@ -638,7 +637,7 @@ pub enum UpvarCapture<'tcx> {
ByRef(UpvarBorrow<'tcx>),
}
#[derive(PartialEq, Clone, Copy)]
#[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable)]
pub struct UpvarBorrow<'tcx> {
/// The kind of borrow: by-ref upvars have access to shared
/// immutable borrows, which are not part of the normal language
@ -1940,7 +1939,7 @@ impl<'a, 'gcx, 'tcx, 'container> FieldDefData<'tcx, 'container> {
/// Records the substitutions used to translate the polytype for an
/// item into the monotype of an item reference.
#[derive(Clone)]
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct ItemSubsts<'tcx> {
pub substs: &'tcx Substs<'tcx>,
}

View file

@ -240,7 +240,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
pub fn enum_repr_type(self, opt_hint: Option<&attr::ReprAttr>) -> attr::IntType {
match opt_hint {
// Feed in the given type
Some(&attr::ReprInt(_, int_t)) => int_t,
Some(&attr::ReprInt(int_t)) => int_t,
// ... but provide sensible default if none provided
//
// NB. Historically `fn enum_variants` generate i64 here, while

View file

@ -46,7 +46,6 @@ extern crate serialize;
#[macro_use] extern crate log;
pub mod tempdir;
pub mod rpath;
pub mod sha2;
pub mod target;
pub mod slice;

View file

@ -460,7 +460,7 @@ fn const_val_to_expr(value: &ConstVal) -> P<hir::Expr> {
_ => bug!()
};
P(hir::Expr {
id: 0,
id: DUMMY_NODE_ID,
node: hir::ExprLit(P(Spanned { node: node, span: DUMMY_SP })),
span: DUMMY_SP,
attrs: ast::ThinVec::new(),
@ -625,7 +625,7 @@ fn construct_witness<'a,'tcx>(cx: &MatchCheckCtxt<'a,'tcx>, ctor: &Constructor,
};
P(hir::Pat {
id: 0,
id: DUMMY_NODE_ID,
node: pat,
span: DUMMY_SP
})

View file

@ -539,6 +539,7 @@ impl FromStr for UserIdentifiedItem {
type Err = ();
fn from_str(s: &str) -> Result<UserIdentifiedItem, ()> {
Ok(s.parse()
.map(ast::NodeId::new)
.map(ItemViaNode)
.unwrap_or_else(|_| ItemViaPath(s.split("::").map(|s| s.to_string()).collect())))
}

View file

@ -166,16 +166,17 @@ impl<'a, 'gcx, 'tcx> Env<'a, 'gcx, 'tcx> {
pub fn create_simple_region_hierarchy(&self) {
// creates a region hierarchy where 1 is root, 10 and 11 are
// children of 1, etc
let node = ast::NodeId::from_u32;
let dscope = self.infcx
.tcx
.region_maps
.intern_code_extent(CodeExtentData::DestructionScope(1),
.intern_code_extent(CodeExtentData::DestructionScope(node(1)),
region::ROOT_CODE_EXTENT);
self.create_region_hierarchy(&RH {
id: 1,
sub: &[RH { id: 10, sub: &[] }, RH { id: 11, sub: &[] }],
},
dscope);
id: node(1),
sub: &[RH { id: node(10), sub: &[] }, RH { id: node(11), sub: &[] }],
}, dscope);
}
#[allow(dead_code)] // this seems like it could be useful, even if we don't use it now
@ -315,8 +316,8 @@ impl<'a, 'gcx, 'tcx> Env<'a, 'gcx, 'tcx> {
self.infcx.tcx.mk_imm_ref(r, self.tcx().types.isize)
}
pub fn t_rptr_scope(&self, id: ast::NodeId) -> Ty<'tcx> {
let r = ty::ReScope(self.tcx().region_maps.node_extent(id));
pub fn t_rptr_scope(&self, id: u32) -> Ty<'tcx> {
let r = ty::ReScope(self.tcx().region_maps.node_extent(ast::NodeId::from_u32(id)));
self.infcx.tcx.mk_imm_ref(self.infcx.tcx.mk_region(r), self.tcx().types.isize)
}
@ -327,8 +328,8 @@ impl<'a, 'gcx, 'tcx> Env<'a, 'gcx, 'tcx> {
}))
}
pub fn t_rptr_free(&self, nid: ast::NodeId, id: u32) -> Ty<'tcx> {
let r = self.re_free(nid, id);
pub fn t_rptr_free(&self, nid: u32, id: u32) -> Ty<'tcx> {
let r = self.re_free(ast::NodeId::from_u32(nid), id);
self.infcx.tcx.mk_imm_ref(r, self.tcx().types.isize)
}

View file

@ -15,13 +15,11 @@
use rustc::dep_graph::DepNode;
use rustc::hir::map::DefPath;
use rustc::hir::def_id::DefId;
use rustc::middle::cstore::LOCAL_CRATE;
use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
use rustc::ty::TyCtxt;
use rustc::util::nodemap::DefIdMap;
use std::fmt::{self, Debug};
use std::iter::once;
use syntax::ast;
/// Index into the DefIdDirectory
#[derive(Copy, Clone, Debug, PartialOrd, Ord, Hash, PartialEq, Eq,
@ -43,7 +41,7 @@ pub struct DefIdDirectory {
#[derive(Debug, RustcEncodable, RustcDecodable)]
pub struct CrateInfo {
krate: ast::CrateNum,
krate: CrateNum,
name: String,
disambiguator: String,
}
@ -53,7 +51,7 @@ impl DefIdDirectory {
DefIdDirectory { paths: vec![], krates: krates }
}
fn max_current_crate(&self, tcx: TyCtxt) -> ast::CrateNum {
fn max_current_crate(&self, tcx: TyCtxt) -> CrateNum {
tcx.sess.cstore.crates()
.into_iter()
.max()
@ -72,8 +70,8 @@ impl DefIdDirectory {
pub fn krate_still_valid(&self,
tcx: TyCtxt,
max_current_crate: ast::CrateNum,
krate: ast::CrateNum) -> bool {
max_current_crate: CrateNum,
krate: CrateNum) -> bool {
// Check that the crate-number still matches. For now, if it
// doesn't, just return None. We could do better, such as
// finding the new number.
@ -81,7 +79,7 @@ impl DefIdDirectory {
if krate > max_current_crate {
false
} else {
let old_info = &self.krates[krate as usize];
let old_info = &self.krates[krate.as_usize()];
assert_eq!(old_info.krate, krate);
let old_name: &str = &old_info.name;
let old_disambiguator: &str = &old_info.disambiguator;
@ -101,7 +99,7 @@ impl DefIdDirectory {
} else {
debug!("crate {} changed from {:?} to {:?}/{:?}",
path.krate,
self.krates[path.krate as usize],
self.krates[path.krate.as_usize()],
tcx.crate_name(path.krate),
tcx.crate_disambiguator(path.krate));
None

View file

@ -114,8 +114,8 @@
//! unsupported file system and emit a warning in that case. This is not yet
//! implemented.
use rustc::hir::def_id::{CrateNum, LOCAL_CRATE};
use rustc::hir::svh::Svh;
use rustc::middle::cstore::LOCAL_CRATE;
use rustc::session::Session;
use rustc::ty::TyCtxt;
use rustc::util::fs as fs_util;
@ -129,7 +129,6 @@ use std::mem;
use std::path::{Path, PathBuf};
use std::time::{UNIX_EPOCH, SystemTime, Duration};
use std::__rand::{thread_rng, Rng};
use syntax::ast;
const LOCK_FILE_EXT: &'static str = ".lock";
const DEP_GRAPH_FILENAME: &'static str = "dep-graph.bin";
@ -580,7 +579,7 @@ fn string_to_timestamp(s: &str) -> Result<SystemTime, ()> {
Ok(UNIX_EPOCH + duration)
}
fn crate_path_tcx(tcx: TyCtxt, cnum: ast::CrateNum) -> PathBuf {
fn crate_path_tcx(tcx: TyCtxt, cnum: CrateNum) -> PathBuf {
crate_path(tcx.sess, &tcx.crate_name(cnum), &tcx.crate_disambiguator(cnum))
}
@ -592,7 +591,7 @@ fn crate_path_tcx(tcx: TyCtxt, cnum: ast::CrateNum) -> PathBuf {
/// crate's (name, disambiguator) pair. The metadata hashes are only valid for
/// the exact version of the binary we are reading from now (i.e. the hashes
/// are part of the dependency graph of a specific compilation session).
pub fn find_metadata_hashes_for(tcx: TyCtxt, cnum: ast::CrateNum) -> Option<PathBuf> {
pub fn find_metadata_hashes_for(tcx: TyCtxt, cnum: CrateNum) -> Option<PathBuf> {
let crate_directory = crate_path_tcx(tcx, cnum);
if !crate_directory.exists() {

View file

@ -11,7 +11,7 @@
use rbml::Error;
use rbml::opaque::Decoder;
use rustc::dep_graph::DepNode;
use rustc::hir::def_id::DefId;
use rustc::hir::def_id::{CrateNum, DefId};
use rustc::hir::svh::Svh;
use rustc::ty::TyCtxt;
use rustc_data_structures::fnv::FnvHashMap;
@ -19,7 +19,6 @@ use rustc_data_structures::flock;
use rustc_serialize::Decodable;
use std::io::{ErrorKind, Read};
use std::fs::File;
use syntax::ast;
use IncrementalHashesMap;
use super::data::*;
@ -29,7 +28,7 @@ pub struct HashContext<'a, 'tcx: 'a> {
pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
incremental_hashes_map: &'a IncrementalHashesMap,
item_metadata_hashes: FnvHashMap<DefId, u64>,
crate_hashes: FnvHashMap<ast::CrateNum, Svh>,
crate_hashes: FnvHashMap<CrateNum, Svh>,
}
impl<'a, 'tcx> HashContext<'a, 'tcx> {
@ -121,7 +120,7 @@ impl<'a, 'tcx> HashContext<'a, 'tcx> {
}
}
fn load_data(&mut self, cnum: ast::CrateNum) {
fn load_data(&mut self, cnum: CrateNum) {
debug!("load_data(cnum={})", cnum);
let svh = self.tcx.sess.cstore.crate_hash(cnum);
@ -187,7 +186,7 @@ impl<'a, 'tcx> HashContext<'a, 'tcx> {
}
fn load_from_data(&mut self,
cnum: ast::CrateNum,
cnum: CrateNum,
data: &[u8],
expected_svh: Svh) -> Result<(), Error> {
debug!("load_from_data(cnum={})", cnum);

View file

@ -92,7 +92,7 @@ pub struct TypeLimits {
impl TypeLimits {
pub fn new() -> TypeLimits {
TypeLimits {
negated_expr_id: !0,
negated_expr_id: ast::DUMMY_NODE_ID,
}
}
}

View file

@ -9,98 +9,57 @@
// except according to those terms.
#![allow(non_camel_case_types)]
// FIXME: remove this after snapshot, and Results are handled
#![allow(unused_must_use)]
use rustc::hir::map as ast_map;
use rustc::hir;
use rustc::hir::fold;
use rustc::hir::fold::Folder;
use rustc::hir::intravisit::{Visitor, IdRangeComputingVisitor, IdRange};
use common as c;
use cstore;
use decoder;
use decoder::DecodeContext;
use encoder::EncodeContext;
use middle::cstore::{InlinedItem, InlinedItemRef};
use rustc::ty::adjustment;
use rustc::ty::cast;
use middle::const_qualif::ConstQualif;
use rustc::hir::def::{self, Def};
use rustc::hir::def;
use rustc::hir::def_id::DefId;
use rustc::ty::{self, Ty, TyCtxt};
use rustc::ty::{self, TyCtxt};
use syntax::ast;
use syntax::ptr::P;
use syntax_pos;
use std::io::SeekFrom;
use std::io::prelude::*;
use rbml::reader;
use rbml;
use rustc_serialize::{Decodable, Decoder, DecoderHelpers};
use rustc_serialize::{Encodable, EncoderHelpers};
trait tr {
fn tr(&self, dcx: &DecodeContext) -> Self;
}
use rustc_serialize::{Decodable, Encodable};
// ______________________________________________________________________
// Top-level methods.
pub fn encode_inlined_item(ecx: &mut EncodeContext, ii: InlinedItemRef) {
let id = match ii {
InlinedItemRef::Item(_, i) => i.id,
InlinedItemRef::TraitItem(_, ti) => ti.id,
InlinedItemRef::ImplItem(_, ii) => ii.id,
};
debug!("> Encoding inlined item: {} ({:?})",
ecx.tcx.node_path_str(id),
ecx.writer.seek(SeekFrom::Current(0)));
ecx.tag(c::tag_ast, |ecx| {
ecx.tag(c::tag_id_range, |ecx| {
let mut visitor = IdRangeComputingVisitor::new();
match ii {
InlinedItemRef::Item(_, i) => visitor.visit_item(i),
InlinedItemRef::TraitItem(_, ti) => visitor.visit_trait_item(ti),
InlinedItemRef::ImplItem(_, ii) => visitor.visit_impl_item(ii)
}
visitor.result().encode(&mut ecx.opaque()).unwrap()
});
// Folding could be avoided with a smarter encoder.
let (ii, expected_id_range) = simplify_ast(ii);
let id_range = inlined_item_id_range(&ii);
assert_eq!(expected_id_range, id_range);
ecx.tag(c::tag_tree, |ecx| ii.encode(ecx).unwrap());
ecx.start_tag(c::tag_ast);
ecx.start_tag(c::tag_id_range);
id_range.encode(&mut ecx.opaque());
ecx.end_tag();
ecx.start_tag(c::tag_tree);
ii.encode(ecx);
ecx.end_tag();
encode_side_tables_for_ii(ecx, &ii);
ecx.end_tag();
debug!("< Encoded inlined fn: {} ({:?})",
ecx.tcx.node_path_str(id),
ecx.writer.seek(SeekFrom::Current(0)));
}
impl<'a, 'b, 'tcx> ast_map::FoldOps for &'a DecodeContext<'b, 'tcx> {
fn new_id(&self, id: ast::NodeId) -> ast::NodeId {
if id == ast::DUMMY_NODE_ID {
// Used by ast_map to map the NodeInlinedParent.
self.tcx.sess.next_node_id()
} else {
self.tr_id(id)
}
}
fn new_def_id(&self, def_id: DefId) -> DefId {
self.tr_def_id(def_id)
}
fn new_span(&self, span: syntax_pos::Span) -> syntax_pos::Span {
self.tr_span(span)
}
ecx.tag(c::tag_table, |ecx| {
let mut visitor = SideTableEncodingIdVisitor {
ecx: ecx
};
match ii {
InlinedItemRef::Item(_, i) => visitor.visit_item(i),
InlinedItemRef::TraitItem(_, ti) => visitor.visit_trait_item(ti),
InlinedItemRef::ImplItem(_, ii) => visitor.visit_impl_item(ii)
}
});
});
}
/// Decodes an item from its AST in the cdata's metadata and adds it to the
@ -113,8 +72,13 @@ pub fn decode_inlined_item<'a, 'tcx>(cdata: &cstore::CrateMetadata,
orig_did: DefId)
-> &'tcx InlinedItem {
debug!("> Decoding inlined fn: {:?}", tcx.item_path_str(orig_did));
let id_range_doc = ast_doc.get(c::tag_id_range);
let from_id_range = IdRange::decode(&mut id_range_doc.opaque()).unwrap();
let from_id_range = {
let decoder = &mut ast_doc.get(c::tag_id_range).opaque();
IdRange {
min: ast::NodeId::from_u32(u32::decode(decoder).unwrap()),
max: ast::NodeId::from_u32(u32::decode(decoder).unwrap())
}
};
let mut dcx = DecodeContext::new(tcx, cdata, from_id_range,
ast_doc.get(c::tag_tree));
let ii = InlinedItem::decode(&mut dcx).unwrap();
@ -123,7 +87,7 @@ pub fn decode_inlined_item<'a, 'tcx>(cdata: &cstore::CrateMetadata,
parent_def_path,
parent_did,
ii,
&dcx);
tcx.sess.next_node_id());
let item_node_id = match ii {
&InlinedItem::Item(_, ref i) => i.id,
@ -138,376 +102,18 @@ pub fn decode_inlined_item<'a, 'tcx>(cdata: &cstore::CrateMetadata,
ii
}
// ______________________________________________________________________
// Enumerating the IDs which appear in an AST
impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
/// Translates an internal id, meaning a node id that is known to refer to some part of the
/// item currently being inlined, such as a local variable or argument. All naked node-ids
/// that appear in types have this property, since if something might refer to an external item
/// we would use a def-id to allow for the possibility that the item resides in another crate.
pub fn tr_id(&self, id: ast::NodeId) -> ast::NodeId {
// from_id_range should be non-empty
assert!(!self.from_id_range.empty());
// Make sure that translating the NodeId will actually yield a
// meaningful result
assert!(self.from_id_range.contains(id));
// Use wrapping arithmetic because otherwise it introduces control flow.
// Maybe we should just have the control flow? -- aatch
(id.wrapping_sub(self.from_id_range.min).wrapping_add(self.to_id_range.min))
}
/// Translates an EXTERNAL def-id, converting the crate number from the one used in the encoded
/// data to the current crate numbers.. By external, I mean that it be translated to a
/// reference to the item in its original crate, as opposed to being translated to a reference
/// to the inlined version of the item. This is typically, but not always, what you want,
/// because most def-ids refer to external things like types or other fns that may or may not
/// be inlined. Note that even when the inlined function is referencing itself recursively, we
/// would want `tr_def_id` for that reference--- conceptually the function calls the original,
/// non-inlined version, and trans deals with linking that recursive call to the inlined copy.
pub fn tr_def_id(&self, did: DefId) -> DefId {
decoder::translate_def_id(self.cdata, did)
}
/// Translates a `Span` from an extern crate to the corresponding `Span`
/// within the local crate's codemap.
pub fn tr_span(&self, span: syntax_pos::Span) -> syntax_pos::Span {
decoder::translate_span(self.cdata,
self.tcx.sess.codemap(),
&self.last_filemap_index,
span)
}
}
impl tr for DefId {
fn tr(&self, dcx: &DecodeContext) -> DefId {
dcx.tr_def_id(*self)
}
}
impl tr for Option<DefId> {
fn tr(&self, dcx: &DecodeContext) -> Option<DefId> {
self.map(|d| dcx.tr_def_id(d))
}
}
impl tr for syntax_pos::Span {
fn tr(&self, dcx: &DecodeContext) -> syntax_pos::Span {
dcx.tr_span(*self)
}
}
// ______________________________________________________________________
// Encoding and decoding the AST itself
//
// When decoding, we have to renumber the AST so that the node ids that
// appear within are disjoint from the node ids in our existing ASTs.
// We also have to adjust the spans: for now we just insert a dummy span,
// but eventually we should add entries to the local codemap as required.
struct NestedItemsDropper {
id_range: IdRange
}
impl Folder for NestedItemsDropper {
// The unit tests below run on HIR with NodeIds not properly assigned. That
// causes an integer overflow. So we just don't track the id_range when
// building the unit tests.
#[cfg(not(test))]
fn new_id(&mut self, id: ast::NodeId) -> ast::NodeId {
// Record the range of NodeIds we are visiting, so we can do a sanity
// check later
self.id_range.add(id);
id
}
fn fold_block(&mut self, blk: P<hir::Block>) -> P<hir::Block> {
blk.and_then(|hir::Block {id, stmts, expr, rules, span, ..}| {
let stmts_sans_items = stmts.into_iter().filter_map(|stmt| {
let use_stmt = match stmt.node {
hir::StmtExpr(..) | hir::StmtSemi(..) => true,
hir::StmtDecl(ref decl, _) => {
match decl.node {
hir::DeclLocal(_) => true,
hir::DeclItem(_) => false,
}
}
};
if use_stmt {
Some(stmt)
} else {
None
}
}).collect();
let blk_sans_items = P(hir::Block {
stmts: stmts_sans_items,
expr: expr,
id: id,
rules: rules,
span: span,
});
fold::noop_fold_block(blk_sans_items, self)
})
}
}
// Produces a simplified copy of the AST which does not include things
// that we do not need to or do not want to export. For example, we
// do not include any nested items: if these nested items are to be
// inlined, their AST will be exported separately (this only makes
// sense because, in Rust, nested items are independent except for
// their visibility).
//
// As it happens, trans relies on the fact that we do not export
// nested items, as otherwise it would get confused when translating
// inlined items.
fn simplify_ast(ii: InlinedItemRef) -> (InlinedItem, IdRange) {
let mut fld = NestedItemsDropper {
id_range: IdRange::max()
};
let ii = match ii {
// HACK we're not dropping items.
InlinedItemRef::Item(d, i) => {
InlinedItem::Item(d, P(fold::noop_fold_item(i.clone(), &mut fld)))
}
InlinedItemRef::TraitItem(d, ti) => {
InlinedItem::TraitItem(d, P(fold::noop_fold_trait_item(ti.clone(), &mut fld)))
}
InlinedItemRef::ImplItem(d, ii) => {
InlinedItem::ImplItem(d, P(fold::noop_fold_impl_item(ii.clone(), &mut fld)))
}
};
(ii, fld.id_range)
}
// ______________________________________________________________________
// Encoding and decoding of ast::def
impl tr for Def {
fn tr(&self, dcx: &DecodeContext) -> Def {
match *self {
Def::Fn(did) => Def::Fn(did.tr(dcx)),
Def::Method(did) => Def::Method(did.tr(dcx)),
Def::SelfTy(opt_did, impl_id) => {
// Since the impl_id will never lie within the reserved range of
// imported NodeIds, it does not make sense to translate it.
// The result would not make any sense within the importing crate.
// We also don't allow for impl items to be inlined (just their
// members), so even if we had a DefId here, we wouldn't be able
// to do much with it.
// So, we set the id to DUMMY_NODE_ID. That way we make it
// explicit that this is no usable NodeId.
Def::SelfTy(opt_did.map(|did| did.tr(dcx)),
impl_id.map(|_| ast::DUMMY_NODE_ID))
}
Def::Mod(did) => { Def::Mod(did.tr(dcx)) }
Def::ForeignMod(did) => { Def::ForeignMod(did.tr(dcx)) }
Def::Static(did, m) => { Def::Static(did.tr(dcx), m) }
Def::Const(did) => { Def::Const(did.tr(dcx)) }
Def::AssociatedConst(did) => Def::AssociatedConst(did.tr(dcx)),
Def::Local(_, nid) => {
let nid = dcx.tr_id(nid);
let did = dcx.tcx.map.local_def_id(nid);
Def::Local(did, nid)
}
Def::Variant(e_did, v_did) => Def::Variant(e_did.tr(dcx), v_did.tr(dcx)),
Def::Trait(did) => Def::Trait(did.tr(dcx)),
Def::Enum(did) => Def::Enum(did.tr(dcx)),
Def::TyAlias(did) => Def::TyAlias(did.tr(dcx)),
Def::AssociatedTy(trait_did, did) =>
Def::AssociatedTy(trait_did.tr(dcx), did.tr(dcx)),
Def::PrimTy(p) => Def::PrimTy(p),
Def::TyParam(did) => Def::TyParam(did.tr(dcx)),
Def::Upvar(_, nid1, index, nid2) => {
let nid1 = dcx.tr_id(nid1);
let nid2 = dcx.tr_id(nid2);
let did1 = dcx.tcx.map.local_def_id(nid1);
Def::Upvar(did1, nid1, index, nid2)
}
Def::Struct(did) => Def::Struct(did.tr(dcx)),
Def::Union(did) => Def::Union(did.tr(dcx)),
Def::Label(nid) => Def::Label(dcx.tr_id(nid)),
Def::Err => Def::Err,
}
}
}
// ______________________________________________________________________
// Encoding and decoding of freevar information
impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
fn read_freevar_entry(&mut self) -> hir::Freevar {
hir::Freevar::decode(self).unwrap().tr(self)
}
}
impl tr for hir::Freevar {
fn tr(&self, dcx: &DecodeContext) -> hir::Freevar {
hir::Freevar {
def: self.def.tr(dcx),
span: self.span.tr(dcx),
}
}
}
// ______________________________________________________________________
// Encoding and decoding of MethodCallee
impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
fn encode_method_callee(&mut self,
autoderef: u32,
method: &ty::MethodCallee<'tcx>) {
use rustc_serialize::Encoder;
self.emit_struct("MethodCallee", 4, |this| {
this.emit_struct_field("autoderef", 0, |this| {
autoderef.encode(this)
});
this.emit_struct_field("def_id", 1, |this| {
method.def_id.encode(this)
});
this.emit_struct_field("ty", 2, |this| {
method.ty.encode(this)
});
this.emit_struct_field("substs", 3, |this| {
method.substs.encode(this)
})
}).unwrap();
}
}
impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
fn read_method_callee(&mut self) -> (u32, ty::MethodCallee<'tcx>) {
self.read_struct("MethodCallee", 4, |this| {
let autoderef = this.read_struct_field("autoderef", 0,
Decodable::decode).unwrap();
Ok((autoderef, ty::MethodCallee {
def_id: this.read_struct_field("def_id", 1, |this| {
DefId::decode(this).map(|d| d.tr(this))
}).unwrap(),
ty: this.read_struct_field("ty", 2, |this| {
Ty::decode(this)
}).unwrap(),
substs: this.read_struct_field("substs", 3, |this| {
Decodable::decode(this)
}).unwrap()
}))
}).unwrap()
}
}
// ______________________________________________________________________
// Encoding and decoding the side tables
impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
fn emit_upvar_capture(&mut self, capture: &ty::UpvarCapture<'tcx>) {
use rustc_serialize::Encoder;
self.emit_enum("UpvarCapture", |this| {
match *capture {
ty::UpvarCapture::ByValue => {
this.emit_enum_variant("ByValue", 1, 0, |_| Ok(()))
}
ty::UpvarCapture::ByRef(ty::UpvarBorrow { kind, region }) => {
this.emit_enum_variant("ByRef", 2, 0, |this| {
this.emit_enum_variant_arg(0, |this| kind.encode(this));
this.emit_enum_variant_arg(1, |this| region.encode(this))
})
}
}
}).unwrap()
}
fn emit_auto_adjustment(&mut self, adj: &adjustment::AutoAdjustment<'tcx>) {
use rustc_serialize::Encoder;
self.emit_enum("AutoAdjustment", |this| {
match *adj {
adjustment::AdjustReifyFnPointer => {
this.emit_enum_variant("AdjustReifyFnPointer", 1, 0, |_| Ok(()))
}
adjustment::AdjustUnsafeFnPointer => {
this.emit_enum_variant("AdjustUnsafeFnPointer", 2, 0, |_| {
Ok(())
})
}
adjustment::AdjustMutToConstPointer => {
this.emit_enum_variant("AdjustMutToConstPointer", 3, 0, |_| {
Ok(())
})
}
adjustment::AdjustDerefRef(ref auto_deref_ref) => {
this.emit_enum_variant("AdjustDerefRef", 4, 2, |this| {
this.emit_enum_variant_arg(0,
|this| Ok(this.emit_auto_deref_ref(auto_deref_ref)))
})
}
adjustment::AdjustNeverToAny(ref ty) => {
this.emit_enum_variant("AdjustNeverToAny", 5, 1, |this| {
this.emit_enum_variant_arg(0, |this| ty.encode(this))
})
}
}
});
}
fn emit_autoref(&mut self, autoref: &adjustment::AutoRef<'tcx>) {
use rustc_serialize::Encoder;
self.emit_enum("AutoRef", |this| {
match autoref {
&adjustment::AutoPtr(r, m) => {
this.emit_enum_variant("AutoPtr", 0, 2, |this| {
this.emit_enum_variant_arg(0, |this| r.encode(this));
this.emit_enum_variant_arg(1, |this| m.encode(this))
})
}
&adjustment::AutoUnsafe(m) => {
this.emit_enum_variant("AutoUnsafe", 1, 1, |this| {
this.emit_enum_variant_arg(0, |this| m.encode(this))
})
}
}
});
}
fn emit_auto_deref_ref(&mut self, auto_deref_ref: &adjustment::AutoDerefRef<'tcx>) {
use rustc_serialize::Encoder;
self.emit_struct("AutoDerefRef", 2, |this| {
this.emit_struct_field("autoderefs", 0, |this| auto_deref_ref.autoderefs.encode(this));
this.emit_struct_field("autoref", 1, |this| {
this.emit_option(|this| {
match auto_deref_ref.autoref {
None => this.emit_option_none(),
Some(ref a) => this.emit_option_some(|this| Ok(this.emit_autoref(a))),
}
})
});
this.emit_struct_field("unsize", 2, |this| {
auto_deref_ref.unsize.encode(this)
})
});
}
fn tag<F>(&mut self,
tag_id: usize,
f: F) where
F: FnOnce(&mut Self),
{
self.start_tag(tag_id);
self.start_tag(tag_id).unwrap();
f(self);
self.end_tag();
self.end_tag().unwrap();
}
fn id(&mut self, id: ast::NodeId) {
@ -525,14 +131,6 @@ impl<'a, 'b, 'tcx, 'v> Visitor<'v> for SideTableEncodingIdVisitor<'a, 'b, 'tcx>
}
}
fn encode_side_tables_for_ii(ecx: &mut EncodeContext, ii: &InlinedItem) {
ecx.start_tag(c::tag_table);
ii.visit(&mut SideTableEncodingIdVisitor {
ecx: ecx
});
ecx.end_tag();
}
fn encode_side_tables_for_id(ecx: &mut EncodeContext, id: ast::NodeId) {
let tcx = ecx.tcx;
@ -548,23 +146,21 @@ fn encode_side_tables_for_id(ecx: &mut EncodeContext, id: ast::NodeId) {
if let Some(ty) = tcx.node_types().get(&id) {
ecx.tag(c::tag_table_node_type, |ecx| {
ecx.id(id);
ty.encode(ecx);
ty.encode(ecx).unwrap();
})
}
if let Some(item_substs) = tcx.tables.borrow().item_substs.get(&id) {
ecx.tag(c::tag_table_item_subst, |ecx| {
ecx.id(id);
item_substs.substs.encode(ecx);
item_substs.substs.encode(ecx).unwrap();
})
}
if let Some(fv) = tcx.freevars.borrow().get(&id) {
ecx.tag(c::tag_table_freevars, |ecx| {
ecx.id(id);
ecx.emit_from_vec(fv, |ecx, fv_entry| {
fv_entry.encode(ecx)
});
fv.encode(ecx).unwrap();
});
for freevar in fv {
@ -582,8 +178,8 @@ fn encode_side_tables_for_id(ecx: &mut EncodeContext, id: ast::NodeId) {
.get(&upvar_id)
.unwrap()
.clone();
var_id.encode(ecx);
ecx.emit_upvar_capture(&upvar_capture);
var_id.encode(ecx).unwrap();
upvar_capture.encode(ecx).unwrap();
})
}
}
@ -592,7 +188,8 @@ fn encode_side_tables_for_id(ecx: &mut EncodeContext, id: ast::NodeId) {
if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
ecx.tag(c::tag_table_method_map, |ecx| {
ecx.id(id);
ecx.encode_method_callee(method_call.autoderef, method)
method_call.autoderef.encode(ecx).unwrap();
method.encode(ecx).unwrap();
})
}
@ -604,7 +201,8 @@ fn encode_side_tables_for_id(ecx: &mut EncodeContext, id: ast::NodeId) {
if let Some(method) = tcx.tables.borrow().method_map.get(&method_call) {
ecx.tag(c::tag_table_method_map, |ecx| {
ecx.id(id);
ecx.encode_method_callee(method_call.autoderef, method)
method_call.autoderef.encode(ecx).unwrap();
method.encode(ecx).unwrap();
})
}
}
@ -614,7 +212,7 @@ fn encode_side_tables_for_id(ecx: &mut EncodeContext, id: ast::NodeId) {
ecx.tag(c::tag_table_adjustments, |ecx| {
ecx.id(id);
ecx.emit_auto_adjustment(adjustment);
adjustment.encode(ecx).unwrap();
})
}
@ -633,180 +231,60 @@ fn encode_side_tables_for_id(ecx: &mut EncodeContext, id: ast::NodeId) {
}
}
impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
fn read_upvar_capture(&mut self) -> ty::UpvarCapture<'tcx> {
self.read_enum("UpvarCapture", |this| {
let variants = ["ByValue", "ByRef"];
this.read_enum_variant(&variants, |this, i| {
Ok(match i {
1 => ty::UpvarCapture::ByValue,
2 => ty::UpvarCapture::ByRef(ty::UpvarBorrow {
kind: this.read_enum_variant_arg(0,
|this| Decodable::decode(this)).unwrap(),
region: this.read_enum_variant_arg(1,
|this| Decodable::decode(this)).unwrap()
}),
_ => bug!("bad enum variant for ty::UpvarCapture")
})
})
}).unwrap()
}
fn read_auto_adjustment(&mut self) -> adjustment::AutoAdjustment<'tcx> {
self.read_enum("AutoAdjustment", |this| {
let variants = ["AdjustReifyFnPointer", "AdjustUnsafeFnPointer",
"AdjustMutToConstPointer", "AdjustDerefRef",
"AdjustNeverToAny"];
this.read_enum_variant(&variants, |this, i| {
Ok(match i {
1 => adjustment::AdjustReifyFnPointer,
2 => adjustment::AdjustUnsafeFnPointer,
3 => adjustment::AdjustMutToConstPointer,
4 => {
let auto_deref_ref: adjustment::AutoDerefRef =
this.read_enum_variant_arg(0,
|this| Ok(this.read_auto_deref_ref())).unwrap();
adjustment::AdjustDerefRef(auto_deref_ref)
}
5 => {
let ty: Ty<'tcx> = this.read_enum_variant_arg(0, |this| {
Ty::decode(this)
}).unwrap();
adjustment::AdjustNeverToAny(ty)
}
_ => bug!("bad enum variant for adjustment::AutoAdjustment")
})
})
}).unwrap()
}
fn read_auto_deref_ref(&mut self) -> adjustment::AutoDerefRef<'tcx> {
self.read_struct("AutoDerefRef", 2, |this| {
Ok(adjustment::AutoDerefRef {
autoderefs: this.read_struct_field("autoderefs", 0, |this| {
Decodable::decode(this)
}).unwrap(),
autoref: this.read_struct_field("autoref", 1, |this| {
this.read_option(|this, b| {
if b {
Ok(Some(this.read_autoref()))
} else {
Ok(None)
}
})
}).unwrap(),
unsize: this.read_struct_field("unsize", 2, |this| {
Decodable::decode(this)
}).unwrap(),
})
}).unwrap()
}
fn read_autoref(&mut self) -> adjustment::AutoRef<'tcx> {
self.read_enum("AutoRef", |this| {
let variants = ["AutoPtr", "AutoUnsafe"];
this.read_enum_variant(&variants, |this, i| {
Ok(match i {
0 => {
let r: &'tcx ty::Region =
this.read_enum_variant_arg(0, |this| {
Decodable::decode(this)
}).unwrap();
let m: hir::Mutability =
this.read_enum_variant_arg(1, |this| {
Decodable::decode(this)
}).unwrap();
adjustment::AutoPtr(r, m)
}
1 => {
let m: hir::Mutability =
this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap();
adjustment::AutoUnsafe(m)
}
_ => bug!("bad enum variant for adjustment::AutoRef")
})
})
}).unwrap()
}
}
fn decode_side_tables<'a, 'tcx>(dcx: &mut DecodeContext<'a, 'tcx>,
ast_doc: rbml::Doc<'a>) {
for (tag, entry_doc) in reader::docs(ast_doc.get(c::tag_table)) {
dcx.rbml_r = reader::Decoder::new(entry_doc);
let id0: ast::NodeId = Decodable::decode(dcx).unwrap();
let id = dcx.tr_id(id0);
debug!(">> Side table document with tag 0x{:x} \
found for id {} (orig {})",
tag, id, id0);
let id = Decodable::decode(dcx).unwrap();
debug!("decode_side_tables: entry for id={}, tag=0x{:x}", id, tag);
match tag {
c::tag_table_def => {
let def = Def::decode(dcx).unwrap().tr(dcx);
let def = Decodable::decode(dcx).unwrap();
dcx.tcx.def_map.borrow_mut().insert(id, def::PathResolution::new(def));
}
c::tag_table_node_type => {
let ty = Ty::decode(dcx).unwrap();
let ty = Decodable::decode(dcx).unwrap();
dcx.tcx.node_type_insert(id, ty);
}
c::tag_table_item_subst => {
let item_substs = ty::ItemSubsts {
substs: Decodable::decode(dcx).unwrap()
};
dcx.tcx.tables.borrow_mut().item_substs.insert(
id, item_substs);
let item_substs = Decodable::decode(dcx).unwrap();
dcx.tcx.tables.borrow_mut().item_substs.insert(id, item_substs);
}
c::tag_table_freevars => {
let fv_info = dcx.read_to_vec(|dcx| {
Ok(dcx.read_freevar_entry())
}).unwrap().into_iter().collect();
let fv_info = Decodable::decode(dcx).unwrap();
dcx.tcx.freevars.borrow_mut().insert(id, fv_info);
}
c::tag_table_upvar_capture_map => {
let var_id = ast::NodeId::decode(dcx).unwrap();
let upvar_id = ty::UpvarId {
var_id: dcx.tr_id(var_id),
var_id: Decodable::decode(dcx).unwrap(),
closure_expr_id: id
};
let ub = dcx.read_upvar_capture();
let ub = Decodable::decode(dcx).unwrap();
dcx.tcx.tables.borrow_mut().upvar_capture_map.insert(upvar_id, ub);
}
c::tag_table_method_map => {
let (autoderef, method) = dcx.read_method_callee();
let method_call = ty::MethodCall {
expr_id: id,
autoderef: autoderef
autoderef: Decodable::decode(dcx).unwrap()
};
let method = Decodable::decode(dcx).unwrap();
dcx.tcx.tables.borrow_mut().method_map.insert(method_call, method);
}
c::tag_table_adjustments => {
let adj = dcx.read_auto_adjustment();
let adj = Decodable::decode(dcx).unwrap();
dcx.tcx.tables.borrow_mut().adjustments.insert(id, adj);
}
c::tag_table_cast_kinds => {
let cast_kind = cast::CastKind::decode(dcx).unwrap();
let cast_kind = Decodable::decode(dcx).unwrap();
dcx.tcx.cast_kinds.borrow_mut().insert(id, cast_kind);
}
c::tag_table_const_qualif => {
let qualif = ConstQualif::decode(dcx).unwrap();
let qualif = Decodable::decode(dcx).unwrap();
dcx.tcx.const_qualif_map.borrow_mut().insert(id, qualif);
}
_ => {
bug!("unknown tag found in side tables: {:x}", tag);
bug!("unknown tag found in side tables: 0x{:x}", tag);
}
}
debug!(">< Side table doc loaded");
}
}
fn inlined_item_id_range(ii: &InlinedItem) -> IdRange {
let mut visitor = IdRangeComputingVisitor::new();
ii.visit(&mut visitor);
visitor.result()
}

View file

@ -16,7 +16,7 @@ use cstore::{self, CStore, CrateSource, MetadataBlob};
use decoder;
use loader::{self, CratePaths};
use rustc::hir::def_id::DefIndex;
use rustc::hir::def_id::{CrateNum, DefIndex};
use rustc::hir::svh::Svh;
use rustc::dep_graph::{DepGraph, DepNode};
use rustc::session::{config, Session};
@ -52,7 +52,7 @@ struct LocalCrateReader<'a> {
pub struct CrateReader<'a> {
sess: &'a Session,
cstore: &'a CStore,
next_crate_num: ast::CrateNum,
next_crate_num: CrateNum,
foreign_item_map: FnvHashMap<String, Vec<ast::NodeId>>,
local_crate_name: String,
local_crate_config: ast::CrateConfig,
@ -152,7 +152,7 @@ impl PMDSource {
}
enum LoadResult {
Previous(ast::CrateNum),
Previous(CrateNum),
Loaded(loader::Library),
}
@ -208,7 +208,7 @@ impl<'a> CrateReader<'a> {
}
fn existing_match(&self, name: &str, hash: Option<&Svh>, kind: PathKind)
-> Option<ast::CrateNum> {
-> Option<CrateNum> {
let mut ret = None;
self.cstore.iter_crate_data(|cnum, data| {
if data.name != name { return }
@ -295,14 +295,14 @@ impl<'a> CrateReader<'a> {
span: Span,
lib: loader::Library,
explicitly_linked: bool)
-> (ast::CrateNum, Rc<cstore::CrateMetadata>,
-> (CrateNum, Rc<cstore::CrateMetadata>,
cstore::CrateSource) {
info!("register crate `extern crate {} as {}`", name, ident);
self.verify_no_symbol_conflicts(span, &lib.metadata);
// Claim this crate number and cache it
let cnum = self.next_crate_num;
self.next_crate_num += 1;
self.next_crate_num = CrateNum::from_u32(cnum.as_u32() + 1);
// Stash paths for top-most crate locally if necessary.
let crate_paths = if root.is_none() {
@ -370,7 +370,7 @@ impl<'a> CrateReader<'a> {
span: Span,
kind: PathKind,
explicitly_linked: bool)
-> (ast::CrateNum, Rc<cstore::CrateMetadata>, cstore::CrateSource) {
-> (CrateNum, Rc<cstore::CrateMetadata>, cstore::CrateSource) {
info!("resolving crate `extern crate {} as {}`", name, ident);
let result = match self.existing_match(name, hash, kind) {
Some(cnum) => LoadResult::Previous(cnum),
@ -447,9 +447,9 @@ impl<'a> CrateReader<'a> {
}
fn update_extern_crate(&mut self,
cnum: ast::CrateNum,
cnum: CrateNum,
mut extern_crate: ExternCrate,
visited: &mut FnvHashSet<(ast::CrateNum, bool)>)
visited: &mut FnvHashSet<(CrateNum, bool)>)
{
if !visited.insert((cnum, extern_crate.direct)) { return }
@ -482,7 +482,7 @@ impl<'a> CrateReader<'a> {
fn resolve_crate_deps(&mut self,
root: &Option<CratePaths>,
cdata: &[u8],
krate: ast::CrateNum,
krate: CrateNum,
span: Span)
-> cstore::CrateNumMap {
debug!("resolving deps of external crate");
@ -500,11 +500,13 @@ impl<'a> CrateReader<'a> {
(dep.cnum, local_cnum)
}).collect();
let max_cnum = map.values().cloned().max().unwrap_or(0);
let max_cnum = map.values().cloned().max().map(|cnum| cnum.as_u32()).unwrap_or(0);
// we map 0 and all other holes in the map to our parent crate. The "additional"
// self-dependencies should be harmless.
(0..max_cnum+1).map(|cnum| map.get(&cnum).cloned().unwrap_or(krate)).collect()
(0..max_cnum+1).map(|cnum| {
map.get(&CrateNum::from_u32(cnum)).cloned().unwrap_or(krate)
}).collect()
}
fn read_extension_crate(&mut self, span: Span, info: &CrateInfo) -> ExtensionCrate {
@ -875,7 +877,7 @@ impl<'a> CrateReader<'a> {
}
fn inject_dependency_if(&self,
krate: ast::CrateNum,
krate: CrateNum,
what: &str,
needs_dep: &Fn(&cstore::CrateMetadata) -> bool) {
// don't perform this validation if the session has errors, as one of
@ -1113,7 +1115,7 @@ pub fn read_local_crates(sess: & Session,
/// function. When an item from an external crate is later inlined into this
/// crate, this correspondence information is used to translate the span
/// information of the inlined item so that it refers the correct positions in
/// the local codemap (see `astencode::DecodeContext::tr_span()`).
/// the local codemap (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
///
/// The import algorithm in the function below will reuse FileMaps already
/// existing in the local codemap. For example, even if the FileMap of some

View file

@ -20,7 +20,7 @@ use middle::cstore::{NativeLibraryKind, LinkMeta, LinkagePreference};
use rustc::hir::def;
use middle::lang_items;
use rustc::ty::{self, Ty, TyCtxt, VariantKind};
use rustc::hir::def_id::{DefId, DefIndex, CRATE_DEF_INDEX};
use rustc::hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX};
use rustc::dep_graph::DepNode;
use rustc::hir::map as hir_map;
@ -303,14 +303,14 @@ impl<'tcx> CrateStore<'tcx> for cstore::CStore {
decoder::is_typedef(&cdata, did.index)
}
fn dylib_dependency_formats(&self, cnum: ast::CrateNum)
-> Vec<(ast::CrateNum, LinkagePreference)>
fn dylib_dependency_formats(&self, cnum: CrateNum)
-> Vec<(CrateNum, LinkagePreference)>
{
let cdata = self.get_crate_data(cnum);
decoder::get_dylib_dependency_formats(&cdata)
}
fn lang_items(&self, cnum: ast::CrateNum) -> Vec<(DefIndex, usize)>
fn lang_items(&self, cnum: CrateNum) -> Vec<(DefIndex, usize)>
{
let mut result = vec![];
let crate_data = self.get_crate_data(cnum);
@ -320,80 +320,80 @@ impl<'tcx> CrateStore<'tcx> for cstore::CStore {
result
}
fn missing_lang_items(&self, cnum: ast::CrateNum)
fn missing_lang_items(&self, cnum: CrateNum)
-> Vec<lang_items::LangItem>
{
let cdata = self.get_crate_data(cnum);
decoder::get_missing_lang_items(&cdata)
}
fn is_staged_api(&self, cnum: ast::CrateNum) -> bool
fn is_staged_api(&self, cnum: CrateNum) -> bool
{
self.get_crate_data(cnum).staged_api
}
fn is_explicitly_linked(&self, cnum: ast::CrateNum) -> bool
fn is_explicitly_linked(&self, cnum: CrateNum) -> bool
{
self.get_crate_data(cnum).explicitly_linked.get()
}
fn is_allocator(&self, cnum: ast::CrateNum) -> bool
fn is_allocator(&self, cnum: CrateNum) -> bool
{
self.get_crate_data(cnum).is_allocator()
}
fn is_panic_runtime(&self, cnum: ast::CrateNum) -> bool
fn is_panic_runtime(&self, cnum: CrateNum) -> bool
{
self.get_crate_data(cnum).is_panic_runtime()
}
fn is_compiler_builtins(&self, cnum: ast::CrateNum) -> bool {
fn is_compiler_builtins(&self, cnum: CrateNum) -> bool {
self.get_crate_data(cnum).is_compiler_builtins()
}
fn panic_strategy(&self, cnum: ast::CrateNum) -> PanicStrategy {
fn panic_strategy(&self, cnum: CrateNum) -> PanicStrategy {
self.get_crate_data(cnum).panic_strategy()
}
fn crate_attrs(&self, cnum: ast::CrateNum) -> Vec<ast::Attribute>
fn crate_attrs(&self, cnum: CrateNum) -> Vec<ast::Attribute>
{
decoder::get_crate_attributes(self.get_crate_data(cnum).data())
}
fn crate_name(&self, cnum: ast::CrateNum) -> token::InternedString
fn crate_name(&self, cnum: CrateNum) -> token::InternedString
{
token::intern_and_get_ident(&self.get_crate_data(cnum).name[..])
}
fn original_crate_name(&self, cnum: ast::CrateNum) -> token::InternedString
fn original_crate_name(&self, cnum: CrateNum) -> token::InternedString
{
token::intern_and_get_ident(&self.get_crate_data(cnum).name())
}
fn extern_crate(&self, cnum: ast::CrateNum) -> Option<ExternCrate>
fn extern_crate(&self, cnum: CrateNum) -> Option<ExternCrate>
{
self.get_crate_data(cnum).extern_crate.get()
}
fn crate_hash(&self, cnum: ast::CrateNum) -> Svh
fn crate_hash(&self, cnum: CrateNum) -> Svh
{
let cdata = self.get_crate_data(cnum);
decoder::get_crate_hash(cdata.data())
}
fn crate_disambiguator(&self, cnum: ast::CrateNum) -> token::InternedString
fn crate_disambiguator(&self, cnum: CrateNum) -> token::InternedString
{
let cdata = self.get_crate_data(cnum);
token::intern_and_get_ident(decoder::get_crate_disambiguator(cdata.data()))
}
fn crate_struct_field_attrs(&self, cnum: ast::CrateNum)
fn crate_struct_field_attrs(&self, cnum: CrateNum)
-> FnvHashMap<DefId, Vec<ast::Attribute>>
{
decoder::get_struct_field_attrs(&self.get_crate_data(cnum))
}
fn plugin_registrar_fn(&self, cnum: ast::CrateNum) -> Option<DefId>
fn plugin_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>
{
let cdata = self.get_crate_data(cnum);
decoder::get_plugin_registrar_fn(cdata.data()).map(|index| DefId {
@ -402,24 +402,24 @@ impl<'tcx> CrateStore<'tcx> for cstore::CStore {
})
}
fn native_libraries(&self, cnum: ast::CrateNum) -> Vec<(NativeLibraryKind, String)>
fn native_libraries(&self, cnum: CrateNum) -> Vec<(NativeLibraryKind, String)>
{
let cdata = self.get_crate_data(cnum);
decoder::get_native_libraries(&cdata)
}
fn reachable_ids(&self, cnum: ast::CrateNum) -> Vec<DefId>
fn reachable_ids(&self, cnum: CrateNum) -> Vec<DefId>
{
let cdata = self.get_crate_data(cnum);
decoder::get_reachable_ids(&cdata)
}
fn is_no_builtins(&self, cnum: ast::CrateNum) -> bool {
fn is_no_builtins(&self, cnum: CrateNum) -> bool {
attr::contains_name(&self.crate_attrs(cnum), "no_builtins")
}
fn def_index_for_def_key(&self,
cnum: ast::CrateNum,
cnum: CrateNum,
def: DefKey)
-> Option<DefIndex> {
let cdata = self.get_crate_data(cnum);
@ -488,7 +488,7 @@ impl<'tcx> CrateStore<'tcx> for cstore::CStore {
result
}
fn crate_top_level_items(&self, cnum: ast::CrateNum) -> Vec<ChildItem>
fn crate_top_level_items(&self, cnum: CrateNum) -> Vec<ChildItem>
{
let mut result = vec![];
let crate_data = self.get_crate_data(cnum);
@ -651,7 +651,7 @@ impl<'tcx> CrateStore<'tcx> for cstore::CStore {
decoder::is_item_mir_available(&cdata, def.index)
}
fn crates(&self) -> Vec<ast::CrateNum>
fn crates(&self) -> Vec<CrateNum>
{
let mut result = vec![];
self.iter_crate_data(|cnum, _| result.push(cnum));
@ -686,17 +686,17 @@ impl<'tcx> CrateStore<'tcx> for cstore::CStore {
encoder::encoded_ty(tcx, ty, def_id_to_string)
}
fn used_crates(&self, prefer: LinkagePreference) -> Vec<(ast::CrateNum, Option<PathBuf>)>
fn used_crates(&self, prefer: LinkagePreference) -> Vec<(CrateNum, Option<PathBuf>)>
{
self.do_get_used_crates(prefer)
}
fn used_crate_source(&self, cnum: ast::CrateNum) -> CrateSource
fn used_crate_source(&self, cnum: CrateNum) -> CrateSource
{
self.opt_used_crate_source(cnum).unwrap()
}
fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<ast::CrateNum>
fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<CrateNum>
{
self.do_extern_mod_stmt_cnum(emod_id)
}
@ -738,7 +738,7 @@ impl<'tcx> CrateStore<'tcx> for cstore::CStore {
use rustc::middle::cstore::ChildItem;
use std::collections::vec_deque::VecDeque;
use std::collections::hash_map::Entry;
for cnum in 1 .. self.next_crate_num() {
for cnum in (1 .. self.next_crate_num().as_usize()).map(CrateNum::new) {
let cdata = self.get_crate_data(cnum);
match cdata.extern_crate.get() {

View file

@ -22,7 +22,7 @@ use index;
use loader;
use rustc::dep_graph::DepGraph;
use rustc::hir::def_id::{DefIndex, DefId};
use rustc::hir::def_id::{CrateNum, DefIndex, DefId};
use rustc::hir::map::DefKey;
use rustc::hir::svh::Svh;
use rustc::middle::cstore::ExternCrate;
@ -47,7 +47,7 @@ pub use middle::cstore::{CrateSource, LinkMeta};
// local crate numbers (as generated during this session). Each external
// crate may refer to types in other external crates, and each has their
// own crate numbers.
pub type CrateNumMap = IndexVec<ast::CrateNum, ast::CrateNum>;
pub type CrateNumMap = IndexVec<CrateNum, CrateNum>;
pub enum MetadataBlob {
MetadataVec(Bytes),
@ -75,7 +75,7 @@ pub struct CrateMetadata {
pub data: MetadataBlob,
pub cnum_map: RefCell<CrateNumMap>,
pub cnum: ast::CrateNum,
pub cnum: CrateNum,
pub codemap_import_info: RefCell<Vec<ImportedFileMap>>,
pub staged_api: bool,
@ -105,9 +105,9 @@ pub struct CachedInlinedItem {
pub struct CStore {
pub dep_graph: DepGraph,
metas: RefCell<FnvHashMap<ast::CrateNum, Rc<CrateMetadata>>>,
metas: RefCell<FnvHashMap<CrateNum, Rc<CrateMetadata>>>,
/// Map from NodeId's of local extern crate statements to crate numbers
extern_mod_crate_map: RefCell<NodeMap<ast::CrateNum>>,
extern_mod_crate_map: RefCell<NodeMap<CrateNum>>,
used_crate_sources: RefCell<Vec<CrateSource>>,
used_libraries: RefCell<Vec<(String, NativeLibraryKind)>>,
used_link_args: RefCell<Vec<String>>,
@ -135,25 +135,25 @@ impl CStore {
}
}
pub fn next_crate_num(&self) -> ast::CrateNum {
self.metas.borrow().len() as ast::CrateNum + 1
pub fn next_crate_num(&self) -> CrateNum {
CrateNum::new(self.metas.borrow().len() + 1)
}
pub fn get_crate_data(&self, cnum: ast::CrateNum) -> Rc<CrateMetadata> {
pub fn get_crate_data(&self, cnum: CrateNum) -> Rc<CrateMetadata> {
self.metas.borrow().get(&cnum).unwrap().clone()
}
pub fn get_crate_hash(&self, cnum: ast::CrateNum) -> Svh {
pub fn get_crate_hash(&self, cnum: CrateNum) -> Svh {
let cdata = self.get_crate_data(cnum);
decoder::get_crate_hash(cdata.data())
}
pub fn set_crate_data(&self, cnum: ast::CrateNum, data: Rc<CrateMetadata>) {
pub fn set_crate_data(&self, cnum: CrateNum, data: Rc<CrateMetadata>) {
self.metas.borrow_mut().insert(cnum, data);
}
pub fn iter_crate_data<I>(&self, mut i: I) where
I: FnMut(ast::CrateNum, &Rc<CrateMetadata>),
I: FnMut(CrateNum, &Rc<CrateMetadata>),
{
for (&k, v) in self.metas.borrow().iter() {
i(k, v);
@ -162,7 +162,7 @@ impl CStore {
/// Like `iter_crate_data`, but passes source paths (if available) as well.
pub fn iter_crate_data_origins<I>(&self, mut i: I) where
I: FnMut(ast::CrateNum, &CrateMetadata, Option<CrateSource>),
I: FnMut(CrateNum, &CrateMetadata, Option<CrateSource>),
{
for (&k, v) in self.metas.borrow().iter() {
let origin = self.opt_used_crate_source(k);
@ -178,7 +178,7 @@ impl CStore {
}
}
pub fn opt_used_crate_source(&self, cnum: ast::CrateNum)
pub fn opt_used_crate_source(&self, cnum: CrateNum)
-> Option<CrateSource> {
self.used_crate_sources.borrow_mut()
.iter().find(|source| source.cnum == cnum).cloned()
@ -193,7 +193,7 @@ impl CStore {
self.statically_included_foreign_items.borrow_mut().clear();
}
pub fn crate_dependencies_in_rpo(&self, krate: ast::CrateNum) -> Vec<ast::CrateNum>
pub fn crate_dependencies_in_rpo(&self, krate: CrateNum) -> Vec<CrateNum>
{
let mut ordering = Vec::new();
self.push_dependencies_in_postorder(&mut ordering, krate);
@ -202,8 +202,8 @@ impl CStore {
}
pub fn push_dependencies_in_postorder(&self,
ordering: &mut Vec<ast::CrateNum>,
krate: ast::CrateNum)
ordering: &mut Vec<CrateNum>,
krate: CrateNum)
{
if ordering.contains(&krate) { return }
@ -227,7 +227,7 @@ impl CStore {
// topological sort of all crates putting the leaves at the right-most
// positions.
pub fn do_get_used_crates(&self, prefer: LinkagePreference)
-> Vec<(ast::CrateNum, Option<PathBuf>)> {
-> Vec<(CrateNum, Option<PathBuf>)> {
let mut ordering = Vec::new();
for (&num, _) in self.metas.borrow().iter() {
self.push_dependencies_in_postorder(&mut ordering, num);
@ -272,7 +272,7 @@ impl CStore {
pub fn add_extern_mod_stmt_cnum(&self,
emod_id: ast::NodeId,
cnum: ast::CrateNum) {
cnum: CrateNum) {
self.extern_mod_crate_map.borrow_mut().insert(emod_id, cnum);
}
@ -284,7 +284,7 @@ impl CStore {
self.statically_included_foreign_items.borrow().contains(&id)
}
pub fn do_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<ast::CrateNum>
pub fn do_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<CrateNum>
{
self.extern_mod_crate_map.borrow().get(&emod_id).cloned()
}

View file

@ -34,7 +34,7 @@ use rustc::session::config::PanicStrategy;
use middle::cstore::{InlinedItem, LinkagePreference};
use middle::cstore::{DefLike, DlDef, DlField, DlImpl};
use rustc::hir::def::Def;
use rustc::hir::def_id::{DefId, DefIndex};
use rustc::hir::def_id::{CrateNum, DefId, DefIndex, LOCAL_CRATE};
use middle::lang_items;
use rustc::ty::{ImplContainer, TraitContainer};
use rustc::ty::{self, AdtKind, Ty, TyCtxt, TypeFoldable, VariantKind};
@ -42,11 +42,8 @@ use rustc::ty::subst::Substs;
use rustc_const_math::ConstInt;
use rustc::mir;
use rustc::mir::visit::MutVisitor;
use rustc::mir::repr::Location;
use rustc::mir::repr::Mir;
use std::cell::Cell;
use std::io;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
@ -54,11 +51,10 @@ use std::str;
use rbml::reader;
use rbml;
use rustc_serialize::{Decodable, Decoder, SpecializedDecoder};
use rustc_serialize::{Decodable, SpecializedDecoder};
use syntax::attr;
use syntax::parse::token;
use syntax::ast;
use syntax::codemap;
use syntax::ast::{self, NodeId};
use syntax::print::pprust;
use syntax_pos::{self, Span, BytePos, NO_EXPANSION};
@ -66,10 +62,10 @@ 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,
from_id_range: IdRange,
to_id_range: IdRange,
// Cache the last used filemap for translating spans as an optimization.
pub last_filemap_index: Cell<usize>,
last_filemap_index: usize,
}
impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
@ -82,9 +78,9 @@ impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
let to_id_range = if from_id_range.empty() {
from_id_range
} else {
let cnt = from_id_range.max - from_id_range.min;
let cnt = from_id_range.max.as_usize() - from_id_range.min.as_usize();
let to_id_min = tcx.sess.reserve_node_ids(cnt);
let to_id_max = to_id_min + cnt;
let to_id_max = NodeId::new(to_id_min.as_usize() + cnt);
IdRange { min: to_id_min, max: to_id_max }
};
@ -94,7 +90,7 @@ impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
tcx: tcx,
from_id_range: from_id_range,
to_id_range: to_id_range,
last_filemap_index: Cell::new(0)
last_filemap_index: 0
}
}
@ -104,7 +100,7 @@ impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
self.read_opaque(|this, doc| {
Ok(op(&mut TyDecoder::with_doc(
this.tcx, this.cdata.cnum, doc,
&mut |d| this.tr_def_id(d))))
&mut |d| translate_def_id(&this.cdata, d))))
}).unwrap()
}
}
@ -122,6 +118,93 @@ impl<'a, 'tcx> DerefMut for DecodeContext<'a, 'tcx> {
}
}
impl<'a, 'tcx> SpecializedDecoder<NodeId> for DecodeContext<'a, 'tcx> {
fn specialized_decode(&mut self) -> Result<NodeId, Self::Error> {
let id = u32::decode(self)?;
// from_id_range should be non-empty
assert!(!self.from_id_range.empty());
// Make sure that translating the NodeId will actually yield a
// meaningful result
if !self.from_id_range.contains(NodeId::from_u32(id)) {
bug!("NodeId::decode: {} out of DecodeContext range ({:?} -> {:?})",
id, self.from_id_range, self.to_id_range);
}
// Use wrapping arithmetic because otherwise it introduces control flow.
// Maybe we should just have the control flow? -- aatch
Ok(NodeId::from_u32(id.wrapping_sub(self.from_id_range.min.as_u32())
.wrapping_add(self.to_id_range.min.as_u32())))
}
}
impl<'a, 'tcx> SpecializedDecoder<CrateNum> for DecodeContext<'a, 'tcx> {
fn specialized_decode(&mut self) -> Result<CrateNum, Self::Error> {
let cnum = CrateNum::from_u32(u32::decode(self)?);
if cnum == LOCAL_CRATE {
Ok(self.cdata.cnum)
} else {
Ok(self.cdata.cnum_map.borrow()[cnum])
}
}
}
impl<'a, 'tcx> SpecializedDecoder<Span> for DecodeContext<'a, 'tcx> {
fn specialized_decode(&mut self) -> Result<Span, Self::Error> {
let lo = BytePos::decode(self)?;
let hi = BytePos::decode(self)?;
let (lo, hi) = if lo > hi {
// Currently macro expansion sometimes produces invalid Span values
// where lo > hi. In order not to crash the compiler when trying to
// translate these values, let's transform them into something we
// can handle (and which will produce useful debug locations at
// least some of the time).
// This workaround is only necessary as long as macro expansion is
// not fixed. FIXME(#23480)
(lo, lo)
} else {
(lo, hi)
};
let imported_filemaps = self.cdata.imported_filemaps(&self.tcx.sess.codemap());
let filemap = {
// Optimize for the case that most spans within a translated item
// originate from the same filemap.
let last_filemap = &imported_filemaps[self.last_filemap_index];
if lo >= last_filemap.original_start_pos &&
lo <= last_filemap.original_end_pos &&
hi >= last_filemap.original_start_pos &&
hi <= last_filemap.original_end_pos {
last_filemap
} else {
let mut a = 0;
let mut b = imported_filemaps.len();
while b - a > 1 {
let m = (a + b) / 2;
if imported_filemaps[m].original_start_pos > lo {
b = m;
} else {
a = m;
}
}
self.last_filemap_index = a;
&imported_filemaps[a]
}
};
let lo = (lo - filemap.original_start_pos) +
filemap.translated_filemap.start_pos;
let hi = (hi - filemap.original_start_pos) +
filemap.translated_filemap.start_pos;
Ok(syntax_pos::mk_sp(lo, hi))
}
}
// 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.
@ -148,8 +231,8 @@ impl<'a, 'tcx> SpecializedDecoder<&'tcx ty::Region> for DecodeContext<'a, 'tcx>
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)?)
func_substs: Decodable::decode(self)?,
upvar_tys: self.tcx.mk_type_list(Decodable::decode(self)?)
})
}
}
@ -157,7 +240,6 @@ impl<'a, 'tcx> SpecializedDecoder<ty::ClosureSubsts<'tcx>> for DecodeContext<'a,
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))
}
}
@ -318,8 +400,10 @@ fn item_sort(item: rbml::Doc) -> Option<char> {
fn untranslated_def_id(d: rbml::Doc) -> DefId {
let id = reader::doc_as_u64(d);
let index = DefIndex::new((id & 0xFFFF_FFFF) as usize);
DefId { krate: (id >> 32) as u32, index: index }
DefId {
krate: CrateNum::from_u32((id >> 32) as u32),
index: DefIndex::from_u32((id & 0xFFFF_FFFF) as u32)
}
}
fn translated_def_id(cdata: Cmd, d: rbml::Doc) -> DefId {
@ -744,7 +828,7 @@ fn each_child_of_item_or_crate<F, G>(cdata: Cmd,
mut get_crate_data: G,
mut callback: F) where
F: FnMut(DefLike, ast::Name, ty::Visibility),
G: FnMut(ast::CrateNum) -> Rc<CrateMetadata>,
G: FnMut(CrateNum) -> Rc<CrateMetadata>,
{
// Iterate over all children.
for child_info_doc in reader::tagged_docs(item_doc, tag_mod_child) {
@ -806,7 +890,7 @@ fn each_child_of_item_or_crate<F, G>(cdata: Cmd,
/// Iterates over each child of the given item.
pub fn each_child_of_item<F, G>(cdata: Cmd, id: DefIndex, get_crate_data: G, callback: F)
where F: FnMut(DefLike, ast::Name, ty::Visibility),
G: FnMut(ast::CrateNum) -> Rc<CrateMetadata>,
G: FnMut(CrateNum) -> Rc<CrateMetadata>,
{
// Find the item.
let item_doc = match cdata.get_item(id) {
@ -820,7 +904,7 @@ pub fn each_child_of_item<F, G>(cdata: Cmd, id: DefIndex, get_crate_data: G, cal
/// Iterates over all the top-level crate items.
pub fn each_top_level_item_of_crate<F, G>(cdata: Cmd, get_crate_data: G, callback: F)
where F: FnMut(DefLike, ast::Name, ty::Visibility),
G: FnMut(ast::CrateNum) -> Rc<CrateMetadata>,
G: FnMut(CrateNum) -> Rc<CrateMetadata>,
{
each_child_of_item(cdata, CRATE_DEF_INDEX, get_crate_data, callback)
}
@ -894,52 +978,14 @@ pub fn is_item_mir_available<'tcx>(cdata: Cmd, id: DefIndex) -> bool {
pub fn maybe_get_item_mir<'a, 'tcx>(cdata: Cmd,
tcx: TyCtxt<'a, 'tcx, 'tcx>,
id: DefIndex)
-> Option<mir::repr::Mir<'tcx>> {
-> Option<Mir<'tcx>> {
let item_doc = cdata.lookup_item(id);
return reader::maybe_get_doc(item_doc, tag_mir as usize).map(|mir_doc| {
let mut dcx = DecodeContext::new(tcx, cdata,
IdRange { min: 0, max: 0 },
mir_doc);
let mut mir = Decodable::decode(&mut dcx).unwrap();
assert!(dcx.rbml_r.position() == mir_doc.end);
let mut def_id_and_span_translator = MirDefIdAndSpanTranslator {
crate_metadata: cdata,
codemap: tcx.sess.codemap(),
last_filemap_index_hint: Cell::new(0),
};
def_id_and_span_translator.visit_mir(&mut mir);
for promoted in &mut mir.promoted {
def_id_and_span_translator.visit_mir(promoted);
}
mir
});
struct MirDefIdAndSpanTranslator<'cdata, 'codemap> {
crate_metadata: Cmd<'cdata>,
codemap: &'codemap codemap::CodeMap,
last_filemap_index_hint: Cell<usize>
}
impl<'v, 'cdata, 'codemap> mir::visit::MutVisitor<'v>
for MirDefIdAndSpanTranslator<'cdata, 'codemap>
{
fn visit_def_id(&mut self, def_id: &mut DefId, _: Location) {
*def_id = translate_def_id(self.crate_metadata, *def_id);
}
fn visit_span(&mut self, span: &mut Span) {
*span = translate_span(self.crate_metadata,
self.codemap,
&self.last_filemap_index_hint,
*span);
}
}
reader::maybe_get_doc(item_doc, tag_mir).map(|mir_doc| {
let id_range = IdRange { min: NodeId::new(0), max: NodeId::new(0) };
let mut dcx = DecodeContext::new(tcx, cdata, id_range, mir_doc);
Decodable::decode(&mut dcx).unwrap()
})
}
fn get_explicit_self<'a, 'tcx>(item: rbml::Doc, tcx: TyCtxt<'a, 'tcx, 'tcx>)
@ -1225,7 +1271,7 @@ pub fn get_crate_attributes(data: &[u8]) -> Vec<ast::Attribute> {
#[derive(Clone)]
pub struct CrateDep {
pub cnum: ast::CrateNum,
pub cnum: CrateNum,
pub name: String,
pub hash: Svh,
pub explicitly_linked: bool,
@ -1246,7 +1292,7 @@ pub fn get_crate_deps(data: &[u8]) -> Vec<CrateDep> {
let doc = reader::get_doc(depdoc, tag_crate_dep_explicitly_linked);
let explicitly_linked = reader::doc_as_u8(doc) != 0;
CrateDep {
cnum: crate_num as u32 + 1,
cnum: CrateNum::new(crate_num + 1),
name: name,
hash: hash,
explicitly_linked: explicitly_linked,
@ -1335,64 +1381,6 @@ fn reverse_translate_def_id(cdata: Cmd, did: DefId) -> Option<DefId> {
None
}
/// Translates a `Span` from an extern crate to the corresponding `Span`
/// within the local crate's codemap.
pub fn translate_span(cdata: Cmd,
codemap: &codemap::CodeMap,
last_filemap_index_hint: &Cell<usize>,
span: syntax_pos::Span)
-> syntax_pos::Span {
let span = if span.lo > span.hi {
// Currently macro expansion sometimes produces invalid Span values
// where lo > hi. In order not to crash the compiler when trying to
// translate these values, let's transform them into something we
// can handle (and which will produce useful debug locations at
// least some of the time).
// This workaround is only necessary as long as macro expansion is
// not fixed. FIXME(#23480)
syntax_pos::mk_sp(span.lo, span.lo)
} else {
span
};
let imported_filemaps = cdata.imported_filemaps(&codemap);
let filemap = {
// Optimize for the case that most spans within a translated item
// originate from the same filemap.
let last_filemap_index = last_filemap_index_hint.get();
let last_filemap = &imported_filemaps[last_filemap_index];
if span.lo >= last_filemap.original_start_pos &&
span.lo <= last_filemap.original_end_pos &&
span.hi >= last_filemap.original_start_pos &&
span.hi <= last_filemap.original_end_pos {
last_filemap
} else {
let mut a = 0;
let mut b = imported_filemaps.len();
while b - a > 1 {
let m = (a + b) / 2;
if imported_filemaps[m].original_start_pos > span.lo {
b = m;
} else {
a = m;
}
}
last_filemap_index_hint.set(a);
&imported_filemaps[a]
}
};
let lo = (span.lo - filemap.original_start_pos) +
filemap.translated_filemap.start_pos;
let hi = (span.hi - filemap.original_start_pos) +
filemap.translated_filemap.start_pos;
syntax_pos::mk_sp(lo, hi)
}
pub fn each_inherent_implementation_for_type<F>(cdata: Cmd,
id: DefIndex,
mut callback: F)
@ -1491,7 +1479,7 @@ pub fn get_macro_span(doc: rbml::Doc) -> Span {
}
pub fn get_dylib_dependency_formats(cdata: Cmd)
-> Vec<(ast::CrateNum, LinkagePreference)>
-> Vec<(CrateNum, LinkagePreference)>
{
let formats = reader::get_doc(rbml::Doc::new(cdata.data()),
tag_dylib_dependency_formats);
@ -1503,7 +1491,7 @@ pub fn get_dylib_dependency_formats(cdata: Cmd)
let mut split = spec.split(':');
let cnum = split.next().unwrap();
let link = split.next().unwrap();
let cnum: ast::CrateNum = cnum.parse().unwrap();
let cnum = CrateNum::new(cnum.parse().unwrap());
let cnum = cdata.cnum_map.borrow()[cnum];
result.push((cnum, if link == "d" {
LinkagePreference::RequireDynamic

View file

@ -23,7 +23,7 @@ use index::{self, IndexData};
use middle::cstore::{InlinedItemRef, LinkMeta};
use rustc::hir::def;
use rustc::hir::def_id::{CRATE_DEF_INDEX, DefId};
use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
use middle::dependency_format::Linkage;
use rustc::dep_graph::DepNode;
use rustc::traits::specialization_graph;
@ -42,7 +42,7 @@ use std::io::{Cursor, SeekFrom};
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use std::u32;
use syntax::ast::{self, NodeId, Name, CRATE_NODE_ID, CrateNum};
use syntax::ast::{self, NodeId, Name, CRATE_NODE_ID};
use syntax::attr;
use syntax;
use syntax_pos::BytePos;
@ -136,8 +136,7 @@ fn encode_family(ecx: &mut EncodeContext, c: char) {
}
pub fn def_to_u64(did: DefId) -> u64 {
assert!(did.index.as_u32() < u32::MAX);
(did.krate as u64) << 32 | (did.index.as_usize() as u64)
(did.krate.as_u32() as u64) << 32 | (did.index.as_u32() as u64)
}
pub fn def_to_string(_tcx: TyCtxt, did: DefId) -> String {
@ -1457,7 +1456,7 @@ fn encode_crate_deps(ecx: &mut EncodeContext, cstore: &cstore::CStore) {
// Sanity-check the crate numbers
let mut expected_cnum = 1;
for &(n, _) in &deps {
assert_eq!(n, expected_cnum);
assert_eq!(n, CrateNum::new(expected_cnum));
expected_cnum += 1;
}

View file

@ -18,7 +18,7 @@
use rustc::hir;
use rustc::hir::def_id::{DefId, DefIndex};
use rustc::hir::def_id::{CrateNum, DefId, DefIndex};
use middle::region;
use rustc::ty::subst::{Kind, Substs};
use rustc::ty::{self, ToPredicate, Ty, TyCtxt, TypeFoldable};
@ -38,7 +38,7 @@ pub type DefIdConvert<'a> = &'a mut FnMut(DefId) -> DefId;
pub struct TyDecoder<'a, 'tcx: 'a> {
data: &'a [u8],
krate: ast::CrateNum,
krate: CrateNum,
pos: usize,
tcx: TyCtxt<'a, 'tcx, 'tcx>,
conv_def_id: DefIdConvert<'a>,
@ -46,7 +46,7 @@ pub struct TyDecoder<'a, 'tcx: 'a> {
impl<'a,'tcx> TyDecoder<'a,'tcx> {
pub fn with_doc(tcx: TyCtxt<'a, 'tcx, 'tcx>,
crate_num: ast::CrateNum,
crate_num: CrateNum,
doc: rbml::Doc<'a>,
conv: DefIdConvert<'a>)
-> TyDecoder<'a,'tcx> {
@ -54,7 +54,7 @@ impl<'a,'tcx> TyDecoder<'a,'tcx> {
}
pub fn new(data: &'a [u8],
crate_num: ast::CrateNum,
crate_num: CrateNum,
pos: usize,
tcx: TyCtxt<'a, 'tcx, 'tcx>,
conv: DefIdConvert<'a>)
@ -258,9 +258,9 @@ impl<'a,'tcx> TyDecoder<'a,'tcx> {
// May still be worth fixing though.
'C' => {
assert_eq!(self.next(), '[');
let fn_id = self.parse_uint() as ast::NodeId;
let fn_id = ast::NodeId::new(self.parse_uint());
assert_eq!(self.next(), '|');
let body_id = self.parse_uint() as ast::NodeId;
let body_id = ast::NodeId::new(self.parse_uint());
assert_eq!(self.next(), ']');
region::CodeExtentData::CallSiteScope {
fn_id: fn_id, body_id: body_id
@ -269,25 +269,25 @@ impl<'a,'tcx> TyDecoder<'a,'tcx> {
// This creates scopes with the wrong NodeId. (See note above.)
'P' => {
assert_eq!(self.next(), '[');
let fn_id = self.parse_uint() as ast::NodeId;
let fn_id = ast::NodeId::new(self.parse_uint());
assert_eq!(self.next(), '|');
let body_id = self.parse_uint() as ast::NodeId;
let body_id = ast::NodeId::new(self.parse_uint());
assert_eq!(self.next(), ']');
region::CodeExtentData::ParameterScope {
fn_id: fn_id, body_id: body_id
}
}
'M' => {
let node_id = self.parse_uint() as ast::NodeId;
let node_id = ast::NodeId::new(self.parse_uint());
region::CodeExtentData::Misc(node_id)
}
'D' => {
let node_id = self.parse_uint() as ast::NodeId;
let node_id = ast::NodeId::new(self.parse_uint());
region::CodeExtentData::DestructionScope(node_id)
}
'B' => {
assert_eq!(self.next(), '[');
let node_id = self.parse_uint() as ast::NodeId;
let node_id = ast::NodeId::new(self.parse_uint());
assert_eq!(self.next(), '|');
let first_stmt_index = self.parse_u32();
assert_eq!(self.next(), ']');
@ -726,7 +726,7 @@ fn parse_defid(buf: &[u8]) -> DefId {
let crate_num = match str::from_utf8(crate_part).ok().and_then(|s| {
s.parse::<usize>().ok()
}) {
Some(cn) => cn as ast::CrateNum,
Some(cn) => CrateNum::new(cn),
None => bug!("internal error: parse_defid: crate number expected, found {:?}",
crate_part)
};

View file

@ -20,6 +20,7 @@ use rustc::mir::tcx::LvalueTy;
use rustc::mir::transform::{MirPass, MirSource, Pass};
use rustc::mir::visit::{self, Visitor};
use std::fmt;
use syntax::ast;
use syntax_pos::{Span, DUMMY_SP};
use rustc_data_structures::indexed_vec::Idx;
@ -673,7 +674,7 @@ impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
where T: fmt::Debug + TypeFoldable<'tcx>
{
let mut selcx = traits::SelectionContext::new(self.infcx);
let cause = traits::ObligationCause::misc(self.last_span, 0);
let cause = traits::ObligationCause::misc(self.last_span, ast::CRATE_NODE_ID);
let traits::Normalized { value, obligations } =
traits::normalize(&mut selcx, cause, value);

View file

@ -49,14 +49,14 @@ use rustc::middle::cstore::MacroLoader;
use rustc::session::Session;
use rustc::lint;
use rustc::hir::def::*;
use rustc::hir::def_id::{CRATE_DEF_INDEX, DefId};
use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
use rustc::ty;
use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap};
use rustc::util::nodemap::{NodeMap, NodeSet, FnvHashMap, FnvHashSet};
use syntax::ext::hygiene::Mark;
use syntax::ast::{self, FloatTy};
use syntax::ast::{CRATE_NODE_ID, Name, NodeId, CrateNum, IntTy, UintTy};
use syntax::ast::{CRATE_NODE_ID, Name, NodeId, IntTy, UintTy};
use syntax::parse::token::{self, keywords};
use syntax::util::lev_distance::find_best_match_for_name;

View file

@ -135,7 +135,7 @@ struct ExpansionVisitor<'b, 'a: 'b> {
impl<'a, 'b> ExpansionVisitor<'a, 'b> {
fn visit_invoc(&mut self, id: ast::NodeId) {
assert_eq!(id, self.resolver.expansion_data.len() as u32);
assert_eq!(id.as_u32(), self.resolver.expansion_data.len() as u32);
self.resolver.expansion_data.push(ExpansionData {
module: self.current_module.clone(),
});

View file

@ -14,8 +14,8 @@
//! retrieve the data from a crate.
use rustc::hir;
use rustc::hir::def_id::DefId;
use syntax::ast::{self, CrateNum, NodeId};
use rustc::hir::def_id::{CrateNum, DefId};
use syntax::ast::{self, NodeId};
use syntax_pos::Span;
pub struct CrateData {

View file

@ -29,7 +29,7 @@
use rustc::hir;
use rustc::hir::def::Def;
use rustc::hir::def_id::DefId;
use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
use rustc::hir::map::{Node, NodeItem};
use rustc::session::Session;
use rustc::ty::{self, TyCtxt, ImplOrTraitItem, ImplOrTraitItemContainer};
@ -37,7 +37,7 @@ use rustc::ty::{self, TyCtxt, ImplOrTraitItem, ImplOrTraitItemContainer};
use std::collections::HashSet;
use std::hash::*;
use syntax::ast::{self, NodeId, PatKind, Attribute};
use syntax::ast::{self, NodeId, PatKind, Attribute, CRATE_NODE_ID};
use syntax::parse::token::{self, keywords};
use syntax::visit::{self, Visitor};
use syntax::print::pprust::{path_to_string, ty_to_string, bounds_to_string, generics_to_string};
@ -95,7 +95,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> {
analysis: analysis,
dumper: dumper,
span: span_utils.clone(),
cur_scope: 0,
cur_scope: CRATE_NODE_ID,
mac_defs: HashSet::new(),
mac_uses: HashSet::new(),
}
@ -124,7 +124,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> {
let lo_loc = self.span.sess.codemap().lookup_char_pos(c.span.lo);
ExternalCrateData {
name: c.name,
num: c.number,
num: CrateNum::from_u32(c.number),
file_name: SpanUtils::make_path_string(&lo_loc.file.name),
}
}).collect();
@ -252,7 +252,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> {
ref_id: None,
span: *span,
qualname: qualname.to_owned(),
scope: 0
scope: CRATE_NODE_ID
}.lower(self.tcx));
// write the other sub-paths
@ -368,7 +368,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> {
qualname: format!("{}::{}", qualname, path_to_string(p)),
type_value: typ,
value: String::new(),
scope: 0,
scope: CRATE_NODE_ID,
parent: None,
visibility: Visibility::Inherited,
docs: String::new(),
@ -1044,7 +1044,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> {
qualname: format!("{}${}", path_to_string(p), id),
value: value,
type_value: typ,
scope: 0,
scope: CRATE_NODE_ID,
parent: None,
visibility: Visibility::Inherited,
docs: String::new(),
@ -1239,7 +1239,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump +'ll> Visitor for DumpVisitor<'l, 'tcx, 'll, D>
let alias_span = self.span.span_for_last_ident(item.span);
let cnum = match self.sess.cstore.extern_mod_stmt_cnum(item.id) {
Some(cnum) => cnum,
None => 0,
None => LOCAL_CRATE,
};
if !self.span.filter_generated(alias_span, item.span) {
@ -1478,7 +1478,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump +'ll> Visitor for DumpVisitor<'l, 'tcx, 'll, D>
qualname: format!("{}${}", path_to_string(p), id),
value: value,
type_value: typ,
scope: 0,
scope: CRATE_NODE_ID,
parent: None,
visibility: Visibility::Inherited,
docs: String::new(),

View file

@ -8,10 +8,10 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use rustc::hir::def_id::{DefId, DefIndex};
use rustc::hir::def_id::{CrateNum, DefId, DefIndex};
use rustc::hir::map::Map;
use rustc::ty::TyCtxt;
use syntax::ast::{CrateNum, NodeId};
use syntax::ast::NodeId;
use syntax::codemap::CodeMap;
use syntax_pos::Span;
@ -28,7 +28,10 @@ pub fn make_def_id(id: NodeId, map: &Map) -> DefId {
}
pub fn null_def_id() -> DefId {
DefId { krate: u32::max_value(), index: DefIndex::from_u32(u32::max_value()) }
DefId {
krate: CrateNum::from_u32(u32::max_value()),
index: DefIndex::from_u32(u32::max_value())
}
}
#[derive(Clone, Debug, RustcEncodable)]

View file

@ -117,7 +117,7 @@ struct Id {
impl From<DefId> for Id {
fn from(id: DefId) -> Id {
Id {
krate: id.krate,
krate: id.krate.as_u32(),
index: id.index.as_u32(),
}
}

View file

@ -120,7 +120,7 @@ struct Id {
impl From<DefId> for Id {
fn from(id: DefId) -> Id {
Id {
krate: id.krate,
krate: id.krate.as_u32(),
index: id.index.as_u32(),
}
}

View file

@ -52,7 +52,7 @@ use std::env;
use std::fs::{self, File};
use std::path::{Path, PathBuf};
use syntax::ast::{self, NodeId, PatKind, Attribute};
use syntax::ast::{self, NodeId, PatKind, Attribute, CRATE_NODE_ID};
use syntax::parse::lexer::comments::strip_doc_comment_decoration;
use syntax::parse::token::{self, keywords, InternedString};
use syntax::visit::{self, Visitor};
@ -120,7 +120,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
};
result.push(CrateData {
name: (&self.tcx.sess.cstore.crate_name(n)[..]).to_owned(),
number: n,
number: n.as_u32(),
span: span,
});
}
@ -676,7 +676,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
#[inline]
pub fn enclosing_scope(&self, id: NodeId) -> NodeId {
self.tcx.map.get_enclosing_scope(id).unwrap_or(0)
self.tcx.map.get_enclosing_scope(id).unwrap_or(CRATE_NODE_ID)
}
}

View file

@ -556,9 +556,9 @@ fn range_to_inttype(cx: &CrateContext, hint: Hint, bounds: &IntBounds) -> IntTyp
let attempts;
match hint {
attr::ReprInt(span, ity) => {
attr::ReprInt(ity) => {
if !bounds_usable(cx, ity, bounds) {
span_bug!(span, "representation hint insufficient for discriminant range")
bug!("representation hint insufficient for discriminant range")
}
return ity;
}

View file

@ -26,6 +26,7 @@ use CrateTranslation;
use util::common::time;
use util::fs::fix_windows_verbatim_for_gcc;
use rustc::dep_graph::DepNode;
use rustc::hir::def_id::CrateNum;
use rustc::hir::svh::Svh;
use rustc_back::tempdir::TempDir;
use rustc_incremental::IncrementalHashesMap;
@ -288,7 +289,7 @@ pub fn filename_for_input(sess: &Session,
}
pub fn each_linked_rlib(sess: &Session,
f: &mut FnMut(ast::CrateNum, &Path)) {
f: &mut FnMut(CrateNum, &Path)) {
let crates = sess.cstore.used_crates(LinkagePreference::RequireStatic).into_iter();
let fmts = sess.dependency_formats.borrow();
let fmts = fmts.get(&config::CrateTypeExecutable)
@ -299,7 +300,7 @@ pub fn each_linked_rlib(sess: &Session,
bug!("could not find formats for rlibs")
});
for (cnum, path) in crates {
match fmts[cnum as usize - 1] {
match fmts[cnum.as_usize() - 1] {
Linkage::NotLinked | Linkage::IncludedFromDylib => continue,
_ => {}
}
@ -933,7 +934,7 @@ fn add_upstream_rust_crates(cmd: &mut Linker,
// appear statically in an existing dylib, meaning we'll pick up all the
// symbols from the dylib.
let src = sess.cstore.used_crate_source(cnum);
match data[cnum as usize - 1] {
match data[cnum.as_usize() - 1] {
// compiler-builtins are always placed last to ensure that they're
// linked correctly.
_ if sess.cstore.is_compiler_builtins(cnum) => {
@ -1003,7 +1004,7 @@ fn add_upstream_rust_crates(cmd: &mut Linker,
sess: &Session,
tmpdir: &Path,
crate_type: config::CrateType,
cnum: ast::CrateNum) {
cnum: CrateNum) {
let src = sess.cstore.used_crate_source(cnum);
let cratepath = &src.rlib.unwrap().0;
if !sess.lto() && crate_type != config::CrateTypeDylib {

View file

@ -21,10 +21,10 @@ use monomorphize::Instance;
use back::archive;
use middle::dependency_format::Linkage;
use rustc::hir::def_id::CrateNum;
use session::Session;
use session::config::CrateType;
use session::config;
use syntax::ast;
/// For all the linkers we support, and information they might
/// need out of the shared crate context before we get rid of it.
@ -473,7 +473,7 @@ fn exported_symbols(scx: &SharedCrateContext,
let deps = formats[&crate_type].iter();
symbols.extend(deps.enumerate().filter_map(|(i, f)| {
if *f == Linkage::Static {
Some((i + 1) as ast::CrateNum)
Some(CrateNum::new(i + 1))
} else {
None
}

View file

@ -12,10 +12,11 @@ use std::collections::HashSet;
use std::env;
use std::path::{Path, PathBuf};
use std::fs;
use syntax::ast;
use rustc::hir::def_id::CrateNum;
pub struct RPathConfig<'a> {
pub used_crates: Vec<(ast::CrateNum, Option<PathBuf>)>,
pub used_crates: Vec<(CrateNum, Option<PathBuf>)>,
pub out_filename: PathBuf,
pub is_like_osx: bool,
pub has_rpath: bool,

View file

@ -101,8 +101,8 @@ use common::{CrateContext, SharedCrateContext, gensym_name};
use monomorphize::Instance;
use util::sha2::{Digest, Sha256};
use rustc::middle::{cstore, weak_lang_items};
use rustc::hir::def_id::DefId;
use rustc::middle::weak_lang_items;
use rustc::hir::def_id::{DefId, LOCAL_CRATE};
use rustc::hir::map as hir_map;
use rustc::ty::{Ty, TyCtxt, TypeFoldable};
use rustc::ty::item_path::{self, ItemPathBuffer, RootMode};
@ -298,7 +298,7 @@ pub fn exported_name_from_type_and_prefix<'a, 'tcx>(scx: &SharedCrateContext<'a,
-> String {
let empty_def_path = DefPath {
data: vec![],
krate: cstore::LOCAL_CRATE,
krate: LOCAL_CRATE,
};
let hash = get_symbol_hash(scx, &empty_def_path, t, None);
let path = [token::intern_and_get_ident(prefix)];
@ -315,7 +315,7 @@ pub fn internal_name_from_type_and_suffix<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>
gensym_name(suffix).as_str()];
let def_path = DefPath {
data: vec![],
krate: cstore::LOCAL_CRATE,
krate: LOCAL_CRATE,
};
let hash = get_symbol_hash(ccx.shared(), &def_path, t, None);
mangle(path.iter().cloned(), Some(&hash[..]))

View file

@ -69,7 +69,6 @@ pub use base::trans_crate;
pub use disr::Disr;
pub mod back {
pub use rustc_back::rpath;
pub use rustc::hir::svh;
pub mod archive;
@ -79,6 +78,7 @@ pub mod back {
pub mod symbol_names;
pub mod write;
pub mod msvc;
pub mod rpath;
}
pub mod diagnostics;

View file

@ -356,7 +356,7 @@ fn llvm_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
format!("{}<{}>", base, strings.join(", "))
};
if did.krate == 0 {
if did.is_local() {
tstr
} else {
format!("{}.{}", did.krate, tstr)

View file

@ -12,9 +12,8 @@ use super::{DeferredCallResolution, Expectation, FnCtxt,
TupleArgumentsFlag};
use CrateCtxt;
use middle::cstore::LOCAL_CRATE;
use hir::def::Def;
use hir::def_id::DefId;
use hir::def_id::{DefId, LOCAL_CRATE};
use rustc::{infer, traits};
use rustc::ty::{self, LvaluePreference, Ty};
use syntax::parse::token;

View file

@ -577,7 +577,7 @@ pub fn compare_const_impl<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
assoc::normalize_associated_types_in(&infcx,
&mut fulfillment_cx,
impl_c_span,
0,
ast::CRATE_NODE_ID,
&impl_ty);
debug!("compare_const_impl: impl_ty={:?}",
@ -587,7 +587,7 @@ pub fn compare_const_impl<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
assoc::normalize_associated_types_in(&infcx,
&mut fulfillment_cx,
impl_c_span,
0,
ast::CRATE_NODE_ID,
&trait_ty);
debug!("compare_const_impl: trait_ty={:?}",

View file

@ -83,9 +83,8 @@ use self::TupleArgumentsFlag::*;
use astconv::{AstConv, ast_region_to_region, PathParamMode};
use dep_graph::DepNode;
use fmt_macros::{Parser, Piece, Position};
use middle::cstore::LOCAL_CRATE;
use hir::def::{Def, PathResolution};
use hir::def_id::DefId;
use hir::def_id::{DefId, LOCAL_CRATE};
use hir::pat_util;
use rustc::infer::{self, InferCtxt, InferOk, TypeOrigin, TypeTrace, type_variable};
use rustc::ty::subst::{Subst, Substs};
@ -1450,7 +1449,8 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
writeback_errors: Cell::new(false),
err_count_on_creation: inh.tcx.sess.err_count(),
ret_ty: rty,
ps: RefCell::new(UnsafetyState::function(hir::Unsafety::Normal, 0)),
ps: RefCell::new(UnsafetyState::function(hir::Unsafety::Normal,
ast::CRATE_NODE_ID)),
inh: inh,
}
}
@ -2117,7 +2117,8 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
.unwrap_or(type_variable::Default {
ty: self.next_ty_var(),
origin_span: syntax_pos::DUMMY_SP,
def_id: self.tcx.map.local_def_id(0) // what do I put here?
// what do I put here?
def_id: self.tcx.map.local_def_id(ast::CRATE_NODE_ID)
});
// This is to ensure that we elimnate any non-determinism from the error

View file

@ -11,8 +11,7 @@
//! Orphan checker: every impl either implements a trait defined in this
//! crate or pertains to a type defined in this crate.
use middle::cstore::LOCAL_CRATE;
use hir::def_id::DefId;
use hir::def_id::{DefId, LOCAL_CRATE};
use rustc::traits;
use rustc::ty::{self, TyCtxt};
use syntax::ast;

View file

@ -37,7 +37,7 @@ use rustc::middle::cstore;
use rustc::middle::privacy::AccessLevels;
use rustc::middle::resolve_lifetime::DefRegion::*;
use rustc::hir::def::Def;
use rustc::hir::def_id::{DefId, DefIndex, CRATE_DEF_INDEX};
use rustc::hir::def_id::{self, DefId, DefIndex, CRATE_DEF_INDEX};
use rustc::hir::fold::Folder;
use rustc::hir::print as pprust;
use rustc::ty::subst::Substs;
@ -116,7 +116,7 @@ pub struct Crate {
pub name: String,
pub src: PathBuf,
pub module: Option<Item>,
pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
pub externs: Vec<(def_id::CrateNum, ExternalCrate)>,
pub primitives: Vec<PrimitiveType>,
pub access_levels: Arc<AccessLevels<DefId>>,
// These are later on moved into `CACHEKEY`, leaving the map empty.
@ -124,7 +124,7 @@ pub struct Crate {
pub external_traits: FnvHashMap<DefId, Trait>,
}
struct CrateNum(ast::CrateNum);
struct CrateNum(def_id::CrateNum);
impl<'a, 'tcx> Clean<Crate> for visit_ast::RustdocVisitor<'a, 'tcx> {
fn clean(&self, cx: &DocContext) -> Crate {
@ -1159,7 +1159,7 @@ impl<'a, 'tcx> Clean<FnDecl> for (DefId, &'a ty::PolyFnSig<'tcx>) {
values: sig.0.inputs.iter().map(|t| {
Argument {
type_: t.clean(cx),
id: 0,
id: ast::CRATE_NODE_ID,
name: names.next().unwrap_or("".to_string()),
}
}).collect(),
@ -1808,7 +1808,7 @@ impl<'tcx> Clean<Type> for ty::Ty<'tcx> {
type_params: Vec::new(),
where_predicates: Vec::new()
},
decl: (cx.map.local_def_id(0), &fty.sig).clean(cx),
decl: (cx.map.local_def_id(ast::CRATE_NODE_ID), &fty.sig).clean(cx),
abi: fty.abi,
}),
ty::TyAdt(def, substs) => {
@ -2590,7 +2590,7 @@ impl Clean<Vec<Item>> for doctree::Import {
name: None,
attrs: self.attrs.clean(cx),
source: self.whence.clean(cx),
def_id: cx.map.local_def_id(0),
def_id: cx.map.local_def_id(ast::CRATE_NODE_ID),
visibility: self.vis.clean(cx),
stability: None,
deprecation: None,

View file

@ -13,7 +13,7 @@ use rustc_lint;
use rustc_driver::{driver, target_features, abort_on_err};
use rustc::dep_graph::DepGraph;
use rustc::session::{self, config};
use rustc::hir::def_id::DefId;
use rustc::hir::def_id::{CrateNum, DefId};
use rustc::middle::privacy::AccessLevels;
use rustc::ty::{self, TyCtxt};
use rustc::hir::map as hir_map;
@ -23,7 +23,7 @@ use rustc_trans::back::link;
use rustc_resolve as resolve;
use rustc_metadata::cstore::CStore;
use syntax::{ast, codemap};
use syntax::codemap;
use syntax::feature_gate::UnstableFeatures;
use errors;
use errors::emitter::ColorConfig;
@ -51,7 +51,7 @@ pub struct DocContext<'a, 'tcx: 'a> {
pub map: &'a hir_map::Map<'tcx>,
pub maybe_typed: MaybeTyped<'a, 'tcx>,
pub input: Input,
pub populated_crate_impls: RefCell<FnvHashSet<ast::CrateNum>>,
pub populated_crate_impls: RefCell<FnvHashSet<CrateNum>>,
pub deref_trait_did: Cell<Option<DefId>>,
pub deref_mut_trait_did: Cell<Option<DefId>>,
// Note that external items for which `doc(hidden)` applies to are shown as

View file

@ -21,6 +21,7 @@ use syntax::ptr::P;
use syntax_pos::{self, Span};
use rustc::hir;
use rustc::hir::def_id::CrateNum;
pub struct Module {
pub name: Option<Name>,
@ -53,7 +54,7 @@ impl Module {
pub fn new(name: Option<Name>) -> Module {
Module {
name : name,
id: 0,
id: ast::CRATE_NODE_ID,
vis: hir::Inherited,
stab: None,
depr: None,
@ -245,7 +246,7 @@ pub struct Macro {
pub struct ExternCrate {
pub name: Name,
pub cnum: ast::CrateNum,
pub cnum: CrateNum,
pub path: Option<String>,
pub vis: hir::Visibility,
pub attrs: hir::HirVec<ast::Attribute>,

View file

@ -18,8 +18,7 @@
use std::fmt;
use std::iter::repeat;
use rustc::middle::cstore::LOCAL_CRATE;
use rustc::hir::def_id::DefId;
use rustc::hir::def_id::{DefId, LOCAL_CRATE};
use syntax::abi::Abi;
use rustc::hir;

View file

@ -53,10 +53,9 @@ use std::sync::Arc;
use externalfiles::ExternalHtml;
use serialize::json::{ToJson, Json, as_json};
use syntax::{abi, ast};
use syntax::abi;
use syntax::feature_gate::UnstableFeatures;
use rustc::middle::cstore::LOCAL_CRATE;
use rustc::hir::def_id::{CRATE_DEF_INDEX, DefId};
use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId, LOCAL_CRATE};
use rustc::middle::privacy::AccessLevels;
use rustc::middle::stability;
use rustc::session::config::get_unstable_features_setting;
@ -246,10 +245,10 @@ pub struct Cache {
pub implementors: FnvHashMap<DefId, Vec<Implementor>>,
/// Cache of where external crate documentation can be found.
pub extern_locations: FnvHashMap<ast::CrateNum, (String, ExternalLocation)>,
pub extern_locations: FnvHashMap<CrateNum, (String, ExternalLocation)>,
/// Cache of where documentation for primitives can be found.
pub primitive_locations: FnvHashMap<clean::PrimitiveType, ast::CrateNum>,
pub primitive_locations: FnvHashMap<clean::PrimitiveType, CrateNum>,
// Note that external items for which `doc(hidden)` applies to are shown as
// non-reachable while local items aren't. This is because we're reusing

View file

@ -20,6 +20,7 @@ use syntax_pos::Span;
use rustc::hir::map as hir_map;
use rustc::hir::def::Def;
use rustc::hir::def_id::LOCAL_CRATE;
use rustc::middle::privacy::AccessLevel;
use rustc::util::nodemap::FnvHashSet;
@ -339,7 +340,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
let cstore = &self.cx.sess().cstore;
om.extern_crates.push(ExternCrate {
cnum: cstore.extern_mod_stmt_cnum(item.id)
.unwrap_or(ast::CrateNum::max_value()),
.unwrap_or(LOCAL_CRATE),
name: name,
path: p.map(|x|x.to_string()),
vis: item.vis.clone(),

View file

@ -11,9 +11,8 @@
use rustc::middle::cstore::{CrateStore, ChildItem, DefLike};
use rustc::middle::privacy::{AccessLevels, AccessLevel};
use rustc::hir::def::Def;
use rustc::hir::def_id::{CRATE_DEF_INDEX, DefId};
use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
use rustc::ty::Visibility;
use syntax::ast;
use std::cell::RefMut;
@ -42,7 +41,7 @@ impl<'a, 'b, 'tcx> LibEmbargoVisitor<'a, 'b, 'tcx> {
}
}
pub fn visit_lib(&mut self, cnum: ast::CrateNum) {
pub fn visit_lib(&mut self, cnum: CrateNum) {
let did = DefId { krate: cnum, index: CRATE_DEF_INDEX };
self.update(did, Some(AccessLevel::Public));
self.visit_mod(did);

View file

@ -45,8 +45,7 @@ Core encoding and decoding interfaces.
extern crate rustc_unicode;
extern crate collections;
pub use self::serialize::{Decoder, Encoder, Decodable, Encodable,
DecoderHelpers, EncoderHelpers};
pub use self::serialize::{Decoder, Encoder, Decodable, Encodable};
pub use self::serialize::{SpecializationError, SpecializedEncoder, SpecializedDecoder};
pub use self::serialize::{UseSpecializedEncodable, UseSpecializedDecodable};

View file

@ -593,50 +593,6 @@ impl<T:Decodable+Send+Sync> Decodable for Arc<T> {
}
}
// ___________________________________________________________________________
// Helper routines
pub trait EncoderHelpers: Encoder {
fn emit_from_vec<T, F>(&mut self, v: &[T], f: F)
-> Result<(), Self::Error>
where F: FnMut(&mut Self, &T) -> Result<(), Self::Error>;
}
impl<S:Encoder> EncoderHelpers for S {
fn emit_from_vec<T, F>(&mut self, v: &[T], mut f: F) -> Result<(), S::Error> where
F: FnMut(&mut S, &T) -> Result<(), S::Error>,
{
self.emit_seq(v.len(), |this| {
for (i, e) in v.iter().enumerate() {
this.emit_seq_elt(i, |this| {
f(this, e)
})?;
}
Ok(())
})
}
}
pub trait DecoderHelpers: Decoder {
fn read_to_vec<T, F>(&mut self, f: F)
-> Result<Vec<T>, Self::Error> where
F: FnMut(&mut Self) -> Result<T, Self::Error>;
}
impl<D: Decoder> DecoderHelpers for D {
fn read_to_vec<T, F>(&mut self, mut f: F) -> Result<Vec<T>, D::Error> where F:
FnMut(&mut D) -> Result<T, D::Error>,
{
self.read_seq(|this, len| {
let mut v = Vec::with_capacity(len);
for i in 0..len {
v.push(this.read_seq_elt(i, |this| f(this))?);
}
Ok(v)
})
}
}
// ___________________________________________________________________________
// Specialization-based interface for multi-dispatch Encodable/Decodable.

View file

@ -27,7 +27,9 @@ use tokenstream::{TokenTree};
use std::fmt;
use std::rc::Rc;
use serialize::{Encodable, Decodable, Encoder, Decoder};
use std::u32;
use serialize::{self, Encodable, Decodable, Encoder, Decoder};
/// A name is a part of an identifier, representing a string or gensym. It's
/// the result of interning.
@ -298,17 +300,43 @@ pub struct ParenthesizedParameterData {
pub output: Option<P<Ty>>,
}
pub type CrateNum = u32;
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, RustcEncodable, Hash, Debug)]
pub struct NodeId(u32);
pub type NodeId = u32;
impl NodeId {
pub fn new(x: usize) -> NodeId {
assert!(x < (u32::MAX as usize));
NodeId(x as u32)
}
pub fn from_u32(x: u32) -> NodeId {
NodeId(x)
}
pub fn as_usize(&self) -> usize {
self.0 as usize
}
pub fn as_u32(&self) -> u32 {
self.0
}
}
impl fmt::Display for NodeId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl serialize::UseSpecializedDecodable for NodeId {}
/// Node id used to represent the root of the crate.
pub const CRATE_NODE_ID: NodeId = 0;
pub const CRATE_NODE_ID: NodeId = NodeId(0);
/// When parsing and doing expansions, we initially give all AST nodes this AST
/// node value. Then later, in the renumber pass, we renumber them to have
/// small, positive ids.
pub const DUMMY_NODE_ID: NodeId = !0;
pub const DUMMY_NODE_ID: NodeId = NodeId(!0);
/// The AST represents all type param bounds as types.
/// typeck::collect::compute_bounds matches these against

View file

@ -895,7 +895,7 @@ pub fn find_repr_attrs(diagnostic: &Handler, attr: &Attribute) -> Vec<ReprAttr>
"packed" => Some(ReprPacked),
"simd" => Some(ReprSimd),
_ => match int_type_of_word(word) {
Some(ity) => Some(ReprInt(item.span, ity)),
Some(ity) => Some(ReprInt(ity)),
None => {
// Not a word we recognize
span_err!(diagnostic, item.span, E0552,
@ -939,7 +939,7 @@ fn int_type_of_word(s: &str) -> Option<IntType> {
#[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
pub enum ReprAttr {
ReprAny,
ReprInt(Span, IntType),
ReprInt(IntType),
ReprExtern,
ReprPacked,
ReprSimd,
@ -949,7 +949,7 @@ impl ReprAttr {
pub fn is_ffi_safe(&self) -> bool {
match *self {
ReprAny => false,
ReprInt(_sp, ity) => ity.is_ffi_safe(),
ReprInt(ity) => ity.is_ffi_safe(),
ReprExtern => true,
ReprPacked => false,
ReprSimd => true,

View file

@ -242,11 +242,11 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
while let Some(expansions) = expansions.pop() {
for (mark, expansion) in expansions.into_iter().rev() {
let expansion = expansion.fold_with(&mut placeholder_expander);
placeholder_expander.add(mark, expansion);
placeholder_expander.add(ast::NodeId::from_u32(mark), expansion);
}
}
placeholder_expander.remove(0)
placeholder_expander.remove(ast::NodeId::from_u32(0))
}
fn collect_invocations(&mut self, expansion: Expansion) -> (Expansion, Vec<Invocation>) {
@ -424,7 +424,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> {
expansion_kind: expansion_kind,
expansion_data: ExpansionData { mark: mark, ..self.cx.current_expansion.clone() },
});
placeholder(expansion_kind, mark.as_u32())
placeholder(expansion_kind, ast::NodeId::from_u32(mark.as_u32()))
}
fn collect_bang(

View file

@ -33,6 +33,7 @@
#![feature(unicode)]
#![feature(question_mark)]
#![feature(rustc_diagnostic_macros)]
#![feature(specialization)]
extern crate serialize;
extern crate term;

View file

@ -780,17 +780,17 @@ fn find_repr_type_name(diagnostic: &Handler, type_attrs: &[ast::Attribute]) -> &
attr::ReprAny | attr::ReprPacked | attr::ReprSimd => continue,
attr::ReprExtern => "i32",
attr::ReprInt(_, attr::SignedInt(ast::IntTy::Is)) => "isize",
attr::ReprInt(_, attr::SignedInt(ast::IntTy::I8)) => "i8",
attr::ReprInt(_, attr::SignedInt(ast::IntTy::I16)) => "i16",
attr::ReprInt(_, attr::SignedInt(ast::IntTy::I32)) => "i32",
attr::ReprInt(_, attr::SignedInt(ast::IntTy::I64)) => "i64",
attr::ReprInt(attr::SignedInt(ast::IntTy::Is)) => "isize",
attr::ReprInt(attr::SignedInt(ast::IntTy::I8)) => "i8",
attr::ReprInt(attr::SignedInt(ast::IntTy::I16)) => "i16",
attr::ReprInt(attr::SignedInt(ast::IntTy::I32)) => "i32",
attr::ReprInt(attr::SignedInt(ast::IntTy::I64)) => "i64",
attr::ReprInt(_, attr::UnsignedInt(ast::UintTy::Us)) => "usize",
attr::ReprInt(_, attr::UnsignedInt(ast::UintTy::U8)) => "u8",
attr::ReprInt(_, attr::UnsignedInt(ast::UintTy::U16)) => "u16",
attr::ReprInt(_, attr::UnsignedInt(ast::UintTy::U32)) => "u32",
attr::ReprInt(_, attr::UnsignedInt(ast::UintTy::U64)) => "u64",
attr::ReprInt(attr::UnsignedInt(ast::UintTy::Us)) => "usize",
attr::ReprInt(attr::UnsignedInt(ast::UintTy::U8)) => "u8",
attr::ReprInt(attr::UnsignedInt(ast::UintTy::U16)) => "u16",
attr::ReprInt(attr::UnsignedInt(ast::UintTy::U32)) => "u32",
attr::ReprInt(attr::UnsignedInt(ast::UintTy::U64)) => "u64",
}
}
}

View file

@ -28,6 +28,7 @@
#![feature(rustc_private)]
#![feature(staged_api)]
#![feature(question_mark)]
#![feature(specialization)]
use std::cell::{Cell, RefCell};
use std::ops::{Add, Sub};
@ -151,21 +152,7 @@ impl Encodable for Span {
}
}
impl Decodable for Span {
fn decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
d.read_struct("Span", 2, |d| {
let lo = d.read_struct_field("lo", 0, |d| {
BytePos::decode(d)
})?;
let hi = d.read_struct_field("hi", 1, |d| {
BytePos::decode(d)
})?;
Ok(mk_sp(lo, hi))
})
}
}
impl serialize::UseSpecializedDecodable for Span {}
fn default_span_debug(span: Span, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Span {{ lo: {:?}, hi: {:?}, expn_id: {:?} }}",