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