]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/decoder.rs
Add lint for unknown feature attributes
[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, ForeignModule};
14 use schema::*;
15
16 use rustc_data_structures::sync::{Lrc, ReadGuard};
17 use rustc::hir::map::{DefKey, DefPath, DefPathData, DefPathHash,
18                       DisambiguatedDefPathData};
19 use rustc::hir;
20 use rustc::middle::cstore::LinkagePreference;
21 use rustc::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel};
22 use rustc::hir::def::{self, Def, CtorKind};
23 use rustc::hir::def_id::{CrateNum, DefId, DefIndex,
24                          CRATE_DEF_INDEX, LOCAL_CRATE, LocalDefId};
25 use rustc::ich::Fingerprint;
26 use rustc::middle::lang_items;
27 use rustc::mir::{self, interpret};
28 use rustc::mir::interpret::AllocDecodingSession;
29 use rustc::session::Session;
30 use rustc::ty::{self, Ty, TyCtxt};
31 use rustc::ty::codec::TyDecoder;
32 use rustc::mir::Mir;
33 use rustc::util::captures::Captures;
34
35 use std::io;
36 use std::mem;
37 use std::u32;
38
39 use rustc_serialize::{Decodable, Decoder, SpecializedDecoder, opaque};
40 use syntax::attr;
41 use syntax::ast::{self, Ident};
42 use syntax::codemap;
43 use syntax::symbol::InternedString;
44 use syntax::ext::base::MacroKind;
45 use syntax_pos::{self, Span, BytePos, Pos, DUMMY_SP, NO_EXPANSION};
46
47 pub struct DecodeContext<'a, 'tcx: 'a> {
48     opaque: opaque::Decoder<'a>,
49     cdata: Option<&'a CrateMetadata>,
50     sess: Option<&'a Session>,
51     tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
52
53     // Cache the last used filemap for translating spans as an optimization.
54     last_filemap_index: usize,
55
56     lazy_state: LazyState,
57
58     // Used for decoding interpret::AllocIds in a cached & thread-safe manner.
59     alloc_decoding_session: Option<AllocDecodingSession<'a>>,
60 }
61
62 /// Abstract over the various ways one can create metadata decoders.
63 pub trait Metadata<'a, 'tcx>: Copy {
64     fn raw_bytes(self) -> &'a [u8];
65     fn cdata(self) -> Option<&'a CrateMetadata> { None }
66     fn sess(self) -> Option<&'a Session> { None }
67     fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> { None }
68
69     fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> {
70         let tcx = self.tcx();
71         DecodeContext {
72             opaque: opaque::Decoder::new(self.raw_bytes(), pos),
73             cdata: self.cdata(),
74             sess: self.sess().or(tcx.map(|tcx| tcx.sess)),
75             tcx,
76             last_filemap_index: 0,
77             lazy_state: LazyState::NoNode,
78             alloc_decoding_session: self.cdata().map(|cdata| {
79                 cdata.alloc_decoding_state.new_decoding_session()
80             }),
81         }
82     }
83 }
84
85 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob {
86     fn raw_bytes(self) -> &'a [u8] {
87         &self.0
88     }
89 }
90
91
92 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a MetadataBlob, &'a Session) {
93     fn raw_bytes(self) -> &'a [u8] {
94         let (blob, _) = self;
95         &blob.0
96     }
97
98     fn sess(self) -> Option<&'a Session> {
99         let (_, sess) = self;
100         Some(sess)
101     }
102 }
103
104
105 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a CrateMetadata {
106     fn raw_bytes(self) -> &'a [u8] {
107         self.blob.raw_bytes()
108     }
109     fn cdata(self) -> Option<&'a CrateMetadata> {
110         Some(self)
111     }
112 }
113
114 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, &'a Session) {
115     fn raw_bytes(self) -> &'a [u8] {
116         self.0.raw_bytes()
117     }
118     fn cdata(self) -> Option<&'a CrateMetadata> {
119         Some(self.0)
120     }
121     fn sess(self) -> Option<&'a Session> {
122         Some(&self.1)
123     }
124 }
125
126 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, TyCtxt<'a, 'tcx, 'tcx>) {
127     fn raw_bytes(self) -> &'a [u8] {
128         self.0.raw_bytes()
129     }
130     fn cdata(self) -> Option<&'a CrateMetadata> {
131         Some(self.0)
132     }
133     fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> {
134         Some(self.1)
135     }
136 }
137
138 impl<'a, 'tcx: 'a, T: Decodable> Lazy<T> {
139     pub fn decode<M: Metadata<'a, 'tcx>>(self, meta: M) -> T {
140         let mut dcx = meta.decoder(self.position);
141         dcx.lazy_state = LazyState::NodeStart(self.position);
142         T::decode(&mut dcx).unwrap()
143     }
144 }
145
146 impl<'a, 'tcx: 'a, T: Decodable> LazySeq<T> {
147     pub fn decode<M: Metadata<'a, 'tcx>>(
148         self,
149         meta: M,
150     ) -> impl Iterator<Item = T> + Captures<'tcx> + 'a {
151         let mut dcx = meta.decoder(self.position);
152         dcx.lazy_state = LazyState::NodeStart(self.position);
153         (0..self.len).map(move |_| T::decode(&mut dcx).unwrap())
154     }
155 }
156
157 impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
158     pub fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
159         self.tcx.expect("missing TyCtxt in DecodeContext")
160     }
161
162     pub fn cdata(&self) -> &'a CrateMetadata {
163         self.cdata.expect("missing CrateMetadata in DecodeContext")
164     }
165
166     fn read_lazy_distance(&mut self, min_size: usize) -> Result<usize, <Self as Decoder>::Error> {
167         let distance = self.read_usize()?;
168         let position = match self.lazy_state {
169             LazyState::NoNode => bug!("read_lazy_distance: outside of a metadata node"),
170             LazyState::NodeStart(start) => {
171                 assert!(distance + min_size <= start);
172                 start - distance - min_size
173             }
174             LazyState::Previous(last_min_end) => last_min_end + distance,
175         };
176         self.lazy_state = LazyState::Previous(position + min_size);
177         Ok(position)
178     }
179 }
180
181 impl<'a, 'tcx: 'a> TyDecoder<'a, 'tcx> for DecodeContext<'a, 'tcx> {
182
183     #[inline]
184     fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
185         self.tcx.expect("missing TyCtxt in DecodeContext")
186     }
187
188     #[inline]
189     fn peek_byte(&self) -> u8 {
190         self.opaque.data[self.opaque.position()]
191     }
192
193     #[inline]
194     fn position(&self) -> usize {
195         self.opaque.position()
196     }
197
198     fn cached_ty_for_shorthand<F>(&mut self,
199                                   shorthand: usize,
200                                   or_insert_with: F)
201                                   -> Result<Ty<'tcx>, Self::Error>
202         where F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>
203     {
204         let tcx = self.tcx();
205
206         let key = ty::CReaderCacheKey {
207             cnum: self.cdata().cnum,
208             pos: shorthand,
209         };
210
211         if let Some(&ty) = tcx.rcache.borrow().get(&key) {
212             return Ok(ty);
213         }
214
215         let ty = or_insert_with(self)?;
216         tcx.rcache.borrow_mut().insert(key, ty);
217         Ok(ty)
218     }
219
220     fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
221         where F: FnOnce(&mut Self) -> R
222     {
223         let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
224         let old_opaque = mem::replace(&mut self.opaque, new_opaque);
225         let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode);
226         let r = f(self);
227         self.opaque = old_opaque;
228         self.lazy_state = old_state;
229         r
230     }
231
232     fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
233         if cnum == LOCAL_CRATE {
234             self.cdata().cnum
235         } else {
236             self.cdata().cnum_map[cnum]
237         }
238     }
239 }
240
241 impl<'a, 'tcx, T> SpecializedDecoder<Lazy<T>> for DecodeContext<'a, 'tcx> {
242     fn specialized_decode(&mut self) -> Result<Lazy<T>, Self::Error> {
243         Ok(Lazy::with_position(self.read_lazy_distance(Lazy::<T>::min_size())?))
244     }
245 }
246
247 impl<'a, 'tcx, T> SpecializedDecoder<LazySeq<T>> for DecodeContext<'a, 'tcx> {
248     fn specialized_decode(&mut self) -> Result<LazySeq<T>, Self::Error> {
249         let len = self.read_usize()?;
250         let position = if len == 0 {
251             0
252         } else {
253             self.read_lazy_distance(LazySeq::<T>::min_size(len))?
254         };
255         Ok(LazySeq::with_position_and_length(position, len))
256     }
257 }
258
259
260 impl<'a, 'tcx> SpecializedDecoder<DefId> for DecodeContext<'a, 'tcx> {
261     #[inline]
262     fn specialized_decode(&mut self) -> Result<DefId, Self::Error> {
263         let krate = CrateNum::decode(self)?;
264         let index = DefIndex::decode(self)?;
265
266         Ok(DefId {
267             krate,
268             index,
269         })
270     }
271 }
272
273 impl<'a, 'tcx> SpecializedDecoder<DefIndex> for DecodeContext<'a, 'tcx> {
274     #[inline]
275     fn specialized_decode(&mut self) -> Result<DefIndex, Self::Error> {
276         Ok(DefIndex::from_raw_u32(self.read_u32()?))
277     }
278 }
279
280 impl<'a, 'tcx> SpecializedDecoder<LocalDefId> for DecodeContext<'a, 'tcx> {
281     #[inline]
282     fn specialized_decode(&mut self) -> Result<LocalDefId, Self::Error> {
283         self.specialized_decode().map(|i| LocalDefId::from_def_id(i))
284     }
285 }
286
287 impl<'a, 'tcx> SpecializedDecoder<interpret::AllocId> for DecodeContext<'a, 'tcx> {
288     fn specialized_decode(&mut self) -> Result<interpret::AllocId, Self::Error> {
289         if let Some(alloc_decoding_session) = self.alloc_decoding_session {
290             alloc_decoding_session.decode_alloc_id(self)
291         } else {
292             bug!("Attempting to decode interpret::AllocId without CrateMetadata")
293         }
294     }
295 }
296
297 impl<'a, 'tcx> SpecializedDecoder<Span> for DecodeContext<'a, 'tcx> {
298     fn specialized_decode(&mut self) -> Result<Span, Self::Error> {
299         let tag = u8::decode(self)?;
300
301         if tag == TAG_INVALID_SPAN {
302             return Ok(DUMMY_SP)
303         }
304
305         debug_assert_eq!(tag, TAG_VALID_SPAN);
306
307         let lo = BytePos::decode(self)?;
308         let len = BytePos::decode(self)?;
309         let hi = lo + len;
310
311         let sess = if let Some(sess) = self.sess {
312             sess
313         } else {
314             bug!("Cannot decode Span without Session.")
315         };
316
317         let imported_filemaps = self.cdata().imported_filemaps(&sess.codemap());
318         let filemap = {
319             // Optimize for the case that most spans within a translated item
320             // originate from the same filemap.
321             let last_filemap = &imported_filemaps[self.last_filemap_index];
322
323             if lo >= last_filemap.original_start_pos &&
324                lo <= last_filemap.original_end_pos {
325                 last_filemap
326             } else {
327                 let mut a = 0;
328                 let mut b = imported_filemaps.len();
329
330                 while b - a > 1 {
331                     let m = (a + b) / 2;
332                     if imported_filemaps[m].original_start_pos > lo {
333                         b = m;
334                     } else {
335                         a = m;
336                     }
337                 }
338
339                 self.last_filemap_index = a;
340                 &imported_filemaps[a]
341             }
342         };
343
344         // Make sure our binary search above is correct.
345         debug_assert!(lo >= filemap.original_start_pos &&
346                       lo <= filemap.original_end_pos);
347
348         // Make sure we correctly filtered out invalid spans during encoding
349         debug_assert!(hi >= filemap.original_start_pos &&
350                       hi <= filemap.original_end_pos);
351
352         let lo = (lo + filemap.translated_filemap.start_pos) - filemap.original_start_pos;
353         let hi = (hi + filemap.translated_filemap.start_pos) - filemap.original_start_pos;
354
355         Ok(Span::new(lo, hi, NO_EXPANSION))
356     }
357 }
358
359 impl<'a, 'tcx> SpecializedDecoder<Fingerprint> for DecodeContext<'a, 'tcx> {
360     fn specialized_decode(&mut self) -> Result<Fingerprint, Self::Error> {
361         Fingerprint::decode_opaque(&mut self.opaque)
362     }
363 }
364
365 impl<'a, 'tcx, T: Decodable> SpecializedDecoder<mir::ClearCrossCrate<T>>
366 for DecodeContext<'a, 'tcx> {
367     #[inline]
368     fn specialized_decode(&mut self) -> Result<mir::ClearCrossCrate<T>, Self::Error> {
369         Ok(mir::ClearCrossCrate::Clear)
370     }
371 }
372
373 implement_ty_decoder!( DecodeContext<'a, 'tcx> );
374
375 impl<'a, 'tcx> MetadataBlob {
376     pub fn is_compatible(&self) -> bool {
377         self.raw_bytes().starts_with(METADATA_HEADER)
378     }
379
380     pub fn get_rustc_version(&self) -> String {
381         Lazy::with_position(METADATA_HEADER.len() + 4).decode(self)
382     }
383
384     pub fn get_root(&self) -> CrateRoot {
385         let slice = self.raw_bytes();
386         let offset = METADATA_HEADER.len();
387         let pos = (((slice[offset + 0] as u32) << 24) | ((slice[offset + 1] as u32) << 16) |
388                    ((slice[offset + 2] as u32) << 8) |
389                    ((slice[offset + 3] as u32) << 0)) as usize;
390         Lazy::with_position(pos).decode(self)
391     }
392
393     pub fn list_crate_metadata(&self,
394                                out: &mut dyn io::Write) -> io::Result<()> {
395         write!(out, "=External Dependencies=\n")?;
396         let root = self.get_root();
397         for (i, dep) in root.crate_deps
398                             .decode(self)
399                             .enumerate() {
400             write!(out, "{} {}-{}\n", i + 1, dep.name, dep.hash)?;
401         }
402         write!(out, "\n")?;
403         Ok(())
404     }
405 }
406
407 impl<'tcx> EntryKind<'tcx> {
408     fn to_def(&self, did: DefId) -> Option<Def> {
409         Some(match *self {
410             EntryKind::Const(..) => Def::Const(did),
411             EntryKind::AssociatedConst(..) => Def::AssociatedConst(did),
412             EntryKind::ImmStatic |
413             EntryKind::ForeignImmStatic => Def::Static(did, false),
414             EntryKind::MutStatic |
415             EntryKind::ForeignMutStatic => Def::Static(did, true),
416             EntryKind::Struct(_, _) => Def::Struct(did),
417             EntryKind::Union(_, _) => Def::Union(did),
418             EntryKind::Fn(_) |
419             EntryKind::ForeignFn(_) => Def::Fn(did),
420             EntryKind::Method(_) => Def::Method(did),
421             EntryKind::Type => Def::TyAlias(did),
422             EntryKind::Existential => Def::Existential(did),
423             EntryKind::AssociatedType(_) => Def::AssociatedTy(did),
424             EntryKind::AssociatedExistential(_) => Def::AssociatedExistential(did),
425             EntryKind::Mod(_) => Def::Mod(did),
426             EntryKind::Variant(_) => Def::Variant(did),
427             EntryKind::Trait(_) => Def::Trait(did),
428             EntryKind::Enum(..) => Def::Enum(did),
429             EntryKind::MacroDef(_) => Def::Macro(did, MacroKind::Bang),
430             EntryKind::GlobalAsm => Def::GlobalAsm(did),
431             EntryKind::ForeignType => Def::TyForeign(did),
432
433             EntryKind::ForeignMod |
434             EntryKind::Impl(_) |
435             EntryKind::Field |
436             EntryKind::Generator(_) |
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,
468         }
469     }
470
471     pub fn item_name(&self, item_index: DefIndex) -> InternedString {
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.to_proc_macro_index()].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, sess: &Session) -> ty::TraitDef {
496         let data = match self.entry(item_id).kind {
497             EntryKind::Trait(data) => data.decode((self, sess)),
498             _ => bug!(),
499         };
500
501         ty::TraitDef::new(self.local_def_id(item_id),
502                           data.unsafety,
503                           data.paren_sugar,
504                           data.has_auto_impl,
505                           self.def_path_table.def_path_hash(item_id))
506     }
507
508     fn get_variant(&self, item: &Entry, index: DefIndex) -> ty::VariantDef {
509         let data = match item.kind {
510             EntryKind::Variant(data) |
511             EntryKind::Struct(data, _) |
512             EntryKind::Union(data, _) => data.decode(self),
513             _ => bug!(),
514         };
515
516         ty::VariantDef {
517             did: self.local_def_id(data.struct_ctor.unwrap_or(index)),
518             name: self.item_name(index).as_symbol(),
519             fields: item.children.decode(self).map(|index| {
520                 let f = self.entry(index);
521                 ty::FieldDef {
522                     did: self.local_def_id(index),
523                     ident: Ident::from_interned_str(self.item_name(index)),
524                     vis: f.visibility.decode(self)
525                 }
526             }).collect(),
527             discr: data.discr,
528             ctor_kind: data.ctor_kind,
529         }
530     }
531
532     pub fn get_adt_def(&self,
533                        item_id: DefIndex,
534                        tcx: TyCtxt<'a, 'tcx, 'tcx>)
535                        -> &'tcx ty::AdtDef {
536         let item = self.entry(item_id);
537         let did = self.local_def_id(item_id);
538
539         let (kind, repr) = match item.kind {
540             EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr),
541             EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr),
542             EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr),
543             _ => bug!("get_adt_def called on a non-ADT {:?}", did),
544         };
545
546         let variants = if let ty::AdtKind::Enum = kind {
547             item.children
548                 .decode(self)
549                 .map(|index| {
550                     self.get_variant(&self.entry(index), index)
551                 })
552                 .collect()
553         } else {
554             vec![self.get_variant(&item, item_id)]
555         };
556
557         tcx.alloc_adt_def(did, kind, variants, repr)
558     }
559
560     pub fn get_predicates(&self,
561                           item_id: DefIndex,
562                           tcx: TyCtxt<'a, 'tcx, 'tcx>)
563                           -> ty::GenericPredicates<'tcx> {
564         self.entry(item_id).predicates.unwrap().decode((self, tcx))
565     }
566
567     pub fn get_predicates_defined_on(&self,
568                                    item_id: DefIndex,
569                                    tcx: TyCtxt<'a, 'tcx, 'tcx>)
570                                    -> ty::GenericPredicates<'tcx> {
571         self.entry(item_id).predicates_defined_on.unwrap().decode((self, tcx))
572     }
573
574     pub fn get_super_predicates(&self,
575                                 item_id: DefIndex,
576                                 tcx: TyCtxt<'a, 'tcx, 'tcx>)
577                                 -> ty::GenericPredicates<'tcx> {
578         match self.entry(item_id).kind {
579             EntryKind::Trait(data) => data.decode(self).super_predicates.decode((self, tcx)),
580             _ => bug!(),
581         }
582     }
583
584     pub fn get_generics(&self,
585                         item_id: DefIndex,
586                         sess: &Session)
587                         -> ty::Generics {
588         self.entry(item_id).generics.unwrap().decode((self, sess))
589     }
590
591     pub fn get_type(&self, id: DefIndex, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
592         self.entry(id).ty.unwrap().decode((self, tcx))
593     }
594
595     pub fn get_stability(&self, id: DefIndex) -> Option<attr::Stability> {
596         match self.is_proc_macro(id) {
597             true => None,
598             false => self.entry(id).stability.map(|stab| stab.decode(self)),
599         }
600     }
601
602     pub fn get_deprecation(&self, id: DefIndex) -> Option<attr::Deprecation> {
603         match self.is_proc_macro(id) {
604             true => None,
605             false => self.entry(id).deprecation.map(|depr| depr.decode(self)),
606         }
607     }
608
609     pub fn get_visibility(&self, id: DefIndex) -> ty::Visibility {
610         match self.is_proc_macro(id) {
611             true => ty::Visibility::Public,
612             false => self.entry(id).visibility.decode(self),
613         }
614     }
615
616     fn get_impl_data(&self, id: DefIndex) -> ImplData<'tcx> {
617         match self.entry(id).kind {
618             EntryKind::Impl(data) => data.decode(self),
619             _ => bug!(),
620         }
621     }
622
623     pub fn get_parent_impl(&self, id: DefIndex) -> Option<DefId> {
624         self.get_impl_data(id).parent_impl
625     }
626
627     pub fn get_impl_polarity(&self, id: DefIndex) -> hir::ImplPolarity {
628         self.get_impl_data(id).polarity
629     }
630
631     pub fn get_impl_defaultness(&self, id: DefIndex) -> hir::Defaultness {
632         self.get_impl_data(id).defaultness
633     }
634
635     pub fn get_coerce_unsized_info(&self,
636                                    id: DefIndex)
637                                    -> Option<ty::adjustment::CoerceUnsizedInfo> {
638         self.get_impl_data(id).coerce_unsized_info
639     }
640
641     pub fn get_impl_trait(&self,
642                           id: DefIndex,
643                           tcx: TyCtxt<'a, 'tcx, 'tcx>)
644                           -> Option<ty::TraitRef<'tcx>> {
645         self.get_impl_data(id).trait_ref.map(|tr| tr.decode((self, tcx)))
646     }
647
648     /// Iterates over all the stability attributes in the given crate.
649     pub fn get_lib_features(&self) -> Vec<(ast::Name, Option<ast::Name>)> {
650         self.root
651             .lib_features
652             .decode(self)
653             .collect()
654     }
655
656     /// Iterates over the language items in the given crate.
657     pub fn get_lang_items(&self) -> Vec<(DefId, usize)> {
658         self.root
659             .lang_items
660             .decode(self)
661             .map(|(def_index, index)| (self.local_def_id(def_index), index))
662             .collect()
663     }
664
665     /// Iterates over each child of the given item.
666     pub fn each_child_of_item<F>(&self, id: DefIndex, mut callback: F, sess: &Session)
667         where F: FnMut(def::Export)
668     {
669         if let Some(ref proc_macros) = self.proc_macros {
670             if id == CRATE_DEF_INDEX {
671                 for (id, &(name, ref ext)) in proc_macros.iter().enumerate() {
672                     let def = Def::Macro(
673                         DefId {
674                             krate: self.cnum,
675                             index: DefIndex::from_proc_macro_index(id),
676                         },
677                         ext.kind()
678                     );
679                     let ident = Ident::with_empty_ctxt(name);
680                     callback(def::Export {
681                         ident: ident,
682                         def: def,
683                         vis: ty::Visibility::Public,
684                         span: DUMMY_SP,
685                     });
686                 }
687             }
688             return
689         }
690
691         // Find the item.
692         let item = match self.maybe_entry(id) {
693             None => return,
694             Some(item) => item.decode((self, sess)),
695         };
696
697         // Iterate over all children.
698         let macros_only = self.dep_kind.lock().macros_only();
699         for child_index in item.children.decode((self, sess)) {
700             if macros_only {
701                 continue
702             }
703
704             // Get the item.
705             if let Some(child) = self.maybe_entry(child_index) {
706                 let child = child.decode((self, sess));
707                 match child.kind {
708                     EntryKind::MacroDef(..) => {}
709                     _ if macros_only => continue,
710                     _ => {}
711                 }
712
713                 // Hand off the item to the callback.
714                 match child.kind {
715                     // FIXME(eddyb) Don't encode these in children.
716                     EntryKind::ForeignMod => {
717                         for child_index in child.children.decode((self, sess)) {
718                             if let Some(def) = self.get_def(child_index) {
719                                 callback(def::Export {
720                                     def,
721                                     ident: Ident::from_interned_str(self.item_name(child_index)),
722                                     vis: self.get_visibility(child_index),
723                                     span: self.entry(child_index).span.decode((self, sess)),
724                                 });
725                             }
726                         }
727                         continue;
728                     }
729                     EntryKind::Impl(_) => continue,
730
731                     _ => {}
732                 }
733
734                 let def_key = self.def_key(child_index);
735                 let span = child.span.decode((self, sess));
736                 if let (Some(def), Some(name)) =
737                     (self.get_def(child_index), def_key.disambiguated_data.data.get_opt_name()) {
738                     let ident = Ident::from_interned_str(name);
739                     let vis = self.get_visibility(child_index);
740                     callback(def::Export { def, ident, vis, span });
741                     // For non-re-export structs and variants add their constructors to children.
742                     // Re-export lists automatically contain constructors when necessary.
743                     match def {
744                         Def::Struct(..) => {
745                             if let Some(ctor_def_id) = self.get_struct_ctor_def_id(child_index) {
746                                 let ctor_kind = self.get_ctor_kind(child_index);
747                                 let ctor_def = Def::StructCtor(ctor_def_id, ctor_kind);
748                                 callback(def::Export {
749                                     def: ctor_def,
750                                     vis: self.get_visibility(ctor_def_id.index),
751                                     ident, span,
752                                 });
753                             }
754                         }
755                         Def::Variant(def_id) => {
756                             // Braced variants, unlike structs, generate unusable names in
757                             // value namespace, they are reserved for possible future use.
758                             let ctor_kind = self.get_ctor_kind(child_index);
759                             let ctor_def = Def::VariantCtor(def_id, ctor_kind);
760                             let vis = self.get_visibility(child_index);
761                             callback(def::Export { def: ctor_def, ident, vis, span });
762                         }
763                         _ => {}
764                     }
765                 }
766             }
767         }
768
769         if let EntryKind::Mod(data) = item.kind {
770             for exp in data.decode((self, sess)).reexports.decode((self, sess)) {
771                 match exp.def {
772                     Def::Macro(..) => {}
773                     _ if macros_only => continue,
774                     _ => {}
775                 }
776                 callback(exp);
777             }
778         }
779     }
780
781     pub fn const_is_rvalue_promotable_to_static(&self, id: DefIndex) -> bool {
782         match self.entry(id).kind {
783             EntryKind::AssociatedConst(_, data, _) |
784             EntryKind::Const(data, _) => data.ast_promotable,
785             _ => bug!(),
786         }
787     }
788
789     pub fn is_item_mir_available(&self, id: DefIndex) -> bool {
790         !self.is_proc_macro(id) &&
791         self.maybe_entry(id).and_then(|item| item.decode(self).mir).is_some()
792     }
793
794     pub fn maybe_get_optimized_mir(&self,
795                                    tcx: TyCtxt<'a, 'tcx, 'tcx>,
796                                    id: DefIndex)
797                                    -> Option<Mir<'tcx>> {
798         match self.is_proc_macro(id) {
799             true => None,
800             false => self.entry(id).mir.map(|mir| mir.decode((self, tcx))),
801         }
802     }
803
804     pub fn mir_const_qualif(&self, id: DefIndex) -> u8 {
805         match self.entry(id).kind {
806             EntryKind::Const(qualif, _) |
807             EntryKind::AssociatedConst(AssociatedContainer::ImplDefault, qualif, _) |
808             EntryKind::AssociatedConst(AssociatedContainer::ImplFinal, qualif, _) => {
809                 qualif.mir
810             }
811             _ => bug!(),
812         }
813     }
814
815     pub fn get_associated_item(&self, id: DefIndex) -> ty::AssociatedItem {
816         let item = self.entry(id);
817         let def_key = self.def_key(id);
818         let parent = self.local_def_id(def_key.parent.unwrap());
819         let name = def_key.disambiguated_data.data.get_opt_name().unwrap();
820
821         let (kind, container, has_self) = match item.kind {
822             EntryKind::AssociatedConst(container, _, _) => {
823                 (ty::AssociatedKind::Const, container, false)
824             }
825             EntryKind::Method(data) => {
826                 let data = data.decode(self);
827                 (ty::AssociatedKind::Method, data.container, data.has_self)
828             }
829             EntryKind::AssociatedType(container) => {
830                 (ty::AssociatedKind::Type, container, false)
831             }
832             _ => bug!("cannot get associated-item of `{:?}`", def_key)
833         };
834
835         ty::AssociatedItem {
836             ident: Ident::from_interned_str(name),
837             kind,
838             vis: item.visibility.decode(self),
839             defaultness: container.defaultness(),
840             def_id: self.local_def_id(id),
841             container: container.with_def_id(parent),
842             method_has_self_argument: has_self
843         }
844     }
845
846     pub fn get_item_variances(&self, id: DefIndex) -> Vec<ty::Variance> {
847         self.entry(id).variances.decode(self).collect()
848     }
849
850     pub fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
851         match self.entry(node_id).kind {
852             EntryKind::Struct(data, _) |
853             EntryKind::Union(data, _) |
854             EntryKind::Variant(data) => data.decode(self).ctor_kind,
855             _ => CtorKind::Fictive,
856         }
857     }
858
859     pub fn get_struct_ctor_def_id(&self, node_id: DefIndex) -> Option<DefId> {
860         match self.entry(node_id).kind {
861             EntryKind::Struct(data, _) => {
862                 data.decode(self).struct_ctor.map(|index| self.local_def_id(index))
863             }
864             _ => None,
865         }
866     }
867
868     pub fn get_item_attrs(&self, node_id: DefIndex, sess: &Session) -> Lrc<[ast::Attribute]> {
869         if self.is_proc_macro(node_id) {
870             return Lrc::new([]);
871         }
872
873         // The attributes for a tuple struct are attached to the definition, not the ctor;
874         // we assume that someone passing in a tuple struct ctor is actually wanting to
875         // look at the definition
876         let def_key = self.def_key(node_id);
877         let item_id = if def_key.disambiguated_data.data == DefPathData::StructCtor {
878             def_key.parent.unwrap()
879         } else {
880             node_id
881         };
882
883         let item = self.entry(item_id);
884         Lrc::from(self.get_attributes(&item, sess))
885     }
886
887     pub fn get_struct_field_names(&self, id: DefIndex) -> Vec<ast::Name> {
888         self.entry(id)
889             .children
890             .decode(self)
891             .map(|index| self.item_name(index).as_symbol())
892             .collect()
893     }
894
895     fn get_attributes(&self, item: &Entry<'tcx>, sess: &Session) -> Vec<ast::Attribute> {
896         item.attributes
897             .decode((self, sess))
898             .map(|mut attr| {
899                 // Need new unique IDs: old thread-local IDs won't map to new threads.
900                 attr.id = attr::mk_attr_id();
901                 attr
902             })
903             .collect()
904     }
905
906     // Translate a DefId from the current compilation environment to a DefId
907     // for an external crate.
908     fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
909         for (local, &global) in self.cnum_map.iter_enumerated() {
910             if global == did.krate {
911                 return Some(DefId {
912                     krate: local,
913                     index: did.index,
914                 });
915             }
916         }
917
918         None
919     }
920
921     pub fn get_inherent_implementations_for_type(&self, id: DefIndex) -> Vec<DefId> {
922         self.entry(id)
923             .inherent_impls
924             .decode(self)
925             .map(|index| self.local_def_id(index))
926             .collect()
927     }
928
929     pub fn get_implementations_for_trait(&self,
930                                          filter: Option<DefId>,
931                                          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         if let Some(filter) = filter {
942             if let Some(impls) = self.trait_impls
943                                      .get(&filter) {
944                 result.extend(impls.decode(self).map(|idx| self.local_def_id(idx)));
945             }
946         } else {
947             for impls in self.trait_impls.values() {
948                 result.extend(impls.decode(self).map(|idx| self.local_def_id(idx)));
949             }
950         }
951     }
952
953     pub fn get_trait_of_item(&self, id: DefIndex) -> Option<DefId> {
954         let def_key = self.def_key(id);
955         match def_key.disambiguated_data.data {
956             DefPathData::TypeNs(..) | DefPathData::ValueNs(..) => (),
957             // Not an associated item
958             _ => return None,
959         }
960         def_key.parent.and_then(|parent_index| {
961             match self.entry(parent_index).kind {
962                 EntryKind::Trait(_) => Some(self.local_def_id(parent_index)),
963                 _ => None,
964             }
965         })
966     }
967
968
969     pub fn get_native_libraries(&self, sess: &Session) -> Vec<NativeLibrary> {
970         self.root.native_libraries.decode((self, sess)).collect()
971     }
972
973     pub fn get_foreign_modules(&self, sess: &Session) -> Vec<ForeignModule> {
974         self.root.foreign_modules.decode((self, sess)).collect()
975     }
976
977     pub fn get_dylib_dependency_formats(&self) -> Vec<(CrateNum, LinkagePreference)> {
978         self.root
979             .dylib_dependency_formats
980             .decode(self)
981             .enumerate()
982             .flat_map(|(i, link)| {
983                 let cnum = CrateNum::new(i + 1);
984                 link.map(|link| (self.cnum_map[cnum], link))
985             })
986             .collect()
987     }
988
989     pub fn get_missing_lang_items(&self) -> Vec<lang_items::LangItem> {
990         self.root
991             .lang_items_missing
992             .decode(self)
993             .collect()
994     }
995
996     pub fn get_fn_arg_names(&self, id: DefIndex) -> Vec<ast::Name> {
997         let arg_names = match self.entry(id).kind {
998             EntryKind::Fn(data) |
999             EntryKind::ForeignFn(data) => data.decode(self).arg_names,
1000             EntryKind::Method(data) => data.decode(self).fn_data.arg_names,
1001             _ => LazySeq::empty(),
1002         };
1003         arg_names.decode(self).collect()
1004     }
1005
1006     pub fn exported_symbols(&self,
1007                             tcx: TyCtxt<'a, 'tcx, 'tcx>)
1008                             -> Vec<(ExportedSymbol<'tcx>, SymbolExportLevel)> {
1009         let lazy_seq: LazySeq<(ExportedSymbol<'tcx>, SymbolExportLevel)> =
1010             LazySeq::with_position_and_length(self.root.exported_symbols.position,
1011                                               self.root.exported_symbols.len);
1012         lazy_seq.decode((self, tcx)).collect()
1013     }
1014
1015     pub fn get_rendered_const(&self, id: DefIndex) -> String {
1016         match self.entry(id).kind {
1017             EntryKind::Const(_, data) |
1018             EntryKind::AssociatedConst(_, _, data) => data.decode(self).0,
1019             _ => bug!(),
1020         }
1021     }
1022
1023     pub fn get_macro(&self, id: DefIndex) -> (InternedString, MacroDef) {
1024         let entry = self.entry(id);
1025         match entry.kind {
1026             EntryKind::MacroDef(macro_def) => (self.item_name(id), macro_def.decode(self)),
1027             _ => bug!(),
1028         }
1029     }
1030
1031     pub fn is_const_fn(&self, id: DefIndex) -> bool {
1032         let constness = match self.entry(id).kind {
1033             EntryKind::Method(data) => data.decode(self).fn_data.constness,
1034             EntryKind::Fn(data) => data.decode(self).constness,
1035             _ => hir::Constness::NotConst,
1036         };
1037         constness == hir::Constness::Const
1038     }
1039
1040     pub fn is_foreign_item(&self, id: DefIndex) -> bool {
1041         match self.entry(id).kind {
1042             EntryKind::ForeignImmStatic |
1043             EntryKind::ForeignMutStatic |
1044             EntryKind::ForeignFn(_) => true,
1045             _ => false,
1046         }
1047     }
1048
1049     pub fn fn_sig(&self,
1050                   id: DefIndex,
1051                   tcx: TyCtxt<'a, 'tcx, 'tcx>)
1052                   -> ty::PolyFnSig<'tcx> {
1053         let sig = match self.entry(id).kind {
1054             EntryKind::Fn(data) |
1055             EntryKind::ForeignFn(data) => data.decode(self).sig,
1056             EntryKind::Method(data) => data.decode(self).fn_data.sig,
1057             EntryKind::Variant(data) |
1058             EntryKind::Struct(data, _) => data.decode(self).ctor_sig.unwrap(),
1059             EntryKind::Closure(data) => data.decode(self).sig,
1060             _ => bug!(),
1061         };
1062         sig.decode((self, tcx))
1063     }
1064
1065     #[inline]
1066     pub fn def_key(&self, index: DefIndex) -> DefKey {
1067         if !self.is_proc_macro(index) {
1068             self.def_path_table.def_key(index)
1069         } else {
1070             // FIXME(#49271) - It would be better if the DefIds were consistent
1071             //                 with the DefPathTable, but for proc-macro crates
1072             //                 they aren't.
1073             let name = self.proc_macros
1074                            .as_ref()
1075                            .unwrap()[index.to_proc_macro_index()].0;
1076             DefKey {
1077                 parent: Some(CRATE_DEF_INDEX),
1078                 disambiguated_data: DisambiguatedDefPathData {
1079                     data: DefPathData::MacroDef(name.as_interned_str()),
1080                     disambiguator: 0,
1081                 }
1082             }
1083         }
1084     }
1085
1086     // Returns the path leading to the thing with this `id`.
1087     pub fn def_path(&self, id: DefIndex) -> DefPath {
1088         debug!("def_path(id={:?})", id);
1089         DefPath::make(self.cnum, id, |parent| self.def_path_table.def_key(parent))
1090     }
1091
1092     #[inline]
1093     pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
1094         self.def_path_table.def_path_hash(index)
1095     }
1096
1097     /// Imports the codemap from an external crate into the codemap of the crate
1098     /// currently being compiled (the "local crate").
1099     ///
1100     /// The import algorithm works analogous to how AST items are inlined from an
1101     /// external crate's metadata:
1102     /// For every FileMap in the external codemap an 'inline' copy is created in the
1103     /// local codemap. The correspondence relation between external and local
1104     /// FileMaps is recorded in the `ImportedFileMap` objects returned from this
1105     /// function. When an item from an external crate is later inlined into this
1106     /// crate, this correspondence information is used to translate the span
1107     /// information of the inlined item so that it refers the correct positions in
1108     /// the local codemap (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1109     ///
1110     /// The import algorithm in the function below will reuse FileMaps already
1111     /// existing in the local codemap. For example, even if the FileMap of some
1112     /// source file of libstd gets imported many times, there will only ever be
1113     /// one FileMap object for the corresponding file in the local codemap.
1114     ///
1115     /// Note that imported FileMaps do not actually contain the source code of the
1116     /// file they represent, just information about length, line breaks, and
1117     /// multibyte characters. This information is enough to generate valid debuginfo
1118     /// for items inlined from other crates.
1119     pub fn imported_filemaps(&'a self,
1120                              local_codemap: &codemap::CodeMap)
1121                              -> ReadGuard<'a, Vec<cstore::ImportedFileMap>> {
1122         {
1123             let filemaps = self.codemap_import_info.borrow();
1124             if !filemaps.is_empty() {
1125                 return filemaps;
1126             }
1127         }
1128
1129         // Lock the codemap_import_info to ensure this only happens once
1130         let mut codemap_import_info = self.codemap_import_info.borrow_mut();
1131
1132         if !codemap_import_info.is_empty() {
1133             drop(codemap_import_info);
1134             return self.codemap_import_info.borrow();
1135         }
1136
1137         let external_codemap = self.root.codemap.decode(self);
1138
1139         let imported_filemaps = external_codemap.map(|filemap_to_import| {
1140             // We can't reuse an existing FileMap, so allocate a new one
1141             // containing the information we need.
1142             let syntax_pos::FileMap { name,
1143                                       name_was_remapped,
1144                                       src_hash,
1145                                       start_pos,
1146                                       end_pos,
1147                                       mut lines,
1148                                       mut multibyte_chars,
1149                                       mut non_narrow_chars,
1150                                       name_hash,
1151                                       .. } = filemap_to_import;
1152
1153             let source_length = (end_pos - start_pos).to_usize();
1154
1155             // Translate line-start positions and multibyte character
1156             // position into frame of reference local to file.
1157             // `CodeMap::new_imported_filemap()` will then translate those
1158             // coordinates to their new global frame of reference when the
1159             // offset of the FileMap is known.
1160             for pos in &mut lines {
1161                 *pos = *pos - start_pos;
1162             }
1163             for mbc in &mut multibyte_chars {
1164                 mbc.pos = mbc.pos - start_pos;
1165             }
1166             for swc in &mut non_narrow_chars {
1167                 *swc = *swc - start_pos;
1168             }
1169
1170             let local_version = local_codemap.new_imported_filemap(name,
1171                                                                    name_was_remapped,
1172                                                                    self.cnum.as_u32(),
1173                                                                    src_hash,
1174                                                                    name_hash,
1175                                                                    source_length,
1176                                                                    lines,
1177                                                                    multibyte_chars,
1178                                                                    non_narrow_chars);
1179             debug!("CrateMetaData::imported_filemaps alloc \
1180                     filemap {:?} original (start_pos {:?} end_pos {:?}) \
1181                     translated (start_pos {:?} end_pos {:?})",
1182                    local_version.name, start_pos, end_pos,
1183                    local_version.start_pos, local_version.end_pos);
1184
1185             cstore::ImportedFileMap {
1186                 original_start_pos: start_pos,
1187                 original_end_pos: end_pos,
1188                 translated_filemap: local_version,
1189             }
1190         }).collect();
1191
1192         *codemap_import_info = imported_filemaps;
1193         drop(codemap_import_info);
1194
1195         // This shouldn't borrow twice, but there is no way to downgrade RefMut to Ref.
1196         self.codemap_import_info.borrow()
1197     }
1198 }