]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/decoder.rs
Fix invalid associated type rendering in rustdoc
[rust.git] / src / librustc_metadata / decoder.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // Decoding metadata from a single crate's metadata
12
13 use cstore::{self, CrateMetadata, MetadataBlob, NativeLibrary};
14 use schema::*;
15
16 use rustc::hir::map::{DefKey, DefPath, DefPathData};
17 use rustc::hir;
18
19 use rustc::middle::cstore::LinkagePreference;
20 use rustc::hir::def::{self, Def, CtorKind};
21 use rustc::hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
22 use rustc::middle::lang_items;
23 use rustc::session::Session;
24 use rustc::ty::{self, Ty, TyCtxt};
25 use rustc::ty::subst::Substs;
26
27 use rustc::mir::Mir;
28
29 use std::borrow::Cow;
30 use std::cell::Ref;
31 use std::collections::BTreeMap;
32 use std::io;
33 use std::mem;
34 use std::str;
35 use std::u32;
36
37 use rustc_serialize::{Decodable, Decoder, SpecializedDecoder, opaque};
38 use syntax::attr;
39 use syntax::ast;
40 use syntax::codemap;
41 use syntax::ext::base::MacroKind;
42 use syntax_pos::{self, Span, BytePos, Pos, DUMMY_SP, NO_EXPANSION};
43
44 pub struct DecodeContext<'a, 'tcx: 'a> {
45     opaque: opaque::Decoder<'a>,
46     cdata: Option<&'a CrateMetadata>,
47     sess: Option<&'a Session>,
48     tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
49
50     // Cache the last used filemap for translating spans as an optimization.
51     last_filemap_index: usize,
52
53     lazy_state: LazyState,
54 }
55
56 /// Abstract over the various ways one can create metadata decoders.
57 pub trait Metadata<'a, 'tcx>: Copy {
58     fn raw_bytes(self) -> &'a [u8];
59     fn cdata(self) -> Option<&'a CrateMetadata> { None }
60     fn sess(self) -> Option<&'a Session> { None }
61     fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> { None }
62
63     fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> {
64         let tcx = self.tcx();
65         DecodeContext {
66             opaque: opaque::Decoder::new(self.raw_bytes(), pos),
67             cdata: self.cdata(),
68             sess: self.sess().or(tcx.map(|tcx| tcx.sess)),
69             tcx: tcx,
70             last_filemap_index: 0,
71             lazy_state: LazyState::NoNode,
72         }
73     }
74 }
75
76 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob {
77     fn raw_bytes(self) -> &'a [u8] {
78         match *self {
79             MetadataBlob::Inflated(ref vec) => vec,
80             MetadataBlob::Archive(ref ar) => ar.as_slice(),
81             MetadataBlob::Raw(ref vec) => vec,
82         }
83     }
84 }
85
86 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a CrateMetadata {
87     fn raw_bytes(self) -> &'a [u8] {
88         self.blob.raw_bytes()
89     }
90     fn cdata(self) -> Option<&'a CrateMetadata> {
91         Some(self)
92     }
93 }
94
95 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, &'a Session) {
96     fn raw_bytes(self) -> &'a [u8] {
97         self.0.raw_bytes()
98     }
99     fn cdata(self) -> Option<&'a CrateMetadata> {
100         Some(self.0)
101     }
102     fn sess(self) -> Option<&'a Session> {
103         Some(&self.1)
104     }
105 }
106
107 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, TyCtxt<'a, 'tcx, 'tcx>) {
108     fn raw_bytes(self) -> &'a [u8] {
109         self.0.raw_bytes()
110     }
111     fn cdata(self) -> Option<&'a CrateMetadata> {
112         Some(self.0)
113     }
114     fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> {
115         Some(self.1)
116     }
117 }
118
119 impl<'a, 'tcx: 'a, T: Decodable> Lazy<T> {
120     pub fn decode<M: Metadata<'a, 'tcx>>(self, meta: M) -> T {
121         let mut dcx = meta.decoder(self.position);
122         dcx.lazy_state = LazyState::NodeStart(self.position);
123         T::decode(&mut dcx).unwrap()
124     }
125 }
126
127 impl<'a, 'tcx: 'a, T: Decodable> LazySeq<T> {
128     pub fn decode<M: Metadata<'a, 'tcx>>(self, meta: M) -> impl Iterator<Item = T> + 'a {
129         let mut dcx = meta.decoder(self.position);
130         dcx.lazy_state = LazyState::NodeStart(self.position);
131         (0..self.len).map(move |_| T::decode(&mut dcx).unwrap())
132     }
133 }
134
135 impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
136     pub fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
137         self.tcx.expect("missing TyCtxt in DecodeContext")
138     }
139
140     pub fn cdata(&self) -> &'a CrateMetadata {
141         self.cdata.expect("missing CrateMetadata in DecodeContext")
142     }
143
144     fn with_position<F: FnOnce(&mut Self) -> R, R>(&mut self, pos: usize, f: F) -> R {
145         let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
146         let old_opaque = mem::replace(&mut self.opaque, new_opaque);
147         let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode);
148         let r = f(self);
149         self.opaque = old_opaque;
150         self.lazy_state = old_state;
151         r
152     }
153
154     fn read_lazy_distance(&mut self, min_size: usize) -> Result<usize, <Self as Decoder>::Error> {
155         let distance = self.read_usize()?;
156         let position = match self.lazy_state {
157             LazyState::NoNode => bug!("read_lazy_distance: outside of a metadata node"),
158             LazyState::NodeStart(start) => {
159                 assert!(distance + min_size <= start);
160                 start - distance - min_size
161             }
162             LazyState::Previous(last_min_end) => last_min_end + distance,
163         };
164         self.lazy_state = LazyState::Previous(position + min_size);
165         Ok(position)
166     }
167 }
168
169 macro_rules! decoder_methods {
170     ($($name:ident -> $ty:ty;)*) => {
171         $(fn $name(&mut self) -> Result<$ty, Self::Error> {
172             self.opaque.$name()
173         })*
174     }
175 }
176
177 impl<'doc, 'tcx> Decoder for DecodeContext<'doc, 'tcx> {
178     type Error = <opaque::Decoder<'doc> as Decoder>::Error;
179
180     decoder_methods! {
181         read_nil -> ();
182
183         read_u128 -> u128;
184         read_u64 -> u64;
185         read_u32 -> u32;
186         read_u16 -> u16;
187         read_u8 -> u8;
188         read_usize -> usize;
189
190         read_i128 -> i128;
191         read_i64 -> i64;
192         read_i32 -> i32;
193         read_i16 -> i16;
194         read_i8 -> i8;
195         read_isize -> isize;
196
197         read_bool -> bool;
198         read_f64 -> f64;
199         read_f32 -> f32;
200         read_char -> char;
201         read_str -> Cow<str>;
202     }
203
204     fn error(&mut self, err: &str) -> Self::Error {
205         self.opaque.error(err)
206     }
207 }
208
209 impl<'a, 'tcx, T> SpecializedDecoder<Lazy<T>> for DecodeContext<'a, 'tcx> {
210     fn specialized_decode(&mut self) -> Result<Lazy<T>, Self::Error> {
211         Ok(Lazy::with_position(self.read_lazy_distance(Lazy::<T>::min_size())?))
212     }
213 }
214
215 impl<'a, 'tcx, T> SpecializedDecoder<LazySeq<T>> for DecodeContext<'a, 'tcx> {
216     fn specialized_decode(&mut self) -> Result<LazySeq<T>, Self::Error> {
217         let len = self.read_usize()?;
218         let position = if len == 0 {
219             0
220         } else {
221             self.read_lazy_distance(LazySeq::<T>::min_size(len))?
222         };
223         Ok(LazySeq::with_position_and_length(position, len))
224     }
225 }
226
227 impl<'a, 'tcx> SpecializedDecoder<CrateNum> for DecodeContext<'a, 'tcx> {
228     fn specialized_decode(&mut self) -> Result<CrateNum, Self::Error> {
229         let cnum = CrateNum::from_u32(u32::decode(self)?);
230         if cnum == LOCAL_CRATE {
231             Ok(self.cdata().cnum)
232         } else {
233             Ok(self.cdata().cnum_map.borrow()[cnum])
234         }
235     }
236 }
237
238 impl<'a, 'tcx> SpecializedDecoder<Span> for DecodeContext<'a, 'tcx> {
239     fn specialized_decode(&mut self) -> Result<Span, Self::Error> {
240         let lo = BytePos::decode(self)?;
241         let hi = BytePos::decode(self)?;
242
243         let sess = if let Some(sess) = self.sess {
244             sess
245         } else {
246             return Ok(Span { lo: lo, hi: hi, ctxt: NO_EXPANSION });
247         };
248
249         let (lo, hi) = if lo > hi {
250             // Currently macro expansion sometimes produces invalid Span values
251             // where lo > hi. In order not to crash the compiler when trying to
252             // translate these values, let's transform them into something we
253             // can handle (and which will produce useful debug locations at
254             // least some of the time).
255             // This workaround is only necessary as long as macro expansion is
256             // not fixed. FIXME(#23480)
257             (lo, lo)
258         } else {
259             (lo, hi)
260         };
261
262         let imported_filemaps = self.cdata().imported_filemaps(&sess.codemap());
263         let filemap = {
264             // Optimize for the case that most spans within a translated item
265             // originate from the same filemap.
266             let last_filemap = &imported_filemaps[self.last_filemap_index];
267
268             if lo >= last_filemap.original_start_pos && lo <= last_filemap.original_end_pos &&
269                hi >= last_filemap.original_start_pos &&
270                hi <= last_filemap.original_end_pos {
271                 last_filemap
272             } else {
273                 let mut a = 0;
274                 let mut b = imported_filemaps.len();
275
276                 while b - a > 1 {
277                     let m = (a + b) / 2;
278                     if imported_filemaps[m].original_start_pos > lo {
279                         b = m;
280                     } else {
281                         a = m;
282                     }
283                 }
284
285                 self.last_filemap_index = a;
286                 &imported_filemaps[a]
287             }
288         };
289
290         let lo = (lo - filemap.original_start_pos) + filemap.translated_filemap.start_pos;
291         let hi = (hi - filemap.original_start_pos) + filemap.translated_filemap.start_pos;
292
293         Ok(Span { lo: lo, hi: hi, ctxt: NO_EXPANSION })
294     }
295 }
296
297 // FIXME(#36588) These impls are horribly unsound as they allow
298 // the caller to pick any lifetime for 'tcx, including 'static,
299 // by using the unspecialized proxies to them.
300
301 impl<'a, 'tcx> SpecializedDecoder<Ty<'tcx>> for DecodeContext<'a, 'tcx> {
302     fn specialized_decode(&mut self) -> Result<Ty<'tcx>, Self::Error> {
303         let tcx = self.tcx();
304
305         // Handle shorthands first, if we have an usize > 0x80.
306         if self.opaque.data[self.opaque.position()] & 0x80 != 0 {
307             let pos = self.read_usize()?;
308             assert!(pos >= SHORTHAND_OFFSET);
309             let key = ty::CReaderCacheKey {
310                 cnum: self.cdata().cnum,
311                 pos: pos - SHORTHAND_OFFSET,
312             };
313             if let Some(ty) = tcx.rcache.borrow().get(&key).cloned() {
314                 return Ok(ty);
315             }
316
317             let ty = self.with_position(key.pos, Ty::decode)?;
318             tcx.rcache.borrow_mut().insert(key, ty);
319             Ok(ty)
320         } else {
321             Ok(tcx.mk_ty(ty::TypeVariants::decode(self)?))
322         }
323     }
324 }
325
326
327 impl<'a, 'tcx> SpecializedDecoder<ty::GenericPredicates<'tcx>> for DecodeContext<'a, 'tcx> {
328     fn specialized_decode(&mut self) -> Result<ty::GenericPredicates<'tcx>, Self::Error> {
329         Ok(ty::GenericPredicates {
330             parent: Decodable::decode(self)?,
331             predicates: (0..self.read_usize()?).map(|_| {
332                     // Handle shorthands first, if we have an usize > 0x80.
333                     if self.opaque.data[self.opaque.position()] & 0x80 != 0 {
334                         let pos = self.read_usize()?;
335                         assert!(pos >= SHORTHAND_OFFSET);
336                         let pos = pos - SHORTHAND_OFFSET;
337
338                         self.with_position(pos, ty::Predicate::decode)
339                     } else {
340                         ty::Predicate::decode(self)
341                     }
342                 })
343                 .collect::<Result<Vec<_>, _>>()?,
344         })
345     }
346 }
347
348 impl<'a, 'tcx> SpecializedDecoder<&'tcx Substs<'tcx>> for DecodeContext<'a, 'tcx> {
349     fn specialized_decode(&mut self) -> Result<&'tcx Substs<'tcx>, Self::Error> {
350         Ok(self.tcx().mk_substs((0..self.read_usize()?).map(|_| Decodable::decode(self)))?)
351     }
352 }
353
354 impl<'a, 'tcx> SpecializedDecoder<&'tcx ty::Region> for DecodeContext<'a, 'tcx> {
355     fn specialized_decode(&mut self) -> Result<&'tcx ty::Region, Self::Error> {
356         Ok(self.tcx().mk_region(Decodable::decode(self)?))
357     }
358 }
359
360 impl<'a, 'tcx> SpecializedDecoder<&'tcx ty::Slice<Ty<'tcx>>> for DecodeContext<'a, 'tcx> {
361     fn specialized_decode(&mut self) -> Result<&'tcx ty::Slice<Ty<'tcx>>, Self::Error> {
362         Ok(self.tcx().mk_type_list((0..self.read_usize()?).map(|_| Decodable::decode(self)))?)
363     }
364 }
365
366 impl<'a, 'tcx> SpecializedDecoder<&'tcx ty::AdtDef> for DecodeContext<'a, 'tcx> {
367     fn specialized_decode(&mut self) -> Result<&'tcx ty::AdtDef, Self::Error> {
368         let def_id = DefId::decode(self)?;
369         Ok(self.tcx().lookup_adt_def(def_id))
370     }
371 }
372
373 impl<'a, 'tcx> SpecializedDecoder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>
374     for DecodeContext<'a, 'tcx> {
375     fn specialized_decode(&mut self)
376         -> Result<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>, Self::Error> {
377         Ok(self.tcx().mk_existential_predicates((0..self.read_usize()?)
378                                                 .map(|_| Decodable::decode(self)))?)
379     }
380 }
381
382 impl<'a, 'tcx> MetadataBlob {
383     pub fn is_compatible(&self) -> bool {
384         self.raw_bytes().starts_with(METADATA_HEADER)
385     }
386
387     pub fn get_rustc_version(&self) -> String {
388         Lazy::with_position(METADATA_HEADER.len() + 4).decode(self)
389     }
390
391     pub fn get_root(&self) -> CrateRoot {
392         let slice = self.raw_bytes();
393         let offset = METADATA_HEADER.len();
394         let pos = (((slice[offset + 0] as u32) << 24) | ((slice[offset + 1] as u32) << 16) |
395                    ((slice[offset + 2] as u32) << 8) |
396                    ((slice[offset + 3] as u32) << 0)) as usize;
397         Lazy::with_position(pos).decode(self)
398     }
399
400     pub fn list_crate_metadata(&self, out: &mut io::Write) -> io::Result<()> {
401         write!(out, "=External Dependencies=\n")?;
402         let root = self.get_root();
403         for (i, dep) in root.crate_deps.decode(self).enumerate() {
404             write!(out, "{} {}-{}\n", i + 1, dep.name, dep.hash)?;
405         }
406         write!(out, "\n")?;
407         Ok(())
408     }
409 }
410
411 impl<'tcx> EntryKind<'tcx> {
412     fn to_def(&self, did: DefId) -> Option<Def> {
413         Some(match *self {
414             EntryKind::Const(_) => Def::Const(did),
415             EntryKind::AssociatedConst(..) => Def::AssociatedConst(did),
416             EntryKind::ImmStatic |
417             EntryKind::ForeignImmStatic => Def::Static(did, false),
418             EntryKind::MutStatic |
419             EntryKind::ForeignMutStatic => Def::Static(did, true),
420             EntryKind::Struct(_, _) => Def::Struct(did),
421             EntryKind::Union(_, _) => Def::Union(did),
422             EntryKind::Fn(_) |
423             EntryKind::ForeignFn(_) => Def::Fn(did),
424             EntryKind::Method(_) => Def::Method(did),
425             EntryKind::Type => Def::TyAlias(did),
426             EntryKind::AssociatedType(_) => Def::AssociatedTy(did),
427             EntryKind::Mod(_) => Def::Mod(did),
428             EntryKind::Variant(_) => Def::Variant(did),
429             EntryKind::Trait(_) => Def::Trait(did),
430             EntryKind::Enum(..) => Def::Enum(did),
431             EntryKind::MacroDef(_) => Def::Macro(did, MacroKind::Bang),
432
433             EntryKind::ForeignMod |
434             EntryKind::Impl(_) |
435             EntryKind::DefaultImpl(_) |
436             EntryKind::Field |
437             EntryKind::Closure(_) => return None,
438         })
439     }
440 }
441
442 impl<'a, 'tcx> CrateMetadata {
443     fn is_proc_macro(&self, id: DefIndex) -> bool {
444         self.proc_macros.is_some() && id != CRATE_DEF_INDEX
445     }
446
447     fn maybe_entry(&self, item_id: DefIndex) -> Option<Lazy<Entry<'tcx>>> {
448         assert!(!self.is_proc_macro(item_id));
449         self.root.index.lookup(self.blob.raw_bytes(), item_id)
450     }
451
452     fn entry(&self, item_id: DefIndex) -> Entry<'tcx> {
453         match self.maybe_entry(item_id) {
454             None => {
455                 bug!("entry: id not found: {:?} in crate {:?} with number {}",
456                      item_id,
457                      self.name,
458                      self.cnum)
459             }
460             Some(d) => d.decode(self),
461         }
462     }
463
464     fn local_def_id(&self, index: DefIndex) -> DefId {
465         DefId {
466             krate: self.cnum,
467             index: index,
468         }
469     }
470
471     fn item_name(&self, item_index: DefIndex) -> ast::Name {
472         self.def_key(item_index)
473             .disambiguated_data
474             .data
475             .get_opt_name()
476             .expect("no name in item_name")
477     }
478
479     pub fn get_def(&self, index: DefIndex) -> Option<Def> {
480         if !self.is_proc_macro(index) {
481             self.entry(index).kind.to_def(self.local_def_id(index))
482         } else {
483             let kind = self.proc_macros.as_ref().unwrap()[index.as_usize() - 1].1.kind();
484             Some(Def::Macro(self.local_def_id(index), kind))
485         }
486     }
487
488     pub fn get_span(&self, index: DefIndex, sess: &Session) -> Span {
489         match self.is_proc_macro(index) {
490             true => DUMMY_SP,
491             false => self.entry(index).span.decode((self, sess)),
492         }
493     }
494
495     pub fn get_trait_def(&self, item_id: DefIndex) -> ty::TraitDef {
496         let data = match self.entry(item_id).kind {
497             EntryKind::Trait(data) => data.decode(self),
498             _ => bug!(),
499         };
500
501         let def = ty::TraitDef::new(self.local_def_id(item_id),
502                                     data.unsafety,
503                                     data.paren_sugar,
504                                     self.def_path_table.def_path_hash(item_id));
505
506         if data.has_default_impl {
507             def.record_has_default_impl();
508         }
509
510         def
511     }
512
513     fn get_variant(&self,
514                    item: &Entry<'tcx>,
515                    index: DefIndex,
516                    tcx: TyCtxt<'a, 'tcx, 'tcx>)
517                    -> (ty::VariantDef, Option<DefIndex>) {
518         let data = match item.kind {
519             EntryKind::Variant(data) |
520             EntryKind::Struct(data, _) |
521             EntryKind::Union(data, _) => data.decode(self),
522             _ => bug!(),
523         };
524
525         if let ty::VariantDiscr::Explicit(def_id) = data.discr {
526             let result = data.evaluated_discr.map_or(Err(()), Ok);
527             tcx.maps.monomorphic_const_eval.borrow_mut().insert(def_id, result);
528         }
529
530         (ty::VariantDef {
531             did: self.local_def_id(data.struct_ctor.unwrap_or(index)),
532             name: self.item_name(index),
533             fields: item.children.decode(self).map(|index| {
534                 let f = self.entry(index);
535                 ty::FieldDef {
536                     did: self.local_def_id(index),
537                     name: self.item_name(index),
538                     vis: f.visibility.decode(self)
539                 }
540             }).collect(),
541             discr: data.discr,
542             ctor_kind: data.ctor_kind,
543         }, data.struct_ctor)
544     }
545
546     pub fn get_adt_def(&self,
547                        item_id: DefIndex,
548                        tcx: TyCtxt<'a, 'tcx, 'tcx>)
549                        -> &'tcx ty::AdtDef {
550         let item = self.entry(item_id);
551         let did = self.local_def_id(item_id);
552         let kind = match item.kind {
553             EntryKind::Enum(_) => ty::AdtKind::Enum,
554             EntryKind::Struct(_, _) => ty::AdtKind::Struct,
555             EntryKind::Union(_, _) => ty::AdtKind::Union,
556             _ => bug!("get_adt_def called on a non-ADT {:?}", did),
557         };
558         let variants = if let ty::AdtKind::Enum = kind {
559             item.children
560                 .decode(self)
561                 .map(|index| {
562                     let (variant, struct_ctor) =
563                         self.get_variant(&self.entry(index), index, tcx);
564                     assert_eq!(struct_ctor, None);
565                     variant
566                 })
567                 .collect()
568         } else {
569             let (variant, _struct_ctor) = self.get_variant(&item, item_id, tcx);
570             vec![variant]
571         };
572         let (kind, repr) = match item.kind {
573             EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr),
574             EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr),
575             EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr),
576             _ => bug!("get_adt_def called on a non-ADT {:?}", did),
577         };
578
579         tcx.alloc_adt_def(did, kind, variants, repr)
580     }
581
582     pub fn get_predicates(&self,
583                           item_id: DefIndex,
584                           tcx: TyCtxt<'a, 'tcx, 'tcx>)
585                           -> ty::GenericPredicates<'tcx> {
586         self.entry(item_id).predicates.unwrap().decode((self, tcx))
587     }
588
589     pub fn get_super_predicates(&self,
590                                 item_id: DefIndex,
591                                 tcx: TyCtxt<'a, 'tcx, 'tcx>)
592                                 -> ty::GenericPredicates<'tcx> {
593         match self.entry(item_id).kind {
594             EntryKind::Trait(data) => data.decode(self).super_predicates.decode((self, tcx)),
595             _ => bug!(),
596         }
597     }
598
599     pub fn get_generics(&self, item_id: DefIndex) -> ty::Generics {
600         self.entry(item_id).generics.unwrap().decode(self)
601     }
602
603     pub fn get_type(&self, id: DefIndex, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
604         self.entry(id).ty.unwrap().decode((self, tcx))
605     }
606
607     pub fn get_stability(&self, id: DefIndex) -> Option<attr::Stability> {
608         match self.is_proc_macro(id) {
609             true => None,
610             false => self.entry(id).stability.map(|stab| stab.decode(self)),
611         }
612     }
613
614     pub fn get_deprecation(&self, id: DefIndex) -> Option<attr::Deprecation> {
615         match self.is_proc_macro(id) {
616             true => None,
617             false => self.entry(id).deprecation.map(|depr| depr.decode(self)),
618         }
619     }
620
621     pub fn get_visibility(&self, id: DefIndex) -> ty::Visibility {
622         match self.is_proc_macro(id) {
623             true => ty::Visibility::Public,
624             false => self.entry(id).visibility.decode(self),
625         }
626     }
627
628     fn get_impl_data(&self, id: DefIndex) -> ImplData<'tcx> {
629         match self.entry(id).kind {
630             EntryKind::Impl(data) => data.decode(self),
631             _ => bug!(),
632         }
633     }
634
635     pub fn get_parent_impl(&self, id: DefIndex) -> Option<DefId> {
636         self.get_impl_data(id).parent_impl
637     }
638
639     pub fn get_impl_polarity(&self, id: DefIndex) -> hir::ImplPolarity {
640         self.get_impl_data(id).polarity
641     }
642
643     pub fn get_coerce_unsized_info(&self,
644                                    id: DefIndex)
645                                    -> Option<ty::adjustment::CoerceUnsizedInfo> {
646         self.get_impl_data(id).coerce_unsized_info
647     }
648
649     pub fn get_impl_trait(&self,
650                           id: DefIndex,
651                           tcx: TyCtxt<'a, 'tcx, 'tcx>)
652                           -> Option<ty::TraitRef<'tcx>> {
653         self.get_impl_data(id).trait_ref.map(|tr| tr.decode((self, tcx)))
654     }
655
656     /// Iterates over the language items in the given crate.
657     pub fn get_lang_items(&self) -> Vec<(DefIndex, usize)> {
658         self.root.lang_items.decode(self).collect()
659     }
660
661     /// Iterates over each child of the given item.
662     pub fn each_child_of_item<F>(&self, id: DefIndex, mut callback: F)
663         where F: FnMut(def::Export)
664     {
665         if let Some(ref proc_macros) = self.proc_macros {
666             if id == CRATE_DEF_INDEX {
667                 for (id, &(name, ref ext)) in proc_macros.iter().enumerate() {
668                     let def = Def::Macro(
669                         DefId {
670                             krate: self.cnum,
671                             index: DefIndex::new(id + 1)
672                         },
673                         ext.kind()
674                     );
675                     callback(def::Export { name: name, def: def, span: DUMMY_SP });
676                 }
677             }
678             return
679         }
680
681         // Find the item.
682         let item = match self.maybe_entry(id) {
683             None => return,
684             Some(item) => item.decode(self),
685         };
686
687         // Iterate over all children.
688         let macros_only = self.dep_kind.get().macros_only();
689         for child_index in item.children.decode(self) {
690             if macros_only {
691                 continue
692             }
693
694             // Get the item.
695             if let Some(child) = self.maybe_entry(child_index) {
696                 let child = child.decode(self);
697                 match child.kind {
698                     EntryKind::MacroDef(..) => {}
699                     _ if macros_only => continue,
700                     _ => {}
701                 }
702
703                 // Hand off the item to the callback.
704                 match child.kind {
705                     // FIXME(eddyb) Don't encode these in children.
706                     EntryKind::ForeignMod => {
707                         for child_index in child.children.decode(self) {
708                             if let Some(def) = self.get_def(child_index) {
709                                 callback(def::Export {
710                                     def: def,
711                                     name: self.item_name(child_index),
712                                     span: self.entry(child_index).span.decode(self),
713                                 });
714                             }
715                         }
716                         continue;
717                     }
718                     EntryKind::Impl(_) |
719                     EntryKind::DefaultImpl(_) => continue,
720
721                     _ => {}
722                 }
723
724                 let def_key = self.def_key(child_index);
725                 let span = child.span.decode(self);
726                 if let (Some(def), Some(name)) =
727                     (self.get_def(child_index), def_key.disambiguated_data.data.get_opt_name()) {
728                     callback(def::Export { def: def, name: name, span: span });
729                     // For non-reexport structs and variants add their constructors to children.
730                     // Reexport lists automatically contain constructors when necessary.
731                     match def {
732                         Def::Struct(..) => {
733                             if let Some(ctor_def_id) = self.get_struct_ctor_def_id(child_index) {
734                                 let ctor_kind = self.get_ctor_kind(child_index);
735                                 let ctor_def = Def::StructCtor(ctor_def_id, ctor_kind);
736                                 callback(def::Export { def: ctor_def, name: name, span: span });
737                             }
738                         }
739                         Def::Variant(def_id) => {
740                             // Braced variants, unlike structs, generate unusable names in
741                             // value namespace, they are reserved for possible future use.
742                             let ctor_kind = self.get_ctor_kind(child_index);
743                             let ctor_def = Def::VariantCtor(def_id, ctor_kind);
744                             callback(def::Export { def: ctor_def, name: name, span: span });
745                         }
746                         _ => {}
747                     }
748                 }
749             }
750         }
751
752         if let EntryKind::Mod(data) = item.kind {
753             for exp in data.decode(self).reexports.decode(self) {
754                 match exp.def {
755                     Def::Macro(..) => {}
756                     _ if macros_only => continue,
757                     _ => {}
758                 }
759                 callback(exp);
760             }
761         }
762     }
763
764     pub fn maybe_get_item_body(&self,
765                                tcx: TyCtxt<'a, 'tcx, 'tcx>,
766                                id: DefIndex)
767                                -> Option<&'tcx hir::Body> {
768         if self.is_proc_macro(id) { return None; }
769         self.entry(id).ast.map(|ast| {
770             let def_id = self.local_def_id(id);
771             let body = ast.decode(self).body.decode(self);
772             tcx.hir.intern_inlined_body(def_id, body)
773         })
774     }
775
776     pub fn item_body_tables(&self,
777                             id: DefIndex,
778                             tcx: TyCtxt<'a, 'tcx, 'tcx>)
779                             -> &'tcx ty::TypeckTables<'tcx> {
780         let ast = self.entry(id).ast.unwrap().decode(self);
781         tcx.alloc_tables(ast.tables.decode((self, tcx)))
782     }
783
784     pub fn item_body_nested_bodies(&self, id: DefIndex) -> BTreeMap<hir::BodyId, hir::Body> {
785         self.entry(id).ast.into_iter().flat_map(|ast| {
786             ast.decode(self).nested_bodies.decode(self).map(|body| (body.id(), body))
787         }).collect()
788     }
789
790     pub fn const_is_rvalue_promotable_to_static(&self, id: DefIndex) -> bool {
791         self.entry(id).ast.expect("const item missing `ast`")
792             .decode(self).rvalue_promotable_to_static
793     }
794
795     pub fn is_item_mir_available(&self, id: DefIndex) -> bool {
796         !self.is_proc_macro(id) &&
797         self.maybe_entry(id).and_then(|item| item.decode(self).mir).is_some()
798     }
799
800     pub fn maybe_get_item_mir(&self,
801                               tcx: TyCtxt<'a, 'tcx, 'tcx>,
802                               id: DefIndex)
803                               -> Option<Mir<'tcx>> {
804         match self.is_proc_macro(id) {
805             true => None,
806             false => self.entry(id).mir.map(|mir| mir.decode((self, tcx))),
807         }
808     }
809
810     pub fn mir_const_qualif(&self, id: DefIndex) -> u8 {
811         match self.entry(id).kind {
812             EntryKind::Const(qualif) |
813             EntryKind::AssociatedConst(AssociatedContainer::ImplDefault, qualif) |
814             EntryKind::AssociatedConst(AssociatedContainer::ImplFinal, qualif) => {
815                 qualif
816             }
817             _ => bug!(),
818         }
819     }
820
821     pub fn get_associated_item(&self, id: DefIndex) -> ty::AssociatedItem {
822         let item = self.entry(id);
823         let def_key = self.def_key(id);
824         let parent = self.local_def_id(def_key.parent.unwrap());
825         let name = def_key.disambiguated_data.data.get_opt_name().unwrap();
826
827         let (kind, container, has_self) = match item.kind {
828             EntryKind::AssociatedConst(container, _) => {
829                 (ty::AssociatedKind::Const, container, false)
830             }
831             EntryKind::Method(data) => {
832                 let data = data.decode(self);
833                 (ty::AssociatedKind::Method, data.container, data.has_self)
834             }
835             EntryKind::AssociatedType(container) => {
836                 (ty::AssociatedKind::Type, container, false)
837             }
838             _ => bug!()
839         };
840
841         ty::AssociatedItem {
842             name: name,
843             kind: kind,
844             vis: item.visibility.decode(self),
845             defaultness: container.defaultness(),
846             def_id: self.local_def_id(id),
847             container: container.with_def_id(parent),
848             method_has_self_argument: has_self
849         }
850     }
851
852     pub fn get_item_variances(&self, id: DefIndex) -> Vec<ty::Variance> {
853         self.entry(id).variances.decode(self).collect()
854     }
855
856     pub fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
857         match self.entry(node_id).kind {
858             EntryKind::Struct(data, _) |
859             EntryKind::Union(data, _) |
860             EntryKind::Variant(data) => data.decode(self).ctor_kind,
861             _ => CtorKind::Fictive,
862         }
863     }
864
865     pub fn get_struct_ctor_def_id(&self, node_id: DefIndex) -> Option<DefId> {
866         match self.entry(node_id).kind {
867             EntryKind::Struct(data, _) => {
868                 data.decode(self).struct_ctor.map(|index| self.local_def_id(index))
869             }
870             _ => None,
871         }
872     }
873
874     pub fn get_item_attrs(&self, node_id: DefIndex) -> Vec<ast::Attribute> {
875         if self.is_proc_macro(node_id) {
876             return Vec::new();
877         }
878         // The attributes for a tuple struct are attached to the definition, not the ctor;
879         // we assume that someone passing in a tuple struct ctor is actually wanting to
880         // look at the definition
881         let mut item = self.entry(node_id);
882         let def_key = self.def_key(node_id);
883         if def_key.disambiguated_data.data == DefPathData::StructCtor {
884             item = self.entry(def_key.parent.unwrap());
885         }
886         self.get_attributes(&item)
887     }
888
889     pub fn get_struct_field_names(&self, id: DefIndex) -> Vec<ast::Name> {
890         self.entry(id)
891             .children
892             .decode(self)
893             .map(|index| self.item_name(index))
894             .collect()
895     }
896
897     fn get_attributes(&self, item: &Entry<'tcx>) -> Vec<ast::Attribute> {
898         item.attributes
899             .decode(self)
900             .map(|mut attr| {
901                 // Need new unique IDs: old thread-local IDs won't map to new threads.
902                 attr.id = attr::mk_attr_id();
903                 attr
904             })
905             .collect()
906     }
907
908     // Translate a DefId from the current compilation environment to a DefId
909     // for an external crate.
910     fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
911         for (local, &global) in self.cnum_map.borrow().iter_enumerated() {
912             if global == did.krate {
913                 return Some(DefId {
914                     krate: local,
915                     index: did.index,
916                 });
917             }
918         }
919
920         None
921     }
922
923     pub fn get_inherent_implementations_for_type(&self, id: DefIndex) -> Vec<DefId> {
924         self.entry(id)
925             .inherent_impls
926             .decode(self)
927             .map(|index| self.local_def_id(index))
928             .collect()
929     }
930
931     pub fn get_implementations_for_trait(&self, filter: Option<DefId>, result: &mut Vec<DefId>) {
932         // Do a reverse lookup beforehand to avoid touching the crate_num
933         // hash map in the loop below.
934         let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) {
935             Some(Some(def_id)) => Some((def_id.krate.as_u32(), def_id.index)),
936             Some(None) => return,
937             None if self.proc_macros.is_some() => return,
938             None => None,
939         };
940
941         // FIXME(eddyb) Make this O(1) instead of O(n).
942         for trait_impls in self.root.impls.decode(self) {
943             if filter.is_some() && filter != Some(trait_impls.trait_id) {
944                 continue;
945             }
946
947             result.extend(trait_impls.impls.decode(self).map(|index| self.local_def_id(index)));
948
949             if filter.is_some() {
950                 break;
951             }
952         }
953     }
954
955     pub fn get_trait_of_item(&self, id: DefIndex) -> Option<DefId> {
956         self.def_key(id).parent.and_then(|parent_index| {
957             match self.entry(parent_index).kind {
958                 EntryKind::Trait(_) => Some(self.local_def_id(parent_index)),
959                 _ => None,
960             }
961         })
962     }
963
964
965     pub fn get_native_libraries(&self) -> Vec<NativeLibrary> {
966         self.root.native_libraries.decode(self).collect()
967     }
968
969     pub fn get_dylib_dependency_formats(&self) -> Vec<(CrateNum, LinkagePreference)> {
970         self.root
971             .dylib_dependency_formats
972             .decode(self)
973             .enumerate()
974             .flat_map(|(i, link)| {
975                 let cnum = CrateNum::new(i + 1);
976                 link.map(|link| (self.cnum_map.borrow()[cnum], link))
977             })
978             .collect()
979     }
980
981     pub fn get_missing_lang_items(&self) -> Vec<lang_items::LangItem> {
982         self.root.lang_items_missing.decode(self).collect()
983     }
984
985     pub fn get_fn_arg_names(&self, id: DefIndex) -> Vec<ast::Name> {
986         let arg_names = match self.entry(id).kind {
987             EntryKind::Fn(data) |
988             EntryKind::ForeignFn(data) => data.decode(self).arg_names,
989             EntryKind::Method(data) => data.decode(self).fn_data.arg_names,
990             _ => LazySeq::empty(),
991         };
992         arg_names.decode(self).collect()
993     }
994
995     pub fn get_exported_symbols(&self) -> Vec<DefId> {
996         self.exported_symbols.iter().map(|&index| self.local_def_id(index)).collect()
997     }
998
999     pub fn get_macro(&self, id: DefIndex) -> (ast::Name, MacroDef) {
1000         let entry = self.entry(id);
1001         match entry.kind {
1002             EntryKind::MacroDef(macro_def) => (self.item_name(id), macro_def.decode(self)),
1003             _ => bug!(),
1004         }
1005     }
1006
1007     pub fn is_const_fn(&self, id: DefIndex) -> bool {
1008         let constness = match self.entry(id).kind {
1009             EntryKind::Method(data) => data.decode(self).fn_data.constness,
1010             EntryKind::Fn(data) => data.decode(self).constness,
1011             _ => hir::Constness::NotConst,
1012         };
1013         constness == hir::Constness::Const
1014     }
1015
1016     pub fn is_foreign_item(&self, id: DefIndex) -> bool {
1017         match self.entry(id).kind {
1018             EntryKind::ForeignImmStatic |
1019             EntryKind::ForeignMutStatic |
1020             EntryKind::ForeignFn(_) => true,
1021             _ => false,
1022         }
1023     }
1024
1025     pub fn is_dllimport_foreign_item(&self, id: DefIndex) -> bool {
1026         self.dllimport_foreign_items.contains(&id)
1027     }
1028
1029     pub fn is_default_impl(&self, impl_id: DefIndex) -> bool {
1030         match self.entry(impl_id).kind {
1031             EntryKind::DefaultImpl(_) => true,
1032             _ => false,
1033         }
1034     }
1035
1036     pub fn closure_kind(&self, closure_id: DefIndex) -> ty::ClosureKind {
1037         match self.entry(closure_id).kind {
1038             EntryKind::Closure(data) => data.decode(self).kind,
1039             _ => bug!(),
1040         }
1041     }
1042
1043     pub fn closure_ty(&self,
1044                       closure_id: DefIndex,
1045                       tcx: TyCtxt<'a, 'tcx, 'tcx>)
1046                       -> ty::PolyFnSig<'tcx> {
1047         match self.entry(closure_id).kind {
1048             EntryKind::Closure(data) => data.decode(self).ty.decode((self, tcx)),
1049             _ => bug!(),
1050         }
1051     }
1052
1053     #[inline]
1054     pub fn def_key(&self, index: DefIndex) -> DefKey {
1055         self.def_path_table.def_key(index)
1056     }
1057
1058     // Returns the path leading to the thing with this `id`.
1059     pub fn def_path(&self, id: DefIndex) -> DefPath {
1060         debug!("def_path(id={:?})", id);
1061         DefPath::make(self.cnum, id, |parent| self.def_path_table.def_key(parent))
1062     }
1063
1064     #[inline]
1065     pub fn def_path_hash(&self, index: DefIndex) -> u64 {
1066         self.def_path_table.def_path_hash(index)
1067     }
1068
1069     /// Imports the codemap from an external crate into the codemap of the crate
1070     /// currently being compiled (the "local crate").
1071     ///
1072     /// The import algorithm works analogous to how AST items are inlined from an
1073     /// external crate's metadata:
1074     /// For every FileMap in the external codemap an 'inline' copy is created in the
1075     /// local codemap. The correspondence relation between external and local
1076     /// FileMaps is recorded in the `ImportedFileMap` objects returned from this
1077     /// function. When an item from an external crate is later inlined into this
1078     /// crate, this correspondence information is used to translate the span
1079     /// information of the inlined item so that it refers the correct positions in
1080     /// the local codemap (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1081     ///
1082     /// The import algorithm in the function below will reuse FileMaps already
1083     /// existing in the local codemap. For example, even if the FileMap of some
1084     /// source file of libstd gets imported many times, there will only ever be
1085     /// one FileMap object for the corresponding file in the local codemap.
1086     ///
1087     /// Note that imported FileMaps do not actually contain the source code of the
1088     /// file they represent, just information about length, line breaks, and
1089     /// multibyte characters. This information is enough to generate valid debuginfo
1090     /// for items inlined from other crates.
1091     pub fn imported_filemaps(&'a self,
1092                              local_codemap: &codemap::CodeMap)
1093                              -> Ref<'a, Vec<cstore::ImportedFileMap>> {
1094         {
1095             let filemaps = self.codemap_import_info.borrow();
1096             if !filemaps.is_empty() {
1097                 return filemaps;
1098             }
1099         }
1100
1101         let external_codemap = self.root.codemap.decode(self);
1102
1103         let imported_filemaps = external_codemap.map(|filemap_to_import| {
1104                 // Try to find an existing FileMap that can be reused for the filemap to
1105                 // be imported. A FileMap is reusable if it is exactly the same, just
1106                 // positioned at a different offset within the codemap.
1107                 let reusable_filemap = {
1108                     local_codemap.files
1109                         .borrow()
1110                         .iter()
1111                         .find(|fm| are_equal_modulo_startpos(&fm, &filemap_to_import))
1112                         .map(|rc| rc.clone())
1113                 };
1114
1115                 match reusable_filemap {
1116                     Some(fm) => {
1117
1118                         debug!("CrateMetaData::imported_filemaps reuse \
1119                                 filemap {:?} original (start_pos {:?} end_pos {:?}) \
1120                                 translated (start_pos {:?} end_pos {:?})",
1121                                filemap_to_import.name,
1122                                filemap_to_import.start_pos, filemap_to_import.end_pos,
1123                                fm.start_pos, fm.end_pos);
1124
1125                         cstore::ImportedFileMap {
1126                             original_start_pos: filemap_to_import.start_pos,
1127                             original_end_pos: filemap_to_import.end_pos,
1128                             translated_filemap: fm,
1129                         }
1130                     }
1131                     None => {
1132                         // We can't reuse an existing FileMap, so allocate a new one
1133                         // containing the information we need.
1134                         let syntax_pos::FileMap { name,
1135                                                   abs_path,
1136                                                   start_pos,
1137                                                   end_pos,
1138                                                   lines,
1139                                                   multibyte_chars,
1140                                                   .. } = filemap_to_import;
1141
1142                         let source_length = (end_pos - start_pos).to_usize();
1143
1144                         // Translate line-start positions and multibyte character
1145                         // position into frame of reference local to file.
1146                         // `CodeMap::new_imported_filemap()` will then translate those
1147                         // coordinates to their new global frame of reference when the
1148                         // offset of the FileMap is known.
1149                         let mut lines = lines.into_inner();
1150                         for pos in &mut lines {
1151                             *pos = *pos - start_pos;
1152                         }
1153                         let mut multibyte_chars = multibyte_chars.into_inner();
1154                         for mbc in &mut multibyte_chars {
1155                             mbc.pos = mbc.pos - start_pos;
1156                         }
1157
1158                         let local_version = local_codemap.new_imported_filemap(name,
1159                                                                                abs_path,
1160                                                                                source_length,
1161                                                                                lines,
1162                                                                                multibyte_chars);
1163                         debug!("CrateMetaData::imported_filemaps alloc \
1164                                 filemap {:?} original (start_pos {:?} end_pos {:?}) \
1165                                 translated (start_pos {:?} end_pos {:?})",
1166                                local_version.name, start_pos, end_pos,
1167                                local_version.start_pos, local_version.end_pos);
1168
1169                         cstore::ImportedFileMap {
1170                             original_start_pos: start_pos,
1171                             original_end_pos: end_pos,
1172                             translated_filemap: local_version,
1173                         }
1174                     }
1175                 }
1176             })
1177             .collect();
1178
1179         // This shouldn't borrow twice, but there is no way to downgrade RefMut to Ref.
1180         *self.codemap_import_info.borrow_mut() = imported_filemaps;
1181         self.codemap_import_info.borrow()
1182     }
1183 }
1184
1185 fn are_equal_modulo_startpos(fm1: &syntax_pos::FileMap, fm2: &syntax_pos::FileMap) -> bool {
1186     if fm1.byte_length() != fm2.byte_length() {
1187         return false;
1188     }
1189
1190     if fm1.name != fm2.name {
1191         return false;
1192     }
1193
1194     let lines1 = fm1.lines.borrow();
1195     let lines2 = fm2.lines.borrow();
1196
1197     if lines1.len() != lines2.len() {
1198         return false;
1199     }
1200
1201     for (&line1, &line2) in lines1.iter().zip(lines2.iter()) {
1202         if (line1 - fm1.start_pos) != (line2 - fm2.start_pos) {
1203             return false;
1204         }
1205     }
1206
1207     let multibytes1 = fm1.multibyte_chars.borrow();
1208     let multibytes2 = fm2.multibyte_chars.borrow();
1209
1210     if multibytes1.len() != multibytes2.len() {
1211         return false;
1212     }
1213
1214     for (mb1, mb2) in multibytes1.iter().zip(multibytes2.iter()) {
1215         if (mb1.bytes != mb2.bytes) || ((mb1.pos - fm1.start_pos) != (mb2.pos - fm2.start_pos)) {
1216             return false;
1217         }
1218     }
1219
1220     true
1221 }