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::Res;
9 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, 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::{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 let mut loader = crate::passes::collect_intra_doc_links::IntraLinkCrateLoader::new(resolver);
360 ast::visit::walk_crate(&mut loader, krate);
365 crate fn run_global_ctxt(
367 resolver: Rc<RefCell<interface::BoxedResolver>>,
368 mut default_passes: passes::DefaultPassOption,
369 manual_passes: Vec<String>,
370 render_options: RenderOptions,
371 output_format: OutputFormat,
372 ) -> (clean::Crate, RenderOptions, Cache) {
373 // Certain queries assume that some checks were run elsewhere
374 // (see https://github.com/rust-lang/rust/pull/73566#issuecomment-656954425),
375 // so type-check everything other than function bodies in this crate before running lints.
377 // NOTE: this does not call `tcx.analysis()` so that we won't
378 // typeck function bodies or run the default rustc lints.
379 // (see `override_queries` in the `config`)
381 // HACK(jynelson) this calls an _extremely_ limited subset of `typeck`
382 // and might break if queries change their assumptions in the future.
384 // NOTE: This is copy/pasted from typeck/lib.rs and should be kept in sync with those changes.
385 tcx.sess.time("item_types_checking", || {
386 for &module in tcx.hir().krate().modules.keys() {
387 tcx.ensure().check_mod_item_types(module);
390 tcx.sess.abort_if_errors();
391 tcx.sess.time("missing_docs", || {
392 rustc_lint::check_crate(tcx, rustc_lint::builtin::MissingDoc::new);
394 tcx.sess.time("check_mod_attrs", || {
395 for &module in tcx.hir().krate().modules.keys() {
396 tcx.ensure().check_mod_attrs(module);
399 rustc_passes::stability::check_unused_or_stable_features(tcx);
401 let access_levels = tcx.privacy_access_levels(LOCAL_CRATE);
402 // Convert from a HirId set to a DefId set since we don't always have easy access
403 // to the map from defid -> hirid
404 let access_levels = AccessLevels {
408 .map(|(&k, &v)| (tcx.hir().local_def_id(k).to_def_id(), v))
412 let mut ctxt = DocContext {
415 param_env: ParamEnv::empty(),
416 external_traits: Default::default(),
417 active_extern_traits: Default::default(),
418 ty_substs: Default::default(),
419 lt_substs: Default::default(),
420 ct_substs: Default::default(),
421 impl_trait_bounds: Default::default(),
422 fake_def_ids: Default::default(),
423 generated_synthetics: Default::default(),
425 .all_traits(LOCAL_CRATE)
428 .filter(|trait_def_id| tcx.trait_is_auto(*trait_def_id))
430 module_trait_cache: FxHashMap::default(),
431 cache: Cache::new(access_levels, render_options.document_private),
432 inlined: FxHashSet::default(),
437 // Small hack to force the Sized trait to be present.
439 // Note that in case of `#![no_core]`, the trait is not available.
440 if let Some(sized_trait_did) = ctxt.tcx.lang_items().sized_trait() {
441 let mut sized_trait = build_external_trait(&mut ctxt, sized_trait_did);
442 sized_trait.is_auto = true;
445 .insert(sized_trait_did, TraitWithExtraInfo { trait_: sized_trait, is_notable: false });
448 debug!("crate: {:?}", tcx.hir().krate());
450 let mut krate = tcx.sess.time("clean_crate", || clean::krate(&mut ctxt));
452 if krate.module.doc_value().map(|d| d.is_empty()).unwrap_or(true) {
454 "The following guide may be of use:\n\
455 https://doc.rust-lang.org/{}/rustdoc/how-to-write-documentation.html",
456 crate::doc_rust_lang_org_channel(),
458 tcx.struct_lint_node(
459 crate::lint::MISSING_CRATE_LEVEL_DOCS,
460 DocContext::as_local_hir_id(tcx, krate.module.def_id).unwrap(),
463 lint.build("no documentation found for this crate's top-level module");
470 fn report_deprecated_attr(name: &str, diag: &rustc_errors::Handler, sp: Span) {
472 diag.struct_span_warn(sp, &format!("the `#![doc({})]` attribute is deprecated", name));
474 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
475 for more information",
478 if name == "no_default_passes" {
479 msg.help("you may want to use `#![doc(document_private_items)]`");
480 } else if name.starts_with("plugins") {
481 msg.warn("`#![doc(plugins = \"...\")]` no longer functions; see CVE-2018-1000622 <https://nvd.nist.gov/vuln/detail/CVE-2018-1000622>");
487 let parse_pass = |name: &str, sp: Option<Span>| {
488 if let Some(pass) = passes::find_pass(name) {
489 Some(ConditionalPass::always(pass))
491 let msg = &format!("ignoring unknown pass `{}`", name);
492 let mut warning = if let Some(sp) = sp {
493 tcx.sess.struct_span_warn(sp, msg)
495 tcx.sess.struct_warn(msg)
497 if name == "collapse-docs" {
498 warning.note("the `collapse-docs` pass was removed in #80261 <https://github.com/rust-lang/rust/pull/80261>");
505 let mut manual_passes: Vec<_> =
506 manual_passes.into_iter().flat_map(|name| parse_pass(&name, None)).collect();
508 // Process all of the crate attributes, extracting plugin metadata along
509 // with the passes which we are supposed to run.
510 for attr in krate.module.attrs.lists(sym::doc) {
511 let diag = ctxt.sess().diagnostic();
513 let name = attr.name_or_empty();
515 if name == sym::no_default_passes {
516 report_deprecated_attr("no_default_passes", diag, attr.span());
517 if default_passes == passes::DefaultPassOption::Default {
518 default_passes = passes::DefaultPassOption::None;
521 } else if let Some(value) = attr.value_str() {
524 report_deprecated_attr("passes = \"...\"", diag, attr.span());
527 report_deprecated_attr("plugins = \"...\"", diag, attr.span());
532 for name in value.as_str().split_whitespace() {
533 let span = attr.name_value_literal_span().unwrap_or(attr.span());
534 manual_passes.extend(parse_pass(name, Some(span)));
538 if attr.is_word() && name == sym::document_private_items {
539 ctxt.render_options.document_private = true;
543 let passes = passes::defaults(default_passes).iter().copied().chain(manual_passes);
544 info!("Executing passes");
547 let run = match p.condition {
549 WhenDocumentPrivate => ctxt.render_options.document_private,
550 WhenNotDocumentPrivate => !ctxt.render_options.document_private,
551 WhenNotDocumentHidden => !ctxt.render_options.document_hidden,
554 debug!("running pass {}", p.pass.name);
555 krate = ctxt.tcx.sess.time(p.pass.name, || (p.pass.run)(krate, &mut ctxt));
559 ctxt.sess().abort_if_errors();
561 let render_options = ctxt.render_options;
562 let mut cache = ctxt.cache;
563 krate = tcx.sess.time("create_format_cache", || {
564 cache.populate(krate, tcx, &render_options.extern_html_root_urls, &render_options.output)
567 // The main crate doc comments are always collapsed.
568 krate.collapsed = true;
570 (krate, render_options, cache)
573 /// Due to <https://github.com/rust-lang/rust/pull/73566>,
574 /// the name resolution pass may find errors that are never emitted.
575 /// If typeck is called after this happens, then we'll get an ICE:
576 /// 'Res::Error found but not reported'. To avoid this, emit the errors now.
577 struct EmitIgnoredResolutionErrors<'tcx> {
581 impl<'tcx> EmitIgnoredResolutionErrors<'tcx> {
582 fn new(tcx: TyCtxt<'tcx>) -> Self {
587 impl<'tcx> Visitor<'tcx> for EmitIgnoredResolutionErrors<'tcx> {
588 type Map = Map<'tcx>;
590 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
591 // We need to recurse into nested closures,
592 // since those will fallback to the parent for type checking.
593 NestedVisitorMap::OnlyBodies(self.tcx.hir())
596 fn visit_path(&mut self, path: &'tcx Path<'_>, _id: HirId) {
597 debug!("visiting path {:?}", path);
598 if path.res == Res::Err {
599 // We have less context here than in rustc_resolve,
600 // so we can only emit the name and span.
601 // However we can give a hint that rustc_resolve will have more info.
603 "could not resolve path `{}`",
606 .map(|segment| segment.ident.as_str().to_string())
610 let mut err = rustc_errors::struct_span_err!(
614 "failed to resolve: {}",
617 err.span_label(path.span, label);
618 err.note("this error was originally ignored because you are running `rustdoc`");
619 err.note("try running again with `rustc` or `cargo check` and you may get a more detailed error");
622 // We could have an outer resolution that succeeded,
623 // but with generic parameters that failed.
624 // Recurse into the segments so we catch those too.
625 intravisit::walk_path(self, path);
629 /// `DefId` or parameter index (`ty::ParamTy.index`) of a synthetic type parameter
630 /// for `impl Trait` in argument position.
631 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
632 crate enum ImplTraitParam {
637 impl From<DefId> for ImplTraitParam {
638 fn from(did: DefId) -> Self {
639 ImplTraitParam::DefId(did)
643 impl From<u32> for ImplTraitParam {
644 fn from(idx: u32) -> Self {
645 ImplTraitParam::ParamIndex(idx)