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