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