2 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
3 use rustc_data_structures::sync::{self, Lrc};
4 use rustc_driver::abort_on_err;
5 use rustc_errors::emitter::{Emitter, EmitterWriter};
6 use rustc_errors::json::JsonEmitter;
7 use rustc_feature::UnstableFeatures;
8 use rustc_hir::def::{Namespace::TypeNS, Res};
9 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
12 intravisit::{self, NestedVisitorMap, Visitor},
15 use rustc_interface::{interface, Queries};
16 use rustc_middle::hir::map::Map;
17 use rustc_middle::middle::privacy::AccessLevels;
18 use rustc_middle::ty::{ParamEnv, Ty, TyCtxt};
19 use rustc_resolve as resolve;
20 use rustc_session::config::{self, CrateType, ErrorOutputType};
21 use rustc_session::lint;
22 use rustc_session::DiagnosticOutput;
23 use rustc_session::Session;
24 use rustc_span::source_map;
25 use rustc_span::symbol::sym;
28 use std::cell::RefCell;
29 use std::collections::hash_map::Entry;
34 use crate::clean::inline::build_external_trait;
35 use crate::clean::{AttributesExt, TraitWithExtraInfo, MAX_DEF_IDX};
36 use crate::config::{Options as RustdocOptions, OutputFormat, RenderOptions};
37 use crate::formats::cache::Cache;
38 use crate::passes::{self, Condition::*, ConditionalPass};
40 crate use rustc_session::config::{DebuggingOptions, Input, Options};
42 crate struct DocContext<'tcx> {
43 crate tcx: TyCtxt<'tcx>,
44 /// Name resolver. Used for intra-doc links.
46 /// The `Rc<RefCell<...>>` wrapping is needed because that is what's returned by
47 /// [`Queries::expansion()`].
48 // FIXME: see if we can get rid of this RefCell somehow
49 crate resolver: Rc<RefCell<interface::BoxedResolver>>,
50 /// Used for normalization.
52 /// Most of this logic is copied from rustc_lint::late.
53 crate param_env: ParamEnv<'tcx>,
54 /// Later on moved through `clean::Crate` into `cache`
55 crate external_traits: Rc<RefCell<FxHashMap<DefId, clean::TraitWithExtraInfo>>>,
56 /// Used while populating `external_traits` to ensure we don't process the same trait twice at
58 crate active_extern_traits: FxHashSet<DefId>,
59 // The current set of type and lifetime substitutions,
60 // for expanding type aliases at the HIR level:
61 /// Table `DefId` of type parameter -> substituted type
62 crate ty_substs: FxHashMap<DefId, clean::Type>,
63 /// Table `DefId` of lifetime parameter -> substituted lifetime
64 crate lt_substs: FxHashMap<DefId, clean::Lifetime>,
65 /// Table `DefId` of const parameter -> substituted const
66 crate ct_substs: FxHashMap<DefId, clean::Constant>,
67 /// Table synthetic type parameter for `impl Trait` in argument position -> bounds
68 crate impl_trait_bounds: FxHashMap<ImplTraitParam, Vec<clean::GenericBound>>,
69 crate fake_def_ids: FxHashMap<CrateNum, DefIndex>,
70 /// Auto-trait or blanket impls processed so far, as `(self_ty, trait_def_id)`.
71 // FIXME(eddyb) make this a `ty::TraitRef<'tcx>` set.
72 crate generated_synthetics: FxHashSet<(Ty<'tcx>, DefId)>,
73 crate auto_traits: Vec<DefId>,
74 /// The options given to rustdoc that could be relevant to a pass.
75 crate render_options: RenderOptions,
76 /// The traits in scope for a given module.
78 /// See `collect_intra_doc_links::traits_implemented_by` for more details.
79 /// `map<module, set<trait>>`
80 crate module_trait_cache: FxHashMap<DefId, FxHashSet<DefId>>,
81 /// This same cache is used throughout rustdoc, including in [`crate::html::render`].
83 /// Used by [`clean::inline`] to tell if an item has already been inlined.
84 crate inlined: FxHashSet<DefId>,
85 /// Used by `calculate_doc_coverage`.
86 crate output_format: OutputFormat,
89 impl<'tcx> DocContext<'tcx> {
90 crate fn sess(&self) -> &'tcx Session {
94 crate fn with_param_env<T, F: FnOnce(&mut Self) -> T>(&mut self, def_id: DefId, f: F) -> T {
95 let old_param_env = mem::replace(&mut self.param_env, self.tcx.param_env(def_id));
97 self.param_env = old_param_env;
101 crate fn enter_resolver<F, R>(&self, f: F) -> R
103 F: FnOnce(&mut resolve::Resolver<'_>) -> R,
105 self.resolver.borrow_mut().access(f)
108 /// Call the closure with the given parameters set as
109 /// the substitutions for a type alias' RHS.
110 crate fn enter_alias<F, R>(
112 ty_substs: FxHashMap<DefId, clean::Type>,
113 lt_substs: FxHashMap<DefId, clean::Lifetime>,
114 ct_substs: FxHashMap<DefId, clean::Constant>,
118 F: FnOnce(&mut Self) -> R,
120 let (old_tys, old_lts, old_cts) = (
121 mem::replace(&mut self.ty_substs, ty_substs),
122 mem::replace(&mut self.lt_substs, lt_substs),
123 mem::replace(&mut self.ct_substs, ct_substs),
126 self.ty_substs = old_tys;
127 self.lt_substs = old_lts;
128 self.ct_substs = old_cts;
132 /// Create a new "fake" [`DefId`].
134 /// This is an ugly hack, but it's the simplest way to handle synthetic impls without greatly
135 /// refactoring either rustdoc or [`rustc_middle`]. In particular, allowing new [`DefId`]s
136 /// to be registered after the AST is constructed would require storing the [`DefId`] mapping
137 /// in a [`RefCell`], decreasing the performance for normal compilation for very little gain.
139 /// Instead, we construct "fake" [`DefId`]s, which start immediately after the last `DefId`.
140 /// In the [`Debug`] impl for [`clean::Item`], we explicitly check for fake `DefId`s,
141 /// as we'll end up with a panic if we use the `DefId` `Debug` impl for fake `DefId`s.
143 /// [`RefCell`]: std::cell::RefCell
144 /// [`Debug`]: std::fmt::Debug
145 /// [`clean::Item`]: crate::clean::types::Item
146 crate fn next_def_id(&mut self, crate_num: CrateNum) -> DefId {
147 let def_index = match self.fake_def_ids.entry(crate_num) {
148 Entry::Vacant(e) => {
150 let num_def_idx = if crate_num == LOCAL_CRATE {
151 self.tcx.hir().definitions().def_path_table().num_def_ids()
153 self.resolver.borrow_mut().access(|r| r.cstore().num_def_ids(crate_num))
156 DefIndex::from_usize(num_def_idx)
159 MAX_DEF_IDX.with(|m| {
160 m.borrow_mut().insert(crate_num, num_def_idx);
162 e.insert(num_def_idx)
164 Entry::Occupied(e) => e.into_mut(),
166 *def_index = *def_index + 1;
168 DefId { krate: crate_num, index: *def_index }
171 /// Like `hir().local_def_id_to_hir_id()`, but skips calling it on fake DefIds.
172 /// (This avoids a slice-index-out-of-bounds panic.)
173 crate fn as_local_hir_id(tcx: TyCtxt<'_>, def_id: DefId) -> Option<HirId> {
174 if MAX_DEF_IDX.with(|m| {
175 m.borrow().get(&def_id.krate).map(|&idx| idx <= def_id.index).unwrap_or(false)
179 def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
184 /// Creates a new diagnostic `Handler` that can be used to emit warnings and errors.
186 /// If the given `error_format` is `ErrorOutputType::Json` and no `SourceMap` is given, a new one
187 /// will be created for the handler.
188 crate fn new_handler(
189 error_format: ErrorOutputType,
190 source_map: Option<Lrc<source_map::SourceMap>>,
191 debugging_opts: &DebuggingOptions,
192 ) -> rustc_errors::Handler {
193 let emitter: Box<dyn Emitter + sync::Send> = match error_format {
194 ErrorOutputType::HumanReadable(kind) => {
195 let (short, color_config) = kind.unzip();
197 EmitterWriter::stderr(
199 source_map.map(|sm| sm as _),
201 debugging_opts.teach,
202 debugging_opts.terminal_width,
205 .ui_testing(debugging_opts.ui_testing),
208 ErrorOutputType::Json { pretty, json_rendered } => {
209 let source_map = source_map.unwrap_or_else(|| {
210 Lrc::new(source_map::SourceMap::new(source_map::FilePathMapping::empty()))
218 debugging_opts.terminal_width,
221 .ui_testing(debugging_opts.ui_testing),
226 rustc_errors::Handler::with_emitter_and_flags(
228 debugging_opts.diagnostic_handler_flags(true),
232 /// Parse, resolve, and typecheck the given crate.
233 crate fn create_config(
253 ) -> rustc_interface::Config {
254 // Add the doc cfg into the doc build.
255 cfgs.push("doc".to_string());
257 let cpath = Some(input.clone());
258 let input = Input::File(input);
260 // By default, rustdoc ignores all lints.
261 // Specifically unblock lints relevant to documentation or the lint machinery itself.
262 let mut lints_to_show = vec![
263 // it's unclear whether this should be part of rustdoc directly (#77364)
264 rustc_lint::builtin::MISSING_DOCS.name.to_string(),
265 // these are definitely not part of rustdoc, but we want to warn on them anyway.
266 rustc_lint::builtin::RENAMED_AND_REMOVED_LINTS.name.to_string(),
267 rustc_lint::builtin::UNKNOWN_LINTS.name.to_string(),
269 lints_to_show.extend(crate::lint::RUSTDOC_LINTS.iter().map(|lint| lint.name.to_string()));
271 let (lint_opts, lint_caps) = crate::lint::init_lints(lints_to_show, lint_opts, |lint| {
272 // FIXME: why is this necessary?
273 if lint.name == crate::lint::BROKEN_INTRA_DOC_LINKS.name
274 || lint.name == crate::lint::INVALID_CODEBLOCK_ATTRIBUTES.name
278 Some((lint.name_lower(), lint::Allow))
283 if proc_macro_crate { vec![CrateType::ProcMacro] } else { vec![CrateType::Rlib] };
284 // plays with error output here!
285 let sessopts = config::Options {
289 lint_opts: if !display_warnings { lint_opts } else { vec![] },
293 target_triple: target,
294 unstable_features: UnstableFeatures::from_environment(crate_name.as_deref()),
295 actually_rustdoc: true,
306 crate_cfg: interface::parse_cfgspecs(cfgs),
312 diagnostic_output: DiagnosticOutput::Default,
315 parse_sess_created: None,
316 register_lints: Some(box crate::lint::register_lints),
317 override_queries: Some(|_sess, providers, _external_providers| {
318 // Most lints will require typechecking, so just don't run them.
319 providers.lint_mod = |_, _| {};
320 // Prevent `rustc_typeck::check_crate` from calling `typeck` on all bodies.
321 providers.typeck_item_bodies = |_, _| {};
322 // hack so that `used_trait_imports` won't try to call typeck
323 providers.used_trait_imports = |_, _| {
325 static ref EMPTY_SET: FxHashSet<LocalDefId> = FxHashSet::default();
329 // In case typeck does end up being called, don't ICE in case there were name resolution errors
330 providers.typeck = move |tcx, def_id| {
331 // Closures' tables come from their outermost function,
332 // as they are part of the same "inference environment".
333 // This avoids emitting errors for the parent twice (see similar code in `typeck_with_fallback`)
334 let outer_def_id = tcx.closure_base_def_id(def_id.to_def_id()).expect_local();
335 if outer_def_id != def_id {
336 return tcx.typeck(outer_def_id);
340 let body = hir.body(hir.body_owned_by(hir.local_def_id_to_hir_id(def_id)));
341 debug!("visiting body for {:?}", def_id);
342 EmitIgnoredResolutionErrors::new(tcx).visit_body(body);
343 (rustc_interface::DEFAULT_QUERY_PROVIDERS.typeck)(tcx, def_id)
346 make_codegen_backend: None,
347 registry: rustc_driver::diagnostics_registry(),
351 crate fn create_resolver<'a>(
352 queries: &Queries<'a>,
354 ) -> Rc<RefCell<interface::BoxedResolver>> {
355 let parts = abort_on_err(queries.expansion(), sess).peek();
356 let (krate, resolver, _) = &*parts;
357 let resolver = resolver.borrow().clone();
359 // Letting the resolver escape at the end of the function leads to inconsistencies between the
360 // crates the TyCtxt sees and the resolver sees (because the resolver could load more crates
361 // after escaping). Hopefully `IntraLinkCrateLoader` gets all the crates we need ...
362 struct IntraLinkCrateLoader {
364 resolver: Rc<RefCell<interface::BoxedResolver>>,
366 impl ast::visit::Visitor<'_> for IntraLinkCrateLoader {
367 fn visit_attribute(&mut self, attr: &ast::Attribute) {
368 use crate::html::markdown::{markdown_links, MarkdownLink};
369 use crate::passes::collect_intra_doc_links::Disambiguator;
371 if let Some(doc) = attr.doc_str() {
372 for MarkdownLink { link, .. } in markdown_links(&doc.as_str()) {
373 // FIXME: this misses a *lot* of the preprocessing done in collect_intra_doc_links
374 // I think most of it shouldn't be necessary since we only need the crate prefix?
375 let path_str = match Disambiguator::from_str(&link) {
376 Ok(x) => x.map_or(link.as_str(), |(_, p)| p),
379 self.resolver.borrow_mut().access(|resolver| {
380 let _ = resolver.resolve_str_path_error(
389 ast::visit::walk_attribute(self, attr);
392 fn visit_item(&mut self, item: &ast::Item) {
393 use rustc_ast_lowering::ResolverAstLowering;
395 if let ast::ItemKind::Mod(..) = item.kind {
397 self.resolver.borrow_mut().access(|resolver| resolver.local_def_id(item.id));
398 let old_mod = mem::replace(&mut self.current_mod, new_mod.to_def_id());
399 ast::visit::walk_item(self, item);
400 self.current_mod = old_mod;
402 ast::visit::walk_item(self, item);
406 let crate_id = LocalDefId { local_def_index: CRATE_DEF_INDEX }.to_def_id();
407 let mut loader = IntraLinkCrateLoader { current_mod: crate_id, resolver };
408 ast::visit::walk_crate(&mut loader, krate);
413 crate fn run_global_ctxt(
415 resolver: Rc<RefCell<interface::BoxedResolver>>,
416 mut default_passes: passes::DefaultPassOption,
417 manual_passes: Vec<String>,
418 render_options: RenderOptions,
419 output_format: OutputFormat,
420 ) -> (clean::Crate, RenderOptions, Cache) {
421 // Certain queries assume that some checks were run elsewhere
422 // (see https://github.com/rust-lang/rust/pull/73566#issuecomment-656954425),
423 // so type-check everything other than function bodies in this crate before running lints.
425 // NOTE: this does not call `tcx.analysis()` so that we won't
426 // typeck function bodies or run the default rustc lints.
427 // (see `override_queries` in the `config`)
429 // HACK(jynelson) this calls an _extremely_ limited subset of `typeck`
430 // and might break if queries change their assumptions in the future.
432 // NOTE: This is copy/pasted from typeck/lib.rs and should be kept in sync with those changes.
433 tcx.sess.time("item_types_checking", || {
434 for &module in tcx.hir().krate().modules.keys() {
435 tcx.ensure().check_mod_item_types(module);
438 tcx.sess.abort_if_errors();
439 tcx.sess.time("missing_docs", || {
440 rustc_lint::check_crate(tcx, rustc_lint::builtin::MissingDoc::new);
442 tcx.sess.time("check_mod_attrs", || {
443 for &module in tcx.hir().krate().modules.keys() {
444 tcx.ensure().check_mod_attrs(module);
447 rustc_passes::stability::check_unused_or_stable_features(tcx);
449 let access_levels = tcx.privacy_access_levels(LOCAL_CRATE);
450 // Convert from a HirId set to a DefId set since we don't always have easy access
451 // to the map from defid -> hirid
452 let access_levels = AccessLevels {
456 .map(|(&k, &v)| (tcx.hir().local_def_id(k).to_def_id(), v))
460 let mut ctxt = DocContext {
463 param_env: ParamEnv::empty(),
464 external_traits: Default::default(),
465 active_extern_traits: Default::default(),
466 ty_substs: Default::default(),
467 lt_substs: Default::default(),
468 ct_substs: Default::default(),
469 impl_trait_bounds: Default::default(),
470 fake_def_ids: Default::default(),
471 generated_synthetics: Default::default(),
473 .all_traits(LOCAL_CRATE)
476 .filter(|trait_def_id| tcx.trait_is_auto(*trait_def_id))
478 module_trait_cache: FxHashMap::default(),
479 cache: Cache::new(access_levels, render_options.document_private),
480 inlined: FxHashSet::default(),
485 // Small hack to force the Sized trait to be present.
487 // Note that in case of `#![no_core]`, the trait is not available.
488 if let Some(sized_trait_did) = ctxt.tcx.lang_items().sized_trait() {
489 let mut sized_trait = build_external_trait(&mut ctxt, sized_trait_did);
490 sized_trait.is_auto = true;
493 .insert(sized_trait_did, TraitWithExtraInfo { trait_: sized_trait, is_notable: false });
496 debug!("crate: {:?}", tcx.hir().krate());
498 let mut krate = tcx.sess.time("clean_crate", || clean::krate(&mut ctxt));
500 if krate.module.doc_value().map(|d| d.is_empty()).unwrap_or(true) {
501 let help = "The following guide may be of use:\n\
502 https://doc.rust-lang.org/nightly/rustdoc/how-to-write-documentation.html";
503 tcx.struct_lint_node(
504 crate::lint::MISSING_CRATE_LEVEL_DOCS,
505 DocContext::as_local_hir_id(tcx, krate.module.def_id).unwrap(),
508 lint.build("no documentation found for this crate's top-level module");
515 fn report_deprecated_attr(name: &str, diag: &rustc_errors::Handler, sp: Span) {
517 diag.struct_span_warn(sp, &format!("the `#![doc({})]` attribute is deprecated", name));
519 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
520 for more information",
523 if name == "no_default_passes" {
524 msg.help("you may want to use `#![doc(document_private_items)]`");
525 } else if name.starts_with("plugins") {
526 msg.warn("`#![doc(plugins = \"...\")]` no longer functions; see CVE-2018-1000622 <https://nvd.nist.gov/vuln/detail/CVE-2018-1000622>");
532 let parse_pass = |name: &str, sp: Option<Span>| {
533 if let Some(pass) = passes::find_pass(name) {
534 Some(ConditionalPass::always(pass))
536 let msg = &format!("ignoring unknown pass `{}`", name);
537 let mut warning = if let Some(sp) = sp {
538 tcx.sess.struct_span_warn(sp, msg)
540 tcx.sess.struct_warn(msg)
542 if name == "collapse-docs" {
543 warning.note("the `collapse-docs` pass was removed in #80261 <https://github.com/rust-lang/rust/pull/80261>");
550 let mut manual_passes: Vec<_> =
551 manual_passes.into_iter().flat_map(|name| parse_pass(&name, None)).collect();
553 // Process all of the crate attributes, extracting plugin metadata along
554 // with the passes which we are supposed to run.
555 for attr in krate.module.attrs.lists(sym::doc) {
556 let diag = ctxt.sess().diagnostic();
558 let name = attr.name_or_empty();
560 if name == sym::no_default_passes {
561 report_deprecated_attr("no_default_passes", diag, attr.span());
562 if default_passes == passes::DefaultPassOption::Default {
563 default_passes = passes::DefaultPassOption::None;
566 } else if let Some(value) = attr.value_str() {
569 report_deprecated_attr("passes = \"...\"", diag, attr.span());
572 report_deprecated_attr("plugins = \"...\"", diag, attr.span());
577 for name in value.as_str().split_whitespace() {
578 let span = attr.name_value_literal_span().unwrap_or(attr.span());
579 manual_passes.extend(parse_pass(name, Some(span)));
583 if attr.is_word() && name == sym::document_private_items {
584 ctxt.render_options.document_private = true;
588 let passes = passes::defaults(default_passes).iter().copied().chain(manual_passes);
589 info!("Executing passes");
592 let run = match p.condition {
594 WhenDocumentPrivate => ctxt.render_options.document_private,
595 WhenNotDocumentPrivate => !ctxt.render_options.document_private,
596 WhenNotDocumentHidden => !ctxt.render_options.document_hidden,
599 debug!("running pass {}", p.pass.name);
600 krate = ctxt.tcx.sess.time(p.pass.name, || (p.pass.run)(krate, &mut ctxt));
604 ctxt.sess().abort_if_errors();
606 let render_options = ctxt.render_options;
607 let mut cache = ctxt.cache;
608 krate = tcx.sess.time("create_format_cache", || {
609 cache.populate(krate, tcx, &render_options.extern_html_root_urls, &render_options.output)
612 // The main crate doc comments are always collapsed.
613 krate.collapsed = true;
615 (krate, render_options, cache)
618 /// Due to <https://github.com/rust-lang/rust/pull/73566>,
619 /// the name resolution pass may find errors that are never emitted.
620 /// If typeck is called after this happens, then we'll get an ICE:
621 /// 'Res::Error found but not reported'. To avoid this, emit the errors now.
622 struct EmitIgnoredResolutionErrors<'tcx> {
626 impl<'tcx> EmitIgnoredResolutionErrors<'tcx> {
627 fn new(tcx: TyCtxt<'tcx>) -> Self {
632 impl<'tcx> Visitor<'tcx> for EmitIgnoredResolutionErrors<'tcx> {
633 type Map = Map<'tcx>;
635 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
636 // We need to recurse into nested closures,
637 // since those will fallback to the parent for type checking.
638 NestedVisitorMap::OnlyBodies(self.tcx.hir())
641 fn visit_path(&mut self, path: &'tcx Path<'_>, _id: HirId) {
642 debug!("visiting path {:?}", path);
643 if path.res == Res::Err {
644 // We have less context here than in rustc_resolve,
645 // so we can only emit the name and span.
646 // However we can give a hint that rustc_resolve will have more info.
648 "could not resolve path `{}`",
651 .map(|segment| segment.ident.as_str().to_string())
655 let mut err = rustc_errors::struct_span_err!(
659 "failed to resolve: {}",
662 err.span_label(path.span, label);
663 err.note("this error was originally ignored because you are running `rustdoc`");
664 err.note("try running again with `rustc` or `cargo check` and you may get a more detailed error");
667 // We could have an outer resolution that succeeded,
668 // but with generic parameters that failed.
669 // Recurse into the segments so we catch those too.
670 intravisit::walk_path(self, path);
674 /// `DefId` or parameter index (`ty::ParamTy.index`) of a synthetic type parameter
675 /// for `impl Trait` in argument position.
676 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
677 crate enum ImplTraitParam {
682 impl From<DefId> for ImplTraitParam {
683 fn from(did: DefId) -> Self {
684 ImplTraitParam::DefId(did)
688 impl From<u32> for ImplTraitParam {
689 fn from(idx: u32) -> Self {
690 ImplTraitParam::ParamIndex(idx)