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