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