]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/core.rs
Rollup merge of #58802 - nnethercote:inline-record_layout, r=oli-obk
[rust.git] / src / librustdoc / core.rs
1 use rustc_lint;
2 use rustc_driver::{driver, abort_on_err};
3 use rustc::session::{self, config};
4 use rustc::hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CrateNum, LOCAL_CRATE};
5 use rustc::hir::def::Def;
6 use rustc::hir::{self, HirVec};
7 use rustc::middle::cstore::CrateStore;
8 use rustc::middle::privacy::AccessLevels;
9 use rustc::ty::{self, TyCtxt, AllArenas};
10 use rustc::hir::map as hir_map;
11 use rustc::lint::{self, LintPass};
12 use rustc::session::config::ErrorOutputType;
13 use rustc::util::nodemap::{FxHashMap, FxHashSet};
14 use rustc_interface::util;
15 use rustc_resolve as resolve;
16 use rustc_metadata::creader::CrateLoader;
17 use rustc_metadata::cstore::CStore;
18 use rustc_target::spec::TargetTriple;
19
20 use syntax::ast::{self, Ident, NodeId};
21 use syntax::source_map;
22 use syntax::feature_gate::UnstableFeatures;
23 use syntax::json::JsonEmitter;
24 use syntax::ptr::P;
25 use syntax::symbol::keywords;
26 use syntax_pos::DUMMY_SP;
27 use errors::{self, FatalError};
28 use errors::emitter::{Emitter, EmitterWriter};
29 use parking_lot::ReentrantMutex;
30
31 use std::cell::RefCell;
32 use std::mem;
33 use rustc_data_structures::sync::{self, Lrc};
34 use std::rc::Rc;
35 use std::sync::Arc;
36
37 use crate::visit_ast::RustdocVisitor;
38 use crate::config::{Options as RustdocOptions, RenderOptions};
39 use crate::clean;
40 use crate::clean::{get_path_for_type, Clean, MAX_DEF_ID, AttributesExt};
41 use crate::html::render::RenderInfo;
42
43 use crate::passes;
44
45 pub use rustc::session::config::{Input, Options, CodegenOptions};
46 pub use rustc::session::search_paths::SearchPath;
47
48 pub type ExternalPaths = FxHashMap<DefId, (Vec<String>, clean::TypeKind)>;
49
50 pub struct DocContext<'a, 'tcx: 'a, 'rcx: 'a> {
51     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
52     pub resolver: &'a RefCell<resolve::Resolver<'rcx>>,
53     /// The stack of module NodeIds up till this point
54     pub crate_name: Option<String>,
55     pub cstore: Rc<CStore>,
56     /// Later on moved into `html::render::CACHE_KEY`
57     pub renderinfo: RefCell<RenderInfo>,
58     /// Later on moved through `clean::Crate` into `html::render::CACHE_KEY`
59     pub external_traits: Arc<ReentrantMutex<RefCell<FxHashMap<DefId, clean::Trait>>>>,
60     /// Used while populating `external_traits` to ensure we don't process the same trait twice at
61     /// the same time.
62     pub active_extern_traits: RefCell<Vec<DefId>>,
63     // The current set of type and lifetime substitutions,
64     // for expanding type aliases at the HIR level:
65
66     /// Table type parameter definition -> substituted type
67     pub ty_substs: RefCell<FxHashMap<Def, clean::Type>>,
68     /// Table `NodeId` of lifetime parameter definition -> substituted lifetime
69     pub lt_substs: RefCell<FxHashMap<DefId, clean::Lifetime>>,
70     /// Table node id of const parameter definition -> substituted const
71     pub ct_substs: RefCell<FxHashMap<Def, clean::Constant>>,
72     /// Table DefId of `impl Trait` in argument position -> bounds
73     pub impl_trait_bounds: RefCell<FxHashMap<DefId, Vec<clean::GenericBound>>>,
74     pub send_trait: Option<DefId>,
75     pub fake_def_ids: RefCell<FxHashMap<CrateNum, DefId>>,
76     pub all_fake_def_ids: RefCell<FxHashSet<DefId>>,
77     /// Maps (type_id, trait_id) -> auto trait impl
78     pub generated_synthetics: RefCell<FxHashSet<(DefId, DefId)>>,
79     pub all_traits: Vec<DefId>,
80 }
81
82 impl<'a, 'tcx, 'rcx> DocContext<'a, 'tcx, 'rcx> {
83     pub fn sess(&self) -> &session::Session {
84         &self.tcx.sess
85     }
86
87     /// Call the closure with the given parameters set as
88     /// the substitutions for a type alias' RHS.
89     pub fn enter_alias<F, R>(&self,
90                              ty_substs: FxHashMap<Def, clean::Type>,
91                              lt_substs: FxHashMap<DefId, clean::Lifetime>,
92                              ct_substs: FxHashMap<Def, clean::Constant>,
93                              f: F) -> R
94     where F: FnOnce() -> R {
95         let (old_tys, old_lts, old_cts) = (
96             mem::replace(&mut *self.ty_substs.borrow_mut(), ty_substs),
97             mem::replace(&mut *self.lt_substs.borrow_mut(), lt_substs),
98             mem::replace(&mut *self.ct_substs.borrow_mut(), ct_substs),
99         );
100         let r = f();
101         *self.ty_substs.borrow_mut() = old_tys;
102         *self.lt_substs.borrow_mut() = old_lts;
103         *self.ct_substs.borrow_mut() = old_cts;
104         r
105     }
106
107     // This is an ugly hack, but it's the simplest way to handle synthetic impls without greatly
108     // refactoring either librustdoc or librustc. In particular, allowing new DefIds to be
109     // registered after the AST is constructed would require storing the defid mapping in a
110     // RefCell, decreasing the performance for normal compilation for very little gain.
111     //
112     // Instead, we construct 'fake' def ids, which start immediately after the last DefId in
113     // DefIndexAddressSpace::Low. In the Debug impl for clean::Item, we explicitly check for fake
114     // def ids, as we'll end up with a panic if we use the DefId Debug impl for fake DefIds
115     pub fn next_def_id(&self, crate_num: CrateNum) -> DefId {
116         let start_def_id = {
117             let next_id = if crate_num == LOCAL_CRATE {
118                 self.tcx
119                     .hir()
120                     .definitions()
121                     .def_path_table()
122                     .next_id(DefIndexAddressSpace::Low)
123             } else {
124                 self.cstore
125                     .def_path_table(crate_num)
126                     .next_id(DefIndexAddressSpace::Low)
127             };
128
129             DefId {
130                 krate: crate_num,
131                 index: next_id,
132             }
133         };
134
135         let mut fake_ids = self.fake_def_ids.borrow_mut();
136
137         let def_id = fake_ids.entry(crate_num).or_insert(start_def_id).clone();
138         fake_ids.insert(
139             crate_num,
140             DefId {
141                 krate: crate_num,
142                 index: DefIndex::from_array_index(
143                     def_id.index.as_array_index() + 1,
144                     def_id.index.address_space(),
145                 ),
146             },
147         );
148
149         MAX_DEF_ID.with(|m| {
150             m.borrow_mut()
151                 .entry(def_id.krate.clone())
152                 .or_insert(start_def_id);
153         });
154
155         self.all_fake_def_ids.borrow_mut().insert(def_id);
156
157         def_id.clone()
158     }
159
160     /// Like the function of the same name on the HIR map, but skips calling it on fake DefIds.
161     /// (This avoids a slice-index-out-of-bounds panic.)
162     pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
163         if self.all_fake_def_ids.borrow().contains(&def_id) {
164             None
165         } else {
166             self.tcx.hir().as_local_node_id(def_id)
167         }
168     }
169
170     pub fn get_real_ty<F>(&self,
171                           def_id: DefId,
172                           def_ctor: &F,
173                           real_name: &Option<Ident>,
174                           generics: &ty::Generics,
175     ) -> hir::Ty
176     where F: Fn(DefId) -> Def {
177         let path = get_path_for_type(self.tcx, def_id, def_ctor);
178         let mut segments = path.segments.into_vec();
179         let last = segments.pop().expect("segments were empty");
180
181         segments.push(hir::PathSegment::new(
182             real_name.unwrap_or(last.ident),
183             None,
184             None,
185             None,
186             self.generics_to_path_params(generics.clone()),
187             false,
188         ));
189
190         let new_path = hir::Path {
191             span: path.span,
192             def: path.def,
193             segments: HirVec::from_vec(segments),
194         };
195
196         hir::Ty {
197             node: hir::TyKind::Path(hir::QPath::Resolved(None, P(new_path))),
198             span: DUMMY_SP,
199             hir_id: hir::DUMMY_HIR_ID,
200         }
201     }
202
203     pub fn generics_to_path_params(&self, generics: ty::Generics) -> hir::GenericArgs {
204         let mut args = vec![];
205
206         for param in generics.params.iter() {
207             match param.kind {
208                 ty::GenericParamDefKind::Lifetime => {
209                     let name = if param.name == "" {
210                         hir::ParamName::Plain(keywords::StaticLifetime.ident())
211                     } else {
212                         hir::ParamName::Plain(ast::Ident::from_interned_str(param.name))
213                     };
214
215                     args.push(hir::GenericArg::Lifetime(hir::Lifetime {
216                         hir_id: hir::DUMMY_HIR_ID,
217                         span: DUMMY_SP,
218                         name: hir::LifetimeName::Param(name),
219                     }));
220                 }
221                 ty::GenericParamDefKind::Type { .. } => {
222                     args.push(hir::GenericArg::Type(self.ty_param_to_ty(param.clone())));
223                 }
224             }
225         }
226
227         hir::GenericArgs {
228             args: HirVec::from_vec(args),
229             bindings: HirVec::new(),
230             parenthesized: false,
231         }
232     }
233
234     pub fn ty_param_to_ty(&self, param: ty::GenericParamDef) -> hir::Ty {
235         debug!("ty_param_to_ty({:?}) {:?}", param, param.def_id);
236         hir::Ty {
237             node: hir::TyKind::Path(hir::QPath::Resolved(
238                 None,
239                 P(hir::Path {
240                     span: DUMMY_SP,
241                     def: Def::TyParam(param.def_id),
242                     segments: HirVec::from_vec(vec![
243                         hir::PathSegment::from_ident(Ident::from_interned_str(param.name))
244                     ]),
245                 }),
246             )),
247             span: DUMMY_SP,
248             hir_id: hir::DUMMY_HIR_ID,
249         }
250     }
251 }
252
253 pub trait DocAccessLevels {
254     fn is_doc_reachable(&self, did: DefId) -> bool;
255 }
256
257 impl DocAccessLevels for AccessLevels<DefId> {
258     fn is_doc_reachable(&self, did: DefId) -> bool {
259         self.is_public(did)
260     }
261 }
262
263 /// Creates a new diagnostic `Handler` that can be used to emit warnings and errors.
264 ///
265 /// If the given `error_format` is `ErrorOutputType::Json` and no `SourceMap` is given, a new one
266 /// will be created for the handler.
267 pub fn new_handler(error_format: ErrorOutputType,
268                    source_map: Option<Lrc<source_map::SourceMap>>,
269                    treat_err_as_bug: bool,
270                    ui_testing: bool,
271 ) -> errors::Handler {
272     // rustdoc doesn't override (or allow to override) anything from this that is relevant here, so
273     // stick to the defaults
274     let sessopts = Options::default();
275     let emitter: Box<dyn Emitter + sync::Send> = match error_format {
276         ErrorOutputType::HumanReadable(color_config) => Box::new(
277             EmitterWriter::stderr(
278                 color_config,
279                 source_map.map(|cm| cm as _),
280                 false,
281                 sessopts.debugging_opts.teach,
282             ).ui_testing(ui_testing)
283         ),
284         ErrorOutputType::Json(pretty) => {
285             let source_map = source_map.unwrap_or_else(
286                 || Lrc::new(source_map::SourceMap::new(sessopts.file_path_mapping())));
287             Box::new(
288                 JsonEmitter::stderr(
289                     None,
290                     source_map,
291                     pretty,
292                 ).ui_testing(ui_testing)
293             )
294         },
295         ErrorOutputType::Short(color_config) => Box::new(
296             EmitterWriter::stderr(
297                 color_config,
298                 source_map.map(|cm| cm as _),
299                 true,
300                 false)
301         ),
302     };
303
304     errors::Handler::with_emitter_and_flags(
305         emitter,
306         errors::HandlerFlags {
307             can_emit_warnings: true,
308             treat_err_as_bug,
309             report_delayed_bugs: false,
310             external_macro_backtrace: false,
311             ..Default::default()
312         },
313     )
314 }
315
316 pub fn run_core(options: RustdocOptions) -> (clean::Crate, RenderInfo, RenderOptions, Vec<String>) {
317     // Parse, resolve, and typecheck the given crate.
318
319     let RustdocOptions {
320         input,
321         crate_name,
322         error_format,
323         libs,
324         externs,
325         cfgs,
326         codegen_options,
327         debugging_options,
328         target,
329         edition,
330         maybe_sysroot,
331         lint_opts,
332         describe_lints,
333         lint_cap,
334         mut default_passes,
335         mut manual_passes,
336         display_warnings,
337         render_options,
338         ..
339     } = options;
340
341     let cpath = Some(input.clone());
342     let input = Input::File(input);
343
344     let intra_link_resolution_failure_name = lint::builtin::INTRA_DOC_LINK_RESOLUTION_FAILURE.name;
345     let warnings_lint_name = lint::builtin::WARNINGS.name;
346     let missing_docs = rustc_lint::builtin::MISSING_DOCS.name;
347     let missing_doc_example = rustc_lint::builtin::MISSING_DOC_CODE_EXAMPLES.name;
348     let private_doc_tests = rustc_lint::builtin::PRIVATE_DOC_TESTS.name;
349
350     // In addition to those specific lints, we also need to whitelist those given through
351     // command line, otherwise they'll get ignored and we don't want that.
352     let mut whitelisted_lints = vec![warnings_lint_name.to_owned(),
353                                      intra_link_resolution_failure_name.to_owned(),
354                                      missing_docs.to_owned(),
355                                      missing_doc_example.to_owned(),
356                                      private_doc_tests.to_owned()];
357
358     whitelisted_lints.extend(lint_opts.iter().map(|(lint, _)| lint).cloned());
359
360     let lints = lint::builtin::HardwiredLints.get_lints()
361                     .into_iter()
362                     .chain(rustc_lint::SoftLints.get_lints().into_iter())
363                     .filter_map(|lint| {
364                         if lint.name == warnings_lint_name ||
365                            lint.name == intra_link_resolution_failure_name {
366                             None
367                         } else {
368                             Some((lint.name_lower(), lint::Allow))
369                         }
370                     })
371                     .chain(lint_opts.into_iter())
372                     .collect::<Vec<_>>();
373
374     let host_triple = TargetTriple::from_triple(config::host_triple());
375     // plays with error output here!
376     let sessopts = config::Options {
377         maybe_sysroot,
378         search_paths: libs,
379         crate_types: vec![config::CrateType::Rlib],
380         lint_opts: if !display_warnings {
381             lints
382         } else {
383             vec![]
384         },
385         lint_cap: Some(lint_cap.unwrap_or_else(|| lint::Forbid)),
386         cg: codegen_options,
387         externs,
388         target_triple: target.unwrap_or(host_triple),
389         // Ensure that rustdoc works even if rustc is feature-staged
390         unstable_features: UnstableFeatures::Allow,
391         actually_rustdoc: true,
392         debugging_opts: debugging_options.clone(),
393         error_format,
394         edition,
395         describe_lints,
396         ..Options::default()
397     };
398     driver::spawn_thread_pool(sessopts, move |sessopts| {
399         let source_map = Lrc::new(source_map::SourceMap::new(sessopts.file_path_mapping()));
400         let diagnostic_handler = new_handler(error_format,
401                                              Some(source_map.clone()),
402                                              debugging_options.treat_err_as_bug,
403                                              debugging_options.ui_testing);
404
405         let mut sess = session::build_session_(
406             sessopts, cpath, diagnostic_handler, source_map, Default::default(),
407         );
408
409         lint::builtin::HardwiredLints.get_lints()
410                                      .into_iter()
411                                      .chain(rustc_lint::SoftLints.get_lints().into_iter())
412                                      .filter_map(|lint| {
413                                          // We don't want to whitelist *all* lints so let's
414                                          // ignore those ones.
415                                          if whitelisted_lints.iter().any(|l| &lint.name == l) {
416                                              None
417                                          } else {
418                                              Some(lint)
419                                          }
420                                      })
421                                      .for_each(|l| {
422                                          sess.driver_lint_caps.insert(lint::LintId::of(l),
423                                                                       lint::Allow);
424                                      });
425
426         let codegen_backend = util::get_codegen_backend(&sess);
427         let cstore = Rc::new(CStore::new(codegen_backend.metadata_loader()));
428         rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
429
430         let mut cfg = config::build_configuration(&sess, config::parse_cfgspecs(cfgs));
431         util::add_configuration(&mut cfg, &sess, &*codegen_backend);
432         sess.parse_sess.config = cfg;
433
434         let control = &driver::CompileController::basic();
435
436         let krate = match driver::phase_1_parse_input(control, &sess, &input) {
437             Ok(krate) => krate,
438             Err(mut e) => {
439                 e.emit();
440                 FatalError.raise();
441             }
442         };
443
444         let name = match crate_name {
445             Some(ref crate_name) => crate_name.clone(),
446             None => ::rustc_codegen_utils::link::find_crate_name(Some(&sess), &krate.attrs, &input),
447         };
448
449         let mut crate_loader = CrateLoader::new(&sess, &cstore, &name);
450
451         let resolver_arenas = resolve::Resolver::arenas();
452         let result = driver::phase_2_configure_and_expand_inner(&sess,
453                                                         &cstore,
454                                                         krate,
455                                                         None,
456                                                         &name,
457                                                         None,
458                                                         &resolver_arenas,
459                                                         &mut crate_loader,
460                                                         |_| Ok(()));
461         let driver::InnerExpansionResult {
462             mut hir_forest,
463             resolver,
464             ..
465         } = abort_on_err(result, &sess);
466
467         // We need to hold on to the complete resolver, so we clone everything
468         // for the analysis passes to use. Suboptimal, but necessary in the
469         // current architecture.
470         let defs = resolver.definitions.clone();
471         let resolutions = ty::Resolutions {
472             freevars: resolver.freevars.clone(),
473             export_map: resolver.export_map.clone(),
474             trait_map: resolver.trait_map.clone(),
475             glob_map: resolver.glob_map.clone(),
476             maybe_unused_trait_imports: resolver.maybe_unused_trait_imports.clone(),
477             maybe_unused_extern_crates: resolver.maybe_unused_extern_crates.clone(),
478             extern_prelude: resolver.extern_prelude.iter().map(|(ident, entry)| {
479                 (ident.name, entry.introduced_by_item)
480             }).collect(),
481         };
482
483         let mut arenas = AllArenas::new();
484         let hir_map = hir_map::map_crate(&sess, &*cstore, &mut hir_forest, &defs);
485         let output_filenames = util::build_output_filenames(&input,
486                                                             &None,
487                                                             &None,
488                                                             &[],
489                                                             &sess);
490
491         let resolver = RefCell::new(resolver);
492         driver::phase_3_run_analysis_passes(&*codegen_backend,
493                                             control,
494                                             &sess,
495                                             &*cstore,
496                                             hir_map,
497                                             resolutions,
498                                             &mut arenas,
499                                             &name,
500                                             &output_filenames,
501                                             |tcx, _, result| {
502             if result.is_err() {
503                 sess.fatal("Compilation failed, aborting rustdoc");
504             }
505
506             let access_levels = tcx.privacy_access_levels(LOCAL_CRATE);
507
508             // Convert from a NodeId set to a DefId set since we don't always have easy access
509             // to the map from defid -> nodeid
510             let access_levels = AccessLevels {
511                 map: access_levels.map.iter()
512                                     .map(|(&k, &v)| (tcx.hir().local_def_id(k), v))
513                                     .collect()
514             };
515
516             let send_trait = if crate_name == Some("core".to_string()) {
517                 clean::path_to_def_local(&tcx, &["marker", "Send"])
518             } else {
519                 clean::path_to_def(&tcx, &["core", "marker", "Send"])
520             };
521
522             let mut renderinfo = RenderInfo::default();
523             renderinfo.access_levels = access_levels;
524
525             let ctxt = DocContext {
526                 tcx,
527                 resolver: &resolver,
528                 crate_name,
529                 cstore: cstore.clone(),
530                 external_traits: Default::default(),
531                 active_extern_traits: Default::default(),
532                 renderinfo: RefCell::new(renderinfo),
533                 ty_substs: Default::default(),
534                 lt_substs: Default::default(),
535                 ct_substs: Default::default(),
536                 impl_trait_bounds: Default::default(),
537                 send_trait: send_trait,
538                 fake_def_ids: Default::default(),
539                 all_fake_def_ids: Default::default(),
540                 generated_synthetics: Default::default(),
541                 all_traits: tcx.all_traits(LOCAL_CRATE).to_vec(),
542             };
543             debug!("crate: {:?}", tcx.hir().krate());
544
545             let mut krate = {
546                 let mut v = RustdocVisitor::new(&ctxt);
547                 v.visit(tcx.hir().krate());
548                 v.clean(&ctxt)
549             };
550
551             fn report_deprecated_attr(name: &str, diag: &errors::Handler) {
552                 let mut msg = diag.struct_warn(&format!("the `#![doc({})]` attribute is \
553                                                          considered deprecated", name));
554                 msg.warn("please see https://github.com/rust-lang/rust/issues/44136");
555
556                 if name == "no_default_passes" {
557                     msg.help("you may want to use `#![doc(document_private_items)]`");
558                 }
559
560                 msg.emit();
561             }
562
563             // Process all of the crate attributes, extracting plugin metadata along
564             // with the passes which we are supposed to run.
565             for attr in krate.module.as_ref().unwrap().attrs.lists("doc") {
566                 let diag = ctxt.sess().diagnostic();
567
568                 let name = attr.name().map(|s| s.as_str());
569                 let name = name.as_ref().map(|s| &s[..]);
570                 if attr.is_word() {
571                     if name == Some("no_default_passes") {
572                         report_deprecated_attr("no_default_passes", diag);
573                         if default_passes == passes::DefaultPassOption::Default {
574                             default_passes = passes::DefaultPassOption::None;
575                         }
576                     }
577                 } else if let Some(value) = attr.value_str() {
578                     let sink = match name {
579                         Some("passes") => {
580                             report_deprecated_attr("passes = \"...\"", diag);
581                             &mut manual_passes
582                         },
583                         Some("plugins") => {
584                             report_deprecated_attr("plugins = \"...\"", diag);
585                             eprintln!("WARNING: #![doc(plugins = \"...\")] no longer functions; \
586                                       see CVE-2018-1000622");
587                             continue
588                         },
589                         _ => continue,
590                     };
591                     for p in value.as_str().split_whitespace() {
592                         sink.push(p.to_string());
593                     }
594                 }
595
596                 if attr.is_word() && name == Some("document_private_items") {
597                     if default_passes == passes::DefaultPassOption::Default {
598                         default_passes = passes::DefaultPassOption::Private;
599                     }
600                 }
601             }
602
603             let mut passes: Vec<String> =
604                 passes::defaults(default_passes).iter().map(|p| p.to_string()).collect();
605             passes.extend(manual_passes);
606
607             info!("Executing passes");
608
609             for pass in &passes {
610                 match passes::find_pass(pass).map(|p| p.pass) {
611                     Some(pass) => krate = pass(krate, &ctxt),
612                     None => error!("unknown pass {}, skipping", *pass),
613                 }
614             }
615
616             ctxt.sess().abort_if_errors();
617
618             (krate, ctxt.renderinfo.into_inner(), render_options, passes)
619         })
620     })
621 }