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