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