]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/decoder.rs
Run `rustfmt --file-lines ...` for changes from previous commits.
[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, Res, DefKind, CtorOf, CtorKind};
12 use rustc::hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
13 use rustc::hir::map::definitions::DefPathTable;
14 use rustc_data_structures::fingerprint::Fingerprint;
15 use rustc::middle::lang_items;
16 use rustc::mir::{self, interpret};
17 use rustc::mir::interpret::AllocDecodingSession;
18 use rustc::session::Session;
19 use rustc::ty::{self, Ty, TyCtxt};
20 use rustc::ty::codec::TyDecoder;
21 use rustc::mir::Body;
22 use rustc::util::captures::Captures;
23
24 use std::io;
25 use std::mem;
26 use std::u32;
27
28 use rustc_serialize::{Decodable, Decoder, SpecializedDecoder, opaque};
29 use syntax::attr;
30 use syntax::ast::{self, Ident};
31 use syntax::source_map;
32 use syntax::symbol::{Symbol, sym};
33 use syntax::ext::base::{MacroKind, SyntaxExtension};
34 use syntax::ext::hygiene::Mark;
35 use syntax_pos::{self, Span, BytePos, Pos, DUMMY_SP, NO_EXPANSION};
36 use log::debug;
37
38 pub struct DecodeContext<'a, 'tcx: 'a> {
39     opaque: opaque::Decoder<'a>,
40     cdata: Option<&'a CrateMetadata>,
41     sess: Option<&'a Session>,
42     tcx: Option<TyCtxt<'tcx, 'tcx>>,
43
44     // Cache the last used source_file for translating spans as an optimization.
45     last_source_file_index: usize,
46
47     lazy_state: LazyState,
48
49     // Used for decoding interpret::AllocIds in a cached & thread-safe manner.
50     alloc_decoding_session: Option<AllocDecodingSession<'a>>,
51 }
52
53 /// Abstract over the various ways one can create metadata decoders.
54 pub trait Metadata<'a, 'tcx>: Copy {
55     fn raw_bytes(self) -> &'a [u8];
56     fn cdata(self) -> Option<&'a CrateMetadata> { None }
57     fn sess(self) -> Option<&'a Session> { None }
58     fn tcx(self) -> Option<TyCtxt<'tcx, 'tcx>> {
59         None
60         }
61
62     fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> {
63         let tcx = self.tcx();
64         DecodeContext {
65             opaque: opaque::Decoder::new(self.raw_bytes(), pos),
66             cdata: self.cdata(),
67             sess: self.sess().or(tcx.map(|tcx| tcx.sess)),
68             tcx,
69             last_source_file_index: 0,
70             lazy_state: LazyState::NoNode,
71             alloc_decoding_session: self.cdata().map(|cdata| {
72                 cdata.alloc_decoding_state.new_decoding_session()
73             }),
74         }
75     }
76 }
77
78 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob {
79     fn raw_bytes(self) -> &'a [u8] {
80         &self.0
81     }
82 }
83
84
85 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a MetadataBlob, &'a Session) {
86     fn raw_bytes(self) -> &'a [u8] {
87         let (blob, _) = self;
88         &blob.0
89     }
90
91     fn sess(self) -> Option<&'a Session> {
92         let (_, sess) = self;
93         Some(sess)
94     }
95 }
96
97
98 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a CrateMetadata {
99     fn raw_bytes(self) -> &'a [u8] {
100         self.blob.raw_bytes()
101     }
102     fn cdata(self) -> Option<&'a CrateMetadata> {
103         Some(self)
104     }
105 }
106
107 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, &'a Session) {
108     fn raw_bytes(self) -> &'a [u8] {
109         self.0.raw_bytes()
110     }
111     fn cdata(self) -> Option<&'a CrateMetadata> {
112         Some(self.0)
113     }
114     fn sess(self) -> Option<&'a Session> {
115         Some(&self.1)
116     }
117 }
118
119 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, TyCtxt<'tcx, 'tcx>) {
120     fn raw_bytes(self) -> &'a [u8] {
121         self.0.raw_bytes()
122     }
123     fn cdata(self) -> Option<&'a CrateMetadata> {
124         Some(self.0)
125     }
126     fn tcx(self) -> Option<TyCtxt<'tcx, 'tcx>> {
127         Some(self.1)
128     }
129 }
130
131 impl<'a, 'tcx: 'a, T: Decodable> Lazy<T> {
132     pub fn decode<M: Metadata<'a, 'tcx>>(self, meta: M) -> T {
133         let mut dcx = meta.decoder(self.position);
134         dcx.lazy_state = LazyState::NodeStart(self.position);
135         T::decode(&mut dcx).unwrap()
136     }
137 }
138
139 impl<'a, 'tcx: 'a, T: Decodable> LazySeq<T> {
140     pub fn decode<M: Metadata<'a, 'tcx>>(
141         self,
142         meta: M,
143     ) -> impl Iterator<Item = T> + Captures<'tcx> + 'a {
144         let mut dcx = meta.decoder(self.position);
145         dcx.lazy_state = LazyState::NodeStart(self.position);
146         (0..self.len).map(move |_| T::decode(&mut dcx).unwrap())
147     }
148 }
149
150 impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
151     pub fn tcx(&self) -> TyCtxt<'tcx, 'tcx> {
152         self.tcx.expect("missing TyCtxt in DecodeContext")
153     }
154
155     pub fn cdata(&self) -> &'a CrateMetadata {
156         self.cdata.expect("missing CrateMetadata in DecodeContext")
157     }
158
159     fn read_lazy_distance(&mut self, min_size: usize) -> Result<usize, <Self as Decoder>::Error> {
160         let distance = self.read_usize()?;
161         let position = match self.lazy_state {
162             LazyState::NoNode => bug!("read_lazy_distance: outside of a metadata node"),
163             LazyState::NodeStart(start) => {
164                 assert!(distance + min_size <= start);
165                 start - distance - min_size
166             }
167             LazyState::Previous(last_min_end) => last_min_end + distance,
168         };
169         self.lazy_state = LazyState::Previous(position + min_size);
170         Ok(position)
171     }
172 }
173
174 impl<'a, 'tcx> TyDecoder<'tcx> for DecodeContext<'a, 'tcx> {
175     #[inline]
176     fn tcx(&self) -> TyCtxt<'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_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<'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<'tcx> {
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::AssocConst(..) => DefKind::AssocConst,
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::AssocType(_) => DefKind::AssocTy,
420             EntryKind::AssocExistential(_) => DefKind::AssocExistential,
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::default();
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::MacroNs(name.as_interned_str()),
463             Mark::root(),
464             DUMMY_SP);
465         debug!("definition for {:?} is {:?}", name, def_index);
466         assert_eq!(def_index, DefIndex::from_proc_macro_index(index));
467     }
468
469     definitions.def_path_table().clone()
470 }
471
472 impl<'a, 'tcx> CrateMetadata {
473     fn is_proc_macro(&self, id: DefIndex) -> bool {
474         self.proc_macros.is_some() && id != CRATE_DEF_INDEX
475     }
476
477     fn maybe_entry(&self, item_id: DefIndex) -> Option<Lazy<Entry<'tcx>>> {
478         assert!(!self.is_proc_macro(item_id));
479         self.root.entries_index.lookup(self.blob.raw_bytes(), item_id)
480     }
481
482     fn entry(&self, item_id: DefIndex) -> Entry<'tcx> {
483         match self.maybe_entry(item_id) {
484             None => {
485                 bug!("entry: id not found: {:?} in crate {:?} with number {}",
486                      item_id,
487                      self.name,
488                      self.cnum)
489             }
490             Some(d) => d.decode(self),
491         }
492     }
493
494     fn local_def_id(&self, index: DefIndex) -> DefId {
495         DefId {
496             krate: self.cnum,
497             index,
498         }
499     }
500
501     pub fn item_name(&self, item_index: DefIndex) -> Symbol {
502         self.def_key(item_index)
503             .disambiguated_data
504             .data
505             .get_opt_name()
506             .expect("no name in item_name")
507             .as_symbol()
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<'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::with_empty_ctxt(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::with_empty_ctxt(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, item_id: DefIndex, tcx: TyCtxt<'tcx, 'tcx>) -> &'tcx ty::AdtDef {
593         let item = self.entry(item_id);
594         let did = self.local_def_id(item_id);
595
596         let (kind, repr) = match item.kind {
597             EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr),
598             EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr),
599             EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr),
600             _ => bug!("get_adt_def called on a non-ADT {:?}", did),
601         };
602
603         let variants = if let ty::AdtKind::Enum = kind {
604             item.children
605                 .decode(self)
606                 .map(|index| {
607                     self.get_variant(tcx, &self.entry(index), index, did, kind)
608                 })
609                 .collect()
610         } else {
611             std::iter::once(self.get_variant(tcx, &item, item_id, did, kind)).collect()
612         };
613
614         tcx.alloc_adt_def(did, kind, variants, repr)
615     }
616
617     pub fn get_predicates(
618         &self,
619         item_id: DefIndex,
620         tcx: TyCtxt<'tcx, 'tcx>,
621     ) -> ty::GenericPredicates<'tcx> {
622         self.entry(item_id).predicates.unwrap().decode((self, tcx))
623     }
624
625     pub fn get_predicates_defined_on(
626         &self,
627         item_id: DefIndex,
628         tcx: TyCtxt<'tcx, 'tcx>,
629     ) -> ty::GenericPredicates<'tcx> {
630         self.entry(item_id).predicates_defined_on.unwrap().decode((self, tcx))
631     }
632
633     pub fn get_super_predicates(
634         &self,
635         item_id: DefIndex,
636         tcx: TyCtxt<'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<'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(
705         &self,
706         id: DefIndex,
707         tcx: TyCtxt<'tcx, 'tcx>,
708     ) -> Option<ty::TraitRef<'tcx>> {
709         self.get_impl_data(id).trait_ref.map(|tr| tr.decode((self, tcx)))
710     }
711
712     /// Iterates over all the stability attributes in the given crate.
713     pub fn get_lib_features(
714         &self,
715         tcx: TyCtxt<'tcx, '_>,
716     ) -> &'tcx [(ast::Name, Option<ast::Name>)] {
717         // FIXME: For a proc macro crate, not sure whether we should return the "host"
718         // features or an empty Vec. Both don't cause ICEs.
719         tcx.arena.alloc_from_iter(self.root
720             .lib_features
721             .decode(self))
722     }
723
724     /// Iterates over the language items in the given crate.
725     pub fn get_lang_items(&self, tcx: TyCtxt<'tcx, '_>) -> &'tcx [(DefId, usize)] {
726         if self.proc_macros.is_some() {
727             // Proc macro crates do not export any lang-items to the target.
728             &[]
729         } else {
730             tcx.arena.alloc_from_iter(self.root
731                 .lang_items
732                 .decode(self)
733                 .map(|(def_index, index)| (self.local_def_id(def_index), index)))
734         }
735     }
736
737     /// Iterates over each child of the given item.
738     pub fn each_child_of_item<F>(&self, id: DefIndex, mut callback: F, sess: &Session)
739         where F: FnMut(def::Export<hir::HirId>)
740     {
741         if let Some(ref proc_macros) = self.proc_macros {
742             /* If we are loading as a proc macro, we want to return the view of this crate
743              * as a proc macro crate, not as a Rust crate. See `proc_macro_def_path_table`
744              * for the DefPathTable we are corresponding to.
745              */
746             if id == CRATE_DEF_INDEX {
747                 for (id, &(name, ref ext)) in proc_macros.iter().enumerate() {
748                     let res = Res::Def(
749                         DefKind::Macro(ext.kind()),
750                         self.local_def_id(DefIndex::from_proc_macro_index(id)),
751                     );
752                     let ident = Ident::with_empty_ctxt(name);
753                     callback(def::Export {
754                         ident: ident,
755                         res: res,
756                         vis: ty::Visibility::Public,
757                         span: DUMMY_SP,
758                     });
759                 }
760             }
761             return
762         }
763
764         // Find the item.
765         let item = match self.maybe_entry(id) {
766             None => return,
767             Some(item) => item.decode((self, sess)),
768         };
769
770         // Iterate over all children.
771         let macros_only = self.dep_kind.lock().macros_only();
772         for child_index in item.children.decode((self, sess)) {
773             if macros_only {
774                 continue
775             }
776
777             // Get the item.
778             if let Some(child) = self.maybe_entry(child_index) {
779                 let child = child.decode((self, sess));
780                 match child.kind {
781                     EntryKind::MacroDef(..) => {}
782                     _ if macros_only => continue,
783                     _ => {}
784                 }
785
786                 // Hand off the item to the callback.
787                 match child.kind {
788                     // FIXME(eddyb) Don't encode these in children.
789                     EntryKind::ForeignMod => {
790                         for child_index in child.children.decode((self, sess)) {
791                             if let Some(kind) = self.def_kind(child_index) {
792                                 callback(def::Export {
793                                     res: Res::Def(kind, self.local_def_id(child_index)),
794                                     ident: Ident::with_empty_ctxt(self.item_name(child_index)),
795                                     vis: self.get_visibility(child_index),
796                                     span: self.entry(child_index).span.decode((self, sess)),
797                                 });
798                             }
799                         }
800                         continue;
801                     }
802                     EntryKind::Impl(_) => continue,
803
804                     _ => {}
805                 }
806
807                 let def_key = self.def_key(child_index);
808                 let span = child.span.decode((self, sess));
809                 if let (Some(kind), Some(name)) =
810                     (self.def_kind(child_index), def_key.disambiguated_data.data.get_opt_name()) {
811                     let ident = Ident::from_interned_str(name);
812                     let vis = self.get_visibility(child_index);
813                     let def_id = self.local_def_id(child_index);
814                     let res = Res::Def(kind, def_id);
815                     callback(def::Export { res, ident, vis, span });
816                     // For non-re-export structs and variants add their constructors to children.
817                     // Re-export lists automatically contain constructors when necessary.
818                     match kind {
819                         DefKind::Struct => {
820                             if let Some(ctor_def_id) = self.get_ctor_def_id(child_index) {
821                                 let ctor_kind = self.get_ctor_kind(child_index);
822                                 let ctor_res = Res::Def(
823                                     DefKind::Ctor(CtorOf::Struct, ctor_kind),
824                                     ctor_def_id,
825                                 );
826                                 let vis = self.get_visibility(ctor_def_id.index);
827                                 callback(def::Export { res: ctor_res, vis, ident, span });
828                             }
829                         }
830                         DefKind::Variant => {
831                             // Braced variants, unlike structs, generate unusable names in
832                             // value namespace, they are reserved for possible future use.
833                             // It's ok to use the variant's id as a ctor id since an
834                             // error will be reported on any use of such resolution anyway.
835                             let ctor_def_id = self.get_ctor_def_id(child_index).unwrap_or(def_id);
836                             let ctor_kind = self.get_ctor_kind(child_index);
837                             let ctor_res = Res::Def(
838                                 DefKind::Ctor(CtorOf::Variant, ctor_kind),
839                                 ctor_def_id,
840                             );
841                             let mut vis = self.get_visibility(ctor_def_id.index);
842                             if ctor_def_id == def_id && vis == ty::Visibility::Public {
843                                 // For non-exhaustive variants lower the constructor visibility to
844                                 // within the crate. We only need this for fictive constructors,
845                                 // for other constructors correct visibilities
846                                 // were already encoded in metadata.
847                                 let attrs = self.get_item_attrs(def_id.index, sess);
848                                 if attr::contains_name(&attrs, sym::non_exhaustive) {
849                                     let crate_def_id = self.local_def_id(CRATE_DEF_INDEX);
850                                     vis = ty::Visibility::Restricted(crate_def_id);
851                                 }
852                             }
853                             callback(def::Export { res: ctor_res, ident, vis, span });
854                         }
855                         _ => {}
856                     }
857                 }
858             }
859         }
860
861         if let EntryKind::Mod(data) = item.kind {
862             for exp in data.decode((self, sess)).reexports.decode((self, sess)) {
863                 match exp.res {
864                     Res::Def(DefKind::Macro(..), _) => {}
865                     _ if macros_only => continue,
866                     _ => {}
867                 }
868                 callback(exp);
869             }
870         }
871     }
872
873     pub fn const_is_rvalue_promotable_to_static(&self, id: DefIndex) -> bool {
874         match self.entry(id).kind {
875             EntryKind::AssocConst(_, data, _) |
876             EntryKind::Const(data, _) => data.ast_promotable,
877             _ => bug!(),
878         }
879     }
880
881     pub fn is_item_mir_available(&self, id: DefIndex) -> bool {
882         !self.is_proc_macro(id) &&
883         self.maybe_entry(id).and_then(|item| item.decode(self).mir).is_some()
884     }
885
886     pub fn maybe_get_optimized_mir(
887         &self,
888         tcx: TyCtxt<'tcx, 'tcx>,
889         id: DefIndex,
890     ) -> Option<Body<'tcx>> {
891         match self.is_proc_macro(id) {
892             true => None,
893             false => self.entry(id).mir.map(|mir| mir.decode((self, tcx))),
894         }
895     }
896
897     pub fn mir_const_qualif(&self, id: DefIndex) -> u8 {
898         match self.entry(id).kind {
899             EntryKind::Const(qualif, _) |
900             EntryKind::AssocConst(AssocContainer::ImplDefault, qualif, _) |
901             EntryKind::AssocConst(AssocContainer::ImplFinal, qualif, _) => {
902                 qualif.mir
903             }
904             _ => bug!(),
905         }
906     }
907
908     pub fn get_associated_item(&self, id: DefIndex) -> ty::AssocItem {
909         let item = self.entry(id);
910         let def_key = self.def_key(id);
911         let parent = self.local_def_id(def_key.parent.unwrap());
912         let name = def_key.disambiguated_data.data.get_opt_name().unwrap();
913
914         let (kind, container, has_self) = match item.kind {
915             EntryKind::AssocConst(container, _, _) => {
916                 (ty::AssocKind::Const, container, false)
917             }
918             EntryKind::Method(data) => {
919                 let data = data.decode(self);
920                 (ty::AssocKind::Method, data.container, data.has_self)
921             }
922             EntryKind::AssocType(container) => {
923                 (ty::AssocKind::Type, container, false)
924             }
925             EntryKind::AssocExistential(container) => {
926                 (ty::AssocKind::Existential, container, false)
927             }
928             _ => bug!("cannot get associated-item of `{:?}`", def_key)
929         };
930
931         ty::AssocItem {
932             ident: Ident::from_interned_str(name),
933             kind,
934             vis: item.visibility.decode(self),
935             defaultness: container.defaultness(),
936             def_id: self.local_def_id(id),
937             container: container.with_def_id(parent),
938             method_has_self_argument: has_self
939         }
940     }
941
942     pub fn get_item_variances(&self, id: DefIndex) -> Vec<ty::Variance> {
943         self.entry(id).variances.decode(self).collect()
944     }
945
946     pub fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
947         match self.entry(node_id).kind {
948             EntryKind::Struct(data, _) |
949             EntryKind::Union(data, _) |
950             EntryKind::Variant(data) => data.decode(self).ctor_kind,
951             _ => CtorKind::Fictive,
952         }
953     }
954
955     pub fn get_ctor_def_id(&self, node_id: DefIndex) -> Option<DefId> {
956         match self.entry(node_id).kind {
957             EntryKind::Struct(data, _) => {
958                 data.decode(self).ctor.map(|index| self.local_def_id(index))
959             }
960             EntryKind::Variant(data) => {
961                 data.decode(self).ctor.map(|index| self.local_def_id(index))
962             }
963             _ => None,
964         }
965     }
966
967     pub fn get_item_attrs(&self, node_id: DefIndex, sess: &Session) -> Lrc<[ast::Attribute]> {
968         if self.is_proc_macro(node_id) {
969             return Lrc::new([]);
970         }
971
972         // The attributes for a tuple struct/variant are attached to the definition, not the ctor;
973         // we assume that someone passing in a tuple struct ctor is actually wanting to
974         // look at the definition
975         let def_key = self.def_key(node_id);
976         let item_id = if def_key.disambiguated_data.data == DefPathData::Ctor {
977             def_key.parent.unwrap()
978         } else {
979             node_id
980         };
981
982         let item = self.entry(item_id);
983         Lrc::from(self.get_attributes(&item, sess))
984     }
985
986     pub fn get_struct_field_names(&self, id: DefIndex) -> Vec<ast::Name> {
987         self.entry(id)
988             .children
989             .decode(self)
990             .map(|index| self.item_name(index))
991             .collect()
992     }
993
994     fn get_attributes(&self, item: &Entry<'tcx>, sess: &Session) -> Vec<ast::Attribute> {
995         item.attributes
996             .decode((self, sess))
997             .map(|mut attr| {
998                 // Need new unique IDs: old thread-local IDs won't map to new threads.
999                 attr.id = attr::mk_attr_id();
1000                 attr
1001             })
1002             .collect()
1003     }
1004
1005     // Translate a DefId from the current compilation environment to a DefId
1006     // for an external crate.
1007     fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
1008         for (local, &global) in self.cnum_map.iter_enumerated() {
1009             if global == did.krate {
1010                 return Some(DefId {
1011                     krate: local,
1012                     index: did.index,
1013                 });
1014             }
1015         }
1016
1017         None
1018     }
1019
1020     pub fn get_inherent_implementations_for_type(
1021         &self,
1022         tcx: TyCtxt<'tcx, '_>,
1023         id: DefIndex,
1024     ) -> &'tcx [DefId] {
1025         tcx.arena.alloc_from_iter(self.entry(id)
1026                                       .inherent_impls
1027                                       .decode(self)
1028                                       .map(|index| self.local_def_id(index)))
1029     }
1030
1031     pub fn get_implementations_for_trait(
1032         &self,
1033         tcx: TyCtxt<'tcx, '_>,
1034         filter: Option<DefId>,
1035     ) -> &'tcx [DefId] {
1036         if self.proc_macros.is_some() {
1037             // proc-macro crates export no trait impls.
1038             return &[]
1039         }
1040
1041         // Do a reverse lookup beforehand to avoid touching the crate_num
1042         // hash map in the loop below.
1043         let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) {
1044             Some(Some(def_id)) => Some((def_id.krate.as_u32(), def_id.index)),
1045             Some(None) => return &[],
1046             None => None,
1047         };
1048
1049         if let Some(filter) = filter {
1050             if let Some(impls) = self.trait_impls.get(&filter) {
1051                 tcx.arena.alloc_from_iter(impls.decode(self).map(|idx| self.local_def_id(idx)))
1052             } else {
1053                 &[]
1054             }
1055         } else {
1056             tcx.arena.alloc_from_iter(self.trait_impls.values().flat_map(|impls| {
1057                 impls.decode(self).map(|idx| self.local_def_id(idx))
1058             }))
1059         }
1060     }
1061
1062     pub fn get_trait_of_item(&self, id: DefIndex) -> Option<DefId> {
1063         let def_key = self.def_key(id);
1064         match def_key.disambiguated_data.data {
1065             DefPathData::TypeNs(..) | DefPathData::ValueNs(..) => (),
1066             // Not an associated item
1067             _ => return None,
1068         }
1069         def_key.parent.and_then(|parent_index| {
1070             match self.entry(parent_index).kind {
1071                 EntryKind::Trait(_) |
1072                 EntryKind::TraitAlias(_) => Some(self.local_def_id(parent_index)),
1073                 _ => None,
1074             }
1075         })
1076     }
1077
1078
1079     pub fn get_native_libraries(&self, sess: &Session) -> Vec<NativeLibrary> {
1080         if self.proc_macros.is_some() {
1081             // Proc macro crates do not have any *target* native libraries.
1082             vec![]
1083         } else {
1084             self.root.native_libraries.decode((self, sess)).collect()
1085         }
1086     }
1087
1088     pub fn get_foreign_modules(&self, tcx: TyCtxt<'tcx, '_>) -> &'tcx [ForeignModule] {
1089         if self.proc_macros.is_some() {
1090             // Proc macro crates do not have any *target* foreign modules.
1091             &[]
1092         } else {
1093             tcx.arena.alloc_from_iter(self.root.foreign_modules.decode((self, tcx.sess)))
1094         }
1095     }
1096
1097     pub fn get_dylib_dependency_formats(
1098         &self,
1099         tcx: TyCtxt<'tcx, '_>,
1100     ) -> &'tcx [(CrateNum, LinkagePreference)] {
1101         tcx.arena.alloc_from_iter(self.root
1102             .dylib_dependency_formats
1103             .decode(self)
1104             .enumerate()
1105             .flat_map(|(i, link)| {
1106                 let cnum = CrateNum::new(i + 1);
1107                 link.map(|link| (self.cnum_map[cnum], link))
1108             }))
1109     }
1110
1111     pub fn get_missing_lang_items(&self, tcx: TyCtxt<'tcx, '_>) -> &'tcx [lang_items::LangItem] {
1112         if self.proc_macros.is_some() {
1113             // Proc macro crates do not depend on any target weak lang-items.
1114             &[]
1115         } else {
1116             tcx.arena.alloc_from_iter(self.root
1117                 .lang_items_missing
1118                 .decode(self))
1119         }
1120     }
1121
1122     pub fn get_fn_arg_names(&self, id: DefIndex) -> Vec<ast::Name> {
1123         let arg_names = match self.entry(id).kind {
1124             EntryKind::Fn(data) |
1125             EntryKind::ForeignFn(data) => data.decode(self).arg_names,
1126             EntryKind::Method(data) => data.decode(self).fn_data.arg_names,
1127             _ => LazySeq::empty(),
1128         };
1129         arg_names.decode(self).collect()
1130     }
1131
1132     pub fn exported_symbols(
1133         &self,
1134         tcx: TyCtxt<'tcx, 'tcx>,
1135     ) -> Vec<(ExportedSymbol<'tcx>, SymbolExportLevel)> {
1136         if self.proc_macros.is_some() {
1137             // If this crate is a custom derive crate, then we're not even going to
1138             // link those in so we skip those crates.
1139             vec![]
1140         } else {
1141             self.root.exported_symbols.decode((self, tcx)).collect()
1142         }
1143     }
1144
1145     pub fn get_rendered_const(&self, id: DefIndex) -> String {
1146         match self.entry(id).kind {
1147             EntryKind::Const(_, data) |
1148             EntryKind::AssocConst(_, _, data) => data.decode(self).0,
1149             _ => bug!(),
1150         }
1151     }
1152
1153     pub fn get_macro(&self, id: DefIndex) -> MacroDef {
1154         let entry = self.entry(id);
1155         match entry.kind {
1156             EntryKind::MacroDef(macro_def) => macro_def.decode(self),
1157             _ => bug!(),
1158         }
1159     }
1160
1161     crate fn is_const_fn_raw(&self, id: DefIndex) -> bool {
1162         let constness = match self.entry(id).kind {
1163             EntryKind::Method(data) => data.decode(self).fn_data.constness,
1164             EntryKind::Fn(data) => data.decode(self).constness,
1165             EntryKind::Variant(..) | EntryKind::Struct(..) => hir::Constness::Const,
1166             _ => hir::Constness::NotConst,
1167         };
1168         constness == hir::Constness::Const
1169     }
1170
1171     pub fn is_foreign_item(&self, id: DefIndex) -> bool {
1172         match self.entry(id).kind {
1173             EntryKind::ForeignImmStatic |
1174             EntryKind::ForeignMutStatic |
1175             EntryKind::ForeignFn(_) => true,
1176             _ => false,
1177         }
1178     }
1179
1180     crate fn static_mutability(&self, id: DefIndex) -> Option<hir::Mutability> {
1181         match self.entry(id).kind {
1182             EntryKind::ImmStatic |
1183             EntryKind::ForeignImmStatic => Some(hir::MutImmutable),
1184             EntryKind::MutStatic |
1185             EntryKind::ForeignMutStatic => Some(hir::MutMutable),
1186             _ => None,
1187         }
1188     }
1189
1190     pub fn fn_sig(&self, id: DefIndex, tcx: TyCtxt<'tcx, 'tcx>) -> ty::PolyFnSig<'tcx> {
1191         let sig = match self.entry(id).kind {
1192             EntryKind::Fn(data) |
1193             EntryKind::ForeignFn(data) => data.decode(self).sig,
1194             EntryKind::Method(data) => data.decode(self).fn_data.sig,
1195             EntryKind::Variant(data) |
1196             EntryKind::Struct(data, _) => data.decode(self).ctor_sig.unwrap(),
1197             EntryKind::Closure(data) => data.decode(self).sig,
1198             _ => bug!(),
1199         };
1200         sig.decode((self, tcx))
1201     }
1202
1203     #[inline]
1204     pub fn def_key(&self, index: DefIndex) -> DefKey {
1205         self.def_path_table.def_key(index)
1206     }
1207
1208     // Returns the path leading to the thing with this `id`.
1209     pub fn def_path(&self, id: DefIndex) -> DefPath {
1210         debug!("def_path(cnum={:?}, id={:?})", self.cnum, id);
1211         DefPath::make(self.cnum, id, |parent| self.def_path_table.def_key(parent))
1212     }
1213
1214     #[inline]
1215     pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
1216         self.def_path_table.def_path_hash(index)
1217     }
1218
1219     /// Imports the source_map from an external crate into the source_map of the crate
1220     /// currently being compiled (the "local crate").
1221     ///
1222     /// The import algorithm works analogous to how AST items are inlined from an
1223     /// external crate's metadata:
1224     /// For every SourceFile in the external source_map an 'inline' copy is created in the
1225     /// local source_map. The correspondence relation between external and local
1226     /// SourceFiles is recorded in the `ImportedSourceFile` objects returned from this
1227     /// function. When an item from an external crate is later inlined into this
1228     /// crate, this correspondence information is used to translate the span
1229     /// information of the inlined item so that it refers the correct positions in
1230     /// the local source_map (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1231     ///
1232     /// The import algorithm in the function below will reuse SourceFiles already
1233     /// existing in the local source_map. For example, even if the SourceFile of some
1234     /// source file of libstd gets imported many times, there will only ever be
1235     /// one SourceFile object for the corresponding file in the local source_map.
1236     ///
1237     /// Note that imported SourceFiles do not actually contain the source code of the
1238     /// file they represent, just information about length, line breaks, and
1239     /// multibyte characters. This information is enough to generate valid debuginfo
1240     /// for items inlined from other crates.
1241     ///
1242     /// Proc macro crates don't currently export spans, so this function does not have
1243     /// to work for them.
1244     pub fn imported_source_files(&'a self,
1245                                  local_source_map: &source_map::SourceMap)
1246                                  -> ReadGuard<'a, Vec<cstore::ImportedSourceFile>> {
1247         {
1248             let source_files = self.source_map_import_info.borrow();
1249             if !source_files.is_empty() {
1250                 return source_files;
1251             }
1252         }
1253
1254         // Lock the source_map_import_info to ensure this only happens once
1255         let mut source_map_import_info = self.source_map_import_info.borrow_mut();
1256
1257         if !source_map_import_info.is_empty() {
1258             drop(source_map_import_info);
1259             return self.source_map_import_info.borrow();
1260         }
1261
1262         let external_source_map = self.root.source_map.decode(self);
1263
1264         let imported_source_files = external_source_map.map(|source_file_to_import| {
1265             // We can't reuse an existing SourceFile, so allocate a new one
1266             // containing the information we need.
1267             let syntax_pos::SourceFile { name,
1268                                       name_was_remapped,
1269                                       src_hash,
1270                                       start_pos,
1271                                       end_pos,
1272                                       mut lines,
1273                                       mut multibyte_chars,
1274                                       mut non_narrow_chars,
1275                                       name_hash,
1276                                       .. } = source_file_to_import;
1277
1278             let source_length = (end_pos - start_pos).to_usize();
1279
1280             // Translate line-start positions and multibyte character
1281             // position into frame of reference local to file.
1282             // `SourceMap::new_imported_source_file()` will then translate those
1283             // coordinates to their new global frame of reference when the
1284             // offset of the SourceFile is known.
1285             for pos in &mut lines {
1286                 *pos = *pos - start_pos;
1287             }
1288             for mbc in &mut multibyte_chars {
1289                 mbc.pos = mbc.pos - start_pos;
1290             }
1291             for swc in &mut non_narrow_chars {
1292                 *swc = *swc - start_pos;
1293             }
1294
1295             let local_version = local_source_map.new_imported_source_file(name,
1296                                                                    name_was_remapped,
1297                                                                    self.cnum.as_u32(),
1298                                                                    src_hash,
1299                                                                    name_hash,
1300                                                                    source_length,
1301                                                                    lines,
1302                                                                    multibyte_chars,
1303                                                                    non_narrow_chars);
1304             debug!("CrateMetaData::imported_source_files alloc \
1305                     source_file {:?} original (start_pos {:?} end_pos {:?}) \
1306                     translated (start_pos {:?} end_pos {:?})",
1307                    local_version.name, start_pos, end_pos,
1308                    local_version.start_pos, local_version.end_pos);
1309
1310             cstore::ImportedSourceFile {
1311                 original_start_pos: start_pos,
1312                 original_end_pos: end_pos,
1313                 translated_source_file: local_version,
1314             }
1315         }).collect();
1316
1317         *source_map_import_info = imported_source_files;
1318         drop(source_map_import_info);
1319
1320         // This shouldn't borrow twice, but there is no way to downgrade RefMut to Ref.
1321         self.source_map_import_info.borrow()
1322     }
1323 }