]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/cstore_impl.rs
Account for --remap-path-prefix in save-analysis
[rust.git] / src / librustc_metadata / cstore_impl.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use cstore::{self, LoadedMacro};
12 use encoder;
13 use link_args;
14 use native_libs;
15 use foreign_modules;
16 use schema;
17
18 use rustc::ty::query::QueryConfig;
19 use rustc::middle::cstore::{CrateStore, DepKind,
20                             LinkMeta,
21                             EncodedMetadata, NativeLibraryKind};
22 use rustc::middle::exported_symbols::ExportedSymbol;
23 use rustc::middle::stability::DeprecationEntry;
24 use rustc::hir::def;
25 use rustc::session::{CrateDisambiguator, Session};
26 use rustc::ty::{self, TyCtxt};
27 use rustc::ty::query::Providers;
28 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE, CRATE_DEF_INDEX};
29 use rustc::hir::map::{DefKey, DefPath, DefPathHash};
30 use rustc::hir::map::blocks::FnLikeNode;
31 use rustc::hir::map::definitions::DefPathTable;
32 use rustc::util::nodemap::DefIdMap;
33
34 use std::any::Any;
35 use rustc_data_structures::sync::Lrc;
36 use std::sync::Arc;
37
38 use syntax::ast;
39 use syntax::attr;
40 use syntax::codemap;
41 use syntax::edition::Edition;
42 use syntax::parse::filemap_to_stream;
43 use syntax::symbol::Symbol;
44 use syntax_pos::{Span, NO_EXPANSION, FileName};
45 use rustc_data_structures::indexed_set::IdxSetBuf;
46 use rustc::hir;
47
48 macro_rules! provide {
49     (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident,
50       $($name:ident => $compute:block)*) => {
51         pub fn provide_extern<$lt>(providers: &mut Providers<$lt>) {
52             $(fn $name<'a, $lt:$lt, T>($tcx: TyCtxt<'a, $lt, $lt>, def_id_arg: T)
53                                     -> <ty::queries::$name<$lt> as
54                                         QueryConfig<$lt>>::Value
55                 where T: IntoArgs,
56             {
57                 #[allow(unused_variables)]
58                 let ($def_id, $other) = def_id_arg.into_args();
59                 assert!(!$def_id.is_local());
60
61                 let def_path_hash = $tcx.def_path_hash(DefId {
62                     krate: $def_id.krate,
63                     index: CRATE_DEF_INDEX
64                 });
65                 let dep_node = def_path_hash
66                     .to_dep_node(::rustc::dep_graph::DepKind::CrateMetadata);
67                 // The DepNodeIndex of the DepNode::CrateMetadata should be
68                 // cached somewhere, so that we can use read_index().
69                 $tcx.dep_graph.read(dep_node);
70
71                 let $cdata = $tcx.crate_data_as_rc_any($def_id.krate);
72                 let $cdata = $cdata.downcast_ref::<cstore::CrateMetadata>()
73                     .expect("CrateStore crated ata is not a CrateMetadata");
74                 $compute
75             })*
76
77             *providers = Providers {
78                 $($name,)*
79                 ..*providers
80             };
81         }
82     }
83 }
84
85 // small trait to work around different signature queries all being defined via
86 // the macro above.
87 trait IntoArgs {
88     fn into_args(self) -> (DefId, DefId);
89 }
90
91 impl IntoArgs for DefId {
92     fn into_args(self) -> (DefId, DefId) { (self, self) }
93 }
94
95 impl IntoArgs for CrateNum {
96     fn into_args(self) -> (DefId, DefId) { (self.as_def_id(), self.as_def_id()) }
97 }
98
99 impl IntoArgs for (CrateNum, DefId) {
100     fn into_args(self) -> (DefId, DefId) { (self.0.as_def_id(), self.1) }
101 }
102
103 provide! { <'tcx> tcx, def_id, other, cdata,
104     type_of => { cdata.get_type(def_id.index, tcx) }
105     generics_of => {
106         tcx.alloc_generics(cdata.get_generics(def_id.index, tcx.sess))
107     }
108     predicates_of => { cdata.get_predicates(def_id.index, tcx) }
109     predicates_defined_on => { cdata.get_predicates_defined_on(def_id.index, tcx) }
110     super_predicates_of => { cdata.get_super_predicates(def_id.index, tcx) }
111     trait_def => {
112         tcx.alloc_trait_def(cdata.get_trait_def(def_id.index, tcx.sess))
113     }
114     adt_def => { cdata.get_adt_def(def_id.index, tcx) }
115     adt_destructor => {
116         let _ = cdata;
117         tcx.calculate_dtor(def_id, &mut |_,_| Ok(()))
118     }
119     variances_of => { Lrc::new(cdata.get_item_variances(def_id.index)) }
120     associated_item_def_ids => {
121         let mut result = vec![];
122         cdata.each_child_of_item(def_id.index,
123           |child| result.push(child.def.def_id()), tcx.sess);
124         Lrc::new(result)
125     }
126     associated_item => { cdata.get_associated_item(def_id.index) }
127     impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
128     impl_polarity => { cdata.get_impl_polarity(def_id.index) }
129     coerce_unsized_info => {
130         cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
131             bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
132         })
133     }
134     optimized_mir => {
135         let mir = cdata.maybe_get_optimized_mir(tcx, def_id.index).unwrap_or_else(|| {
136             bug!("get_optimized_mir: missing MIR for `{:?}`", def_id)
137         });
138
139         let mir = tcx.alloc_mir(mir);
140
141         mir
142     }
143     mir_const_qualif => {
144         (cdata.mir_const_qualif(def_id.index), Lrc::new(IdxSetBuf::new_empty(0)))
145     }
146     fn_sig => { cdata.fn_sig(def_id.index, tcx) }
147     inherent_impls => { Lrc::new(cdata.get_inherent_implementations_for_type(def_id.index)) }
148     is_const_fn => { cdata.is_const_fn(def_id.index) }
149     is_foreign_item => { cdata.is_foreign_item(def_id.index) }
150     describe_def => { cdata.get_def(def_id.index) }
151     def_span => { cdata.get_span(def_id.index, &tcx.sess) }
152     lookup_stability => {
153         cdata.get_stability(def_id.index).map(|s| tcx.intern_stability(s))
154     }
155     lookup_deprecation_entry => {
156         cdata.get_deprecation(def_id.index).map(DeprecationEntry::external)
157     }
158     item_attrs => { cdata.get_item_attrs(def_id.index, tcx.sess) }
159     // FIXME(#38501) We've skipped a `read` on the `HirBody` of
160     // a `fn` when encoding, so the dep-tracking wouldn't work.
161     // This is only used by rustdoc anyway, which shouldn't have
162     // incremental recompilation ever enabled.
163     fn_arg_names => { cdata.get_fn_arg_names(def_id.index) }
164     rendered_const => { cdata.get_rendered_const(def_id.index) }
165     impl_parent => { cdata.get_parent_impl(def_id.index) }
166     trait_of_item => { cdata.get_trait_of_item(def_id.index) }
167     const_is_rvalue_promotable_to_static => {
168         cdata.const_is_rvalue_promotable_to_static(def_id.index)
169     }
170     is_mir_available => { cdata.is_item_mir_available(def_id.index) }
171
172     dylib_dependency_formats => { Lrc::new(cdata.get_dylib_dependency_formats()) }
173     is_panic_runtime => { cdata.root.panic_runtime }
174     is_compiler_builtins => { cdata.root.compiler_builtins }
175     has_global_allocator => { cdata.root.has_global_allocator }
176     is_sanitizer_runtime => { cdata.root.sanitizer_runtime }
177     is_profiler_runtime => { cdata.root.profiler_runtime }
178     panic_strategy => { cdata.root.panic_strategy }
179     extern_crate => {
180         let r = Lrc::new(*cdata.extern_crate.lock());
181         r
182     }
183     is_no_builtins => { cdata.root.no_builtins }
184     impl_defaultness => { cdata.get_impl_defaultness(def_id.index) }
185     reachable_non_generics => {
186         let reachable_non_generics = tcx
187             .exported_symbols(cdata.cnum)
188             .iter()
189             .filter_map(|&(exported_symbol, export_level)| {
190                 if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
191                     return Some((def_id, export_level))
192                 } else {
193                     None
194                 }
195             })
196             .collect();
197
198         Lrc::new(reachable_non_generics)
199     }
200     native_libraries => { Lrc::new(cdata.get_native_libraries(tcx.sess)) }
201     foreign_modules => { Lrc::new(cdata.get_foreign_modules(tcx.sess)) }
202     plugin_registrar_fn => {
203         cdata.root.plugin_registrar_fn.map(|index| {
204             DefId { krate: def_id.krate, index }
205         })
206     }
207     derive_registrar_fn => {
208         cdata.root.macro_derive_registrar.map(|index| {
209             DefId { krate: def_id.krate, index }
210         })
211     }
212     crate_disambiguator => { cdata.root.disambiguator }
213     crate_hash => { cdata.root.hash }
214     original_crate_name => { cdata.root.name }
215
216     extra_filename => { cdata.root.extra_filename.clone() }
217
218
219     implementations_of_trait => {
220         let mut result = vec![];
221         let filter = Some(other);
222         cdata.get_implementations_for_trait(filter, &mut result);
223         Lrc::new(result)
224     }
225
226     all_trait_implementations => {
227         let mut result = vec![];
228         cdata.get_implementations_for_trait(None, &mut result);
229         Lrc::new(result)
230     }
231
232     visibility => { cdata.get_visibility(def_id.index) }
233     dep_kind => {
234         let r = *cdata.dep_kind.lock();
235         r
236     }
237     crate_name => { cdata.name }
238     item_children => {
239         let mut result = vec![];
240         cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess);
241         Lrc::new(result)
242     }
243     defined_lang_items => { Lrc::new(cdata.get_lang_items()) }
244     missing_lang_items => { Lrc::new(cdata.get_missing_lang_items()) }
245
246     missing_extern_crate_item => {
247         let r = match *cdata.extern_crate.borrow() {
248             Some(extern_crate) if !extern_crate.direct => true,
249             _ => false,
250         };
251         r
252     }
253
254     used_crate_source => { Lrc::new(cdata.source.clone()) }
255
256     exported_symbols => {
257         let cnum = cdata.cnum;
258         assert!(cnum != LOCAL_CRATE);
259
260         // If this crate is a custom derive crate, then we're not even going to
261         // link those in so we skip those crates.
262         if cdata.root.macro_derive_registrar.is_some() {
263             return Arc::new(Vec::new())
264         }
265
266         Arc::new(cdata.exported_symbols(tcx))
267     }
268 }
269
270 pub fn provide<'tcx>(providers: &mut Providers<'tcx>) {
271     fn is_const_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
272         let node_id = tcx.hir.as_local_node_id(def_id)
273                              .expect("Non-local call to local provider is_const_fn");
274
275         if let Some(fn_like) = FnLikeNode::from_node(tcx.hir.get(node_id)) {
276             fn_like.constness() == hir::Constness::Const
277         } else {
278             false
279         }
280     }
281
282     // FIXME(#44234) - almost all of these queries have no sub-queries and
283     // therefore no actual inputs, they're just reading tables calculated in
284     // resolve! Does this work? Unsure! That's what the issue is about
285     *providers = Providers {
286         is_const_fn,
287         is_dllimport_foreign_item: |tcx, id| {
288             tcx.native_library_kind(id) == Some(NativeLibraryKind::NativeUnknown)
289         },
290         is_statically_included_foreign_item: |tcx, id| {
291             match tcx.native_library_kind(id) {
292                 Some(NativeLibraryKind::NativeStatic) |
293                 Some(NativeLibraryKind::NativeStaticNobundle) => true,
294                 _ => false,
295             }
296         },
297         native_library_kind: |tcx, id| {
298             tcx.native_libraries(id.krate)
299                 .iter()
300                 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
301                 .find(|lib| {
302                     let fm_id = match lib.foreign_module {
303                         Some(id) => id,
304                         None => return false,
305                     };
306                     tcx.foreign_modules(id.krate)
307                         .iter()
308                         .find(|m| m.def_id == fm_id)
309                         .expect("failed to find foreign module")
310                         .foreign_items
311                         .contains(&id)
312                 })
313                 .map(|l| l.kind)
314         },
315         native_libraries: |tcx, cnum| {
316             assert_eq!(cnum, LOCAL_CRATE);
317             Lrc::new(native_libs::collect(tcx))
318         },
319         foreign_modules: |tcx, cnum| {
320             assert_eq!(cnum, LOCAL_CRATE);
321             Lrc::new(foreign_modules::collect(tcx))
322         },
323         link_args: |tcx, cnum| {
324             assert_eq!(cnum, LOCAL_CRATE);
325             Lrc::new(link_args::collect(tcx))
326         },
327
328         // Returns a map from a sufficiently visible external item (i.e. an
329         // external item that is visible from at least one local module) to a
330         // sufficiently visible parent (considering modules that re-export the
331         // external item to be parents).
332         visible_parent_map: |tcx, cnum| {
333             use std::collections::vec_deque::VecDeque;
334             use std::collections::hash_map::Entry;
335
336             assert_eq!(cnum, LOCAL_CRATE);
337             let mut visible_parent_map: DefIdMap<DefId> = DefIdMap();
338
339             // Issue 46112: We want the map to prefer the shortest
340             // paths when reporting the path to an item. Therefore we
341             // build up the map via a breadth-first search (BFS),
342             // which naturally yields minimal-length paths.
343             //
344             // Note that it needs to be a BFS over the whole forest of
345             // crates, not just each individual crate; otherwise you
346             // only get paths that are locally minimal with respect to
347             // whatever crate we happened to encounter first in this
348             // traversal, but not globally minimal across all crates.
349             let bfs_queue = &mut VecDeque::new();
350
351             // Preferring shortest paths alone does not guarantee a
352             // deterministic result; so sort by crate num to avoid
353             // hashtable iteration non-determinism. This only makes
354             // things as deterministic as crate-nums assignment is,
355             // which is to say, its not deterministic in general. But
356             // we believe that libstd is consistently assigned crate
357             // num 1, so it should be enough to resolve #46112.
358             let mut crates: Vec<CrateNum> = (*tcx.crates()).clone();
359             crates.sort();
360
361             for &cnum in crates.iter() {
362                 // Ignore crates without a corresponding local `extern crate` item.
363                 if tcx.missing_extern_crate_item(cnum) {
364                     continue
365                 }
366
367                 bfs_queue.push_back(DefId {
368                     krate: cnum,
369                     index: CRATE_DEF_INDEX
370                 });
371             }
372
373             // (restrict scope of mutable-borrow of `visible_parent_map`)
374             {
375                 let visible_parent_map = &mut visible_parent_map;
376                 let mut add_child = |bfs_queue: &mut VecDeque<_>,
377                                      child: &def::Export,
378                                      parent: DefId| {
379                     if child.vis != ty::Visibility::Public {
380                         return;
381                     }
382
383                     let child = child.def.def_id();
384
385                     match visible_parent_map.entry(child) {
386                         Entry::Occupied(mut entry) => {
387                             // If `child` is defined in crate `cnum`, ensure
388                             // that it is mapped to a parent in `cnum`.
389                             if child.krate == cnum && entry.get().krate != cnum {
390                                 entry.insert(parent);
391                             }
392                         }
393                         Entry::Vacant(entry) => {
394                             entry.insert(parent);
395                             bfs_queue.push_back(child);
396                         }
397                     }
398                 };
399
400                 while let Some(def) = bfs_queue.pop_front() {
401                     for child in tcx.item_children(def).iter() {
402                         add_child(bfs_queue, child, def);
403                     }
404                 }
405             }
406
407             Lrc::new(visible_parent_map)
408         },
409
410         ..*providers
411     };
412 }
413
414 impl cstore::CStore {
415     pub fn export_macros_untracked(&self, cnum: CrateNum) {
416         let data = self.get_crate_data(cnum);
417         let mut dep_kind = data.dep_kind.lock();
418         if *dep_kind == DepKind::UnexportedMacrosOnly {
419             *dep_kind = DepKind::MacrosOnly;
420         }
421     }
422
423     pub fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind {
424         let data = self.get_crate_data(cnum);
425         let r = *data.dep_kind.lock();
426         r
427     }
428
429     pub fn crate_edition_untracked(&self, cnum: CrateNum) -> Edition {
430         self.get_crate_data(cnum).root.edition
431     }
432
433     pub fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name> {
434         self.get_crate_data(def.krate).get_struct_field_names(def.index)
435     }
436
437     pub fn item_children_untracked(&self, def_id: DefId, sess: &Session) -> Vec<def::Export> {
438         let mut result = vec![];
439         self.get_crate_data(def_id.krate)
440             .each_child_of_item(def_id.index, |child| result.push(child), sess);
441         result
442     }
443
444     pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
445         let data = self.get_crate_data(id.krate);
446         if let Some(ref proc_macros) = data.proc_macros {
447             return LoadedMacro::ProcMacro(proc_macros[id.index.to_proc_macro_index()].1.clone());
448         } else if data.name == "proc_macro" &&
449                   self.get_crate_data(id.krate).item_name(id.index) == "quote" {
450             use syntax::ext::base::SyntaxExtension;
451             use syntax_ext::proc_macro_impl::BangProcMacro;
452
453             let ext = SyntaxExtension::ProcMacro {
454                 expander: Box::new(BangProcMacro { inner: ::proc_macro::quote }),
455                 allow_internal_unstable: true,
456                 edition: data.root.edition,
457             };
458             return LoadedMacro::ProcMacro(Lrc::new(ext));
459         }
460
461         let (name, def) = data.get_macro(id.index);
462         let source_name = FileName::Macros(name.to_string());
463
464         let filemap = sess.parse_sess.codemap().new_filemap(source_name, def.body);
465         let local_span = Span::new(filemap.start_pos, filemap.end_pos, NO_EXPANSION);
466         let body = filemap_to_stream(&sess.parse_sess, filemap, None);
467
468         // Mark the attrs as used
469         let attrs = data.get_item_attrs(id.index, sess);
470         for attr in attrs.iter() {
471             attr::mark_used(attr);
472         }
473
474         let name = data.def_key(id.index).disambiguated_data.data
475             .get_opt_name().expect("no name in load_macro");
476         sess.imported_macro_spans.borrow_mut()
477             .insert(local_span, (name.to_string(), data.get_span(id.index, sess)));
478
479         LoadedMacro::MacroDef(ast::Item {
480             ident: ast::Ident::from_str(&name.as_str()),
481             id: ast::DUMMY_NODE_ID,
482             span: local_span,
483             attrs: attrs.iter().cloned().collect(),
484             node: ast::ItemKind::MacroDef(ast::MacroDef {
485                 tokens: body.into(),
486                 legacy: def.legacy,
487             }),
488             vis: codemap::respan(local_span.shrink_to_lo(), ast::VisibilityKind::Inherited),
489             tokens: None,
490         })
491     }
492
493     pub fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssociatedItem {
494         self.get_crate_data(def.krate).get_associated_item(def.index)
495     }
496 }
497
498 impl CrateStore for cstore::CStore {
499     fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any> {
500         self.get_crate_data(krate)
501     }
502
503     fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics {
504         self.get_crate_data(def.krate).get_generics(def.index, sess)
505     }
506
507     fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol
508     {
509         self.get_crate_data(cnum).name
510     }
511
512     fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator
513     {
514         self.get_crate_data(cnum).root.disambiguator
515     }
516
517     fn crate_hash_untracked(&self, cnum: CrateNum) -> hir::svh::Svh
518     {
519         self.get_crate_data(cnum).root.hash
520     }
521
522     /// Returns the `DefKey` for a given `DefId`. This indicates the
523     /// parent `DefId` as well as some idea of what kind of data the
524     /// `DefId` refers to.
525     fn def_key(&self, def: DefId) -> DefKey {
526         // Note: loading the def-key (or def-path) for a def-id is not
527         // a *read* of its metadata. This is because the def-id is
528         // really just an interned shorthand for a def-path, which is the
529         // canonical name for an item.
530         //
531         // self.dep_graph.read(DepNode::MetaData(def));
532         self.get_crate_data(def.krate).def_key(def.index)
533     }
534
535     fn def_path(&self, def: DefId) -> DefPath {
536         // See `Note` above in `def_key()` for why this read is
537         // commented out:
538         //
539         // self.dep_graph.read(DepNode::MetaData(def));
540         self.get_crate_data(def.krate).def_path(def.index)
541     }
542
543     fn def_path_hash(&self, def: DefId) -> DefPathHash {
544         self.get_crate_data(def.krate).def_path_hash(def.index)
545     }
546
547     fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable> {
548         self.get_crate_data(cnum).def_path_table.clone()
549     }
550
551     fn crates_untracked(&self) -> Vec<CrateNum>
552     {
553         let mut result = vec![];
554         self.iter_crate_data(|cnum, _| result.push(cnum));
555         result
556     }
557
558     fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum>
559     {
560         self.do_extern_mod_stmt_cnum(emod_id)
561     }
562
563     fn postorder_cnums_untracked(&self) -> Vec<CrateNum> {
564         self.do_postorder_cnums_untracked()
565     }
566
567     fn encode_metadata<'a, 'tcx>(&self,
568                                  tcx: TyCtxt<'a, 'tcx, 'tcx>,
569                                  link_meta: &LinkMeta)
570                                  -> EncodedMetadata
571     {
572         encoder::encode_metadata(tcx, link_meta)
573     }
574
575     fn metadata_encoding_version(&self) -> &[u8]
576     {
577         schema::METADATA_HEADER
578     }
579 }