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;
20 use syntax::ast::{self, Ident, NodeId};
21 use syntax::source_map;
22 use syntax::feature_gate::UnstableFeatures;
23 use syntax::json::JsonEmitter;
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;
31 use std::cell::RefCell;
33 use rustc_data_structures::sync::{self, Lrc};
37 use crate::visit_ast::RustdocVisitor;
38 use crate::config::{Options as RustdocOptions, RenderOptions};
40 use crate::clean::{get_path_for_type, Clean, MAX_DEF_ID, AttributesExt};
41 use crate::html::render::RenderInfo;
45 pub use rustc::session::config::{Input, Options, CodegenOptions};
46 pub use rustc::session::search_paths::SearchPath;
48 pub type ExternalPaths = FxHashMap<DefId, (Vec<String>, clean::TypeKind)>;
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
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:
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>,
82 impl<'a, 'tcx, 'rcx> DocContext<'a, 'tcx, 'rcx> {
83 pub fn sess(&self) -> &session::Session {
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>,
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),
101 *self.ty_substs.borrow_mut() = old_tys;
102 *self.lt_substs.borrow_mut() = old_lts;
103 *self.ct_substs.borrow_mut() = old_cts;
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.
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 {
117 let next_id = if crate_num == LOCAL_CRATE {
122 .next_id(DefIndexAddressSpace::Low)
125 .def_path_table(crate_num)
126 .next_id(DefIndexAddressSpace::Low)
135 let mut fake_ids = self.fake_def_ids.borrow_mut();
137 let def_id = fake_ids.entry(crate_num).or_insert(start_def_id).clone();
142 index: DefIndex::from_array_index(
143 def_id.index.as_array_index() + 1,
144 def_id.index.address_space(),
149 MAX_DEF_ID.with(|m| {
151 .entry(def_id.krate.clone())
152 .or_insert(start_def_id);
155 self.all_fake_def_ids.borrow_mut().insert(def_id);
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) {
166 self.tcx.hir().as_local_node_id(def_id)
170 pub fn get_real_ty<F>(&self,
173 real_name: &Option<Ident>,
174 generics: &ty::Generics,
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");
181 segments.push(hir::PathSegment::new(
182 real_name.unwrap_or(last.ident),
186 self.generics_to_path_params(generics.clone()),
190 let new_path = hir::Path {
193 segments: HirVec::from_vec(segments),
197 node: hir::TyKind::Path(hir::QPath::Resolved(None, P(new_path))),
199 hir_id: hir::DUMMY_HIR_ID,
203 pub fn generics_to_path_params(&self, generics: ty::Generics) -> hir::GenericArgs {
204 let mut args = vec![];
206 for param in generics.params.iter() {
208 ty::GenericParamDefKind::Lifetime => {
209 let name = if param.name == "" {
210 hir::ParamName::Plain(keywords::StaticLifetime.ident())
212 hir::ParamName::Plain(ast::Ident::from_interned_str(param.name))
215 args.push(hir::GenericArg::Lifetime(hir::Lifetime {
216 hir_id: hir::DUMMY_HIR_ID,
218 name: hir::LifetimeName::Param(name),
221 ty::GenericParamDefKind::Type { .. } => {
222 args.push(hir::GenericArg::Type(self.ty_param_to_ty(param.clone())));
228 args: HirVec::from_vec(args),
229 bindings: HirVec::new(),
230 parenthesized: false,
234 pub fn ty_param_to_ty(&self, param: ty::GenericParamDef) -> hir::Ty {
235 debug!("ty_param_to_ty({:?}) {:?}", param, param.def_id);
237 node: hir::TyKind::Path(hir::QPath::Resolved(
241 def: Def::TyParam(param.def_id),
242 segments: HirVec::from_vec(vec![
243 hir::PathSegment::from_ident(Ident::from_interned_str(param.name))
248 hir_id: hir::DUMMY_HIR_ID,
253 pub trait DocAccessLevels {
254 fn is_doc_reachable(&self, did: DefId) -> bool;
257 impl DocAccessLevels for AccessLevels<DefId> {
258 fn is_doc_reachable(&self, did: DefId) -> bool {
263 /// Creates a new diagnostic `Handler` that can be used to emit warnings and errors.
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,
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(
279 source_map.map(|cm| cm as _),
281 sessopts.debugging_opts.teach,
282 ).ui_testing(ui_testing)
284 ErrorOutputType::Json(pretty) => {
285 let source_map = source_map.unwrap_or_else(
286 || Lrc::new(source_map::SourceMap::new(sessopts.file_path_mapping())));
292 ).ui_testing(ui_testing)
295 ErrorOutputType::Short(color_config) => Box::new(
296 EmitterWriter::stderr(
298 source_map.map(|cm| cm as _),
304 errors::Handler::with_emitter_and_flags(
306 errors::HandlerFlags {
307 can_emit_warnings: true,
309 report_delayed_bugs: false,
310 external_macro_backtrace: false,
316 pub fn run_core(options: RustdocOptions) -> (clean::Crate, RenderInfo, RenderOptions, Vec<String>) {
317 // Parse, resolve, and typecheck the given crate.
341 let cpath = Some(input.clone());
342 let input = Input::File(input);
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;
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()];
358 whitelisted_lints.extend(lint_opts.iter().map(|(lint, _)| lint).cloned());
360 let lints = lint::builtin::HardwiredLints.get_lints()
362 .chain(rustc_lint::SoftLints.get_lints().into_iter())
364 if lint.name == warnings_lint_name ||
365 lint.name == intra_link_resolution_failure_name {
368 Some((lint.name_lower(), lint::Allow))
371 .chain(lint_opts.into_iter())
372 .collect::<Vec<_>>();
374 let host_triple = TargetTriple::from_triple(config::host_triple());
375 // plays with error output here!
376 let sessopts = config::Options {
379 crate_types: vec![config::CrateType::Rlib],
380 lint_opts: if !display_warnings {
385 lint_cap: Some(lint_cap.unwrap_or_else(|| lint::Forbid)),
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(),
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);
405 let mut sess = session::build_session_(
406 sessopts, cpath, diagnostic_handler, source_map, Default::default(),
409 lint::builtin::HardwiredLints.get_lints()
411 .chain(rustc_lint::SoftLints.get_lints().into_iter())
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) {
422 sess.driver_lint_caps.insert(lint::LintId::of(l),
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));
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;
434 let control = &driver::CompileController::basic();
436 let krate = match driver::phase_1_parse_input(control, &sess, &input) {
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),
449 let mut crate_loader = CrateLoader::new(&sess, &cstore, &name);
451 let resolver_arenas = resolve::Resolver::arenas();
452 let result = driver::phase_2_configure_and_expand_inner(&sess,
461 let driver::InnerExpansionResult {
465 } = abort_on_err(result, &sess);
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)
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,
491 let resolver = RefCell::new(resolver);
492 driver::phase_3_run_analysis_passes(&*codegen_backend,
503 sess.fatal("Compilation failed, aborting rustdoc");
506 let access_levels = tcx.privacy_access_levels(LOCAL_CRATE);
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))
516 let send_trait = if crate_name == Some("core".to_string()) {
517 clean::path_to_def_local(&tcx, &["marker", "Send"])
519 clean::path_to_def(&tcx, &["core", "marker", "Send"])
522 let mut renderinfo = RenderInfo::default();
523 renderinfo.access_levels = access_levels;
525 let ctxt = DocContext {
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(),
543 debug!("crate: {:?}", tcx.hir().krate());
546 let mut v = RustdocVisitor::new(&ctxt);
547 v.visit(tcx.hir().krate());
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");
556 if name == "no_default_passes" {
557 msg.help("you may want to use `#![doc(document_private_items)]`");
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();
568 let name = attr.name().map(|s| s.as_str());
569 let name = name.as_ref().map(|s| &s[..]);
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;
577 } else if let Some(value) = attr.value_str() {
578 let sink = match name {
580 report_deprecated_attr("passes = \"...\"", diag);
584 report_deprecated_attr("plugins = \"...\"", diag);
585 eprintln!("WARNING: #![doc(plugins = \"...\")] no longer functions; \
586 see CVE-2018-1000622");
591 for p in value.as_str().split_whitespace() {
592 sink.push(p.to_string());
596 if attr.is_word() && name == Some("document_private_items") {
597 if default_passes == passes::DefaultPassOption::Default {
598 default_passes = passes::DefaultPassOption::Private;
603 let mut passes: Vec<String> =
604 passes::defaults(default_passes).iter().map(|p| p.to_string()).collect();
605 passes.extend(manual_passes);
607 info!("Executing passes");
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),
616 ctxt.sess().abort_if_errors();
618 (krate, ctxt.renderinfo.into_inner(), render_options, passes)