1 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
2 use rustc_data_structures::sync::{self, Lrc};
3 use rustc_driver::abort_on_err;
4 use rustc_errors::emitter::{Emitter, EmitterWriter};
5 use rustc_errors::json::JsonEmitter;
6 use rustc_feature::UnstableFeatures;
7 use rustc_hir::def::Res;
8 use rustc_hir::def_id::{DefId, LocalDefId};
11 intravisit::{self, NestedVisitorMap, Visitor},
14 use rustc_interface::{interface, Queries};
15 use rustc_middle::hir::map::Map;
16 use rustc_middle::middle::privacy::AccessLevels;
17 use rustc_middle::ty::{ParamEnv, Ty, TyCtxt};
18 use rustc_resolve as resolve;
19 use rustc_resolve::Namespace::TypeNS;
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::def_id::CRATE_DEF_INDEX;
25 use rustc_span::source_map;
26 use rustc_span::symbol::sym;
27 use rustc_span::{Span, DUMMY_SP};
29 use std::cell::RefCell;
30 use std::lazy::SyncLazy;
34 use crate::clean::inline::build_external_trait;
35 use crate::clean::{self, ItemId, TraitWithExtraInfo};
36 use crate::config::{Options as RustdocOptions, OutputFormat, RenderOptions};
37 use crate::formats::cache::Cache;
38 use crate::passes::{self, Condition::*};
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 parameter substitutions,
60 // for expanding type aliases at the HIR level:
61 /// Table `DefId` of type, lifetime, or const parameter -> substituted type, lifetime, or const
62 crate substs: FxHashMap<DefId, clean::SubstParam>,
63 /// Table synthetic type parameter for `impl Trait` in argument position -> bounds
64 crate impl_trait_bounds: FxHashMap<ImplTraitParam, Vec<clean::GenericBound>>,
65 /// Auto-trait or blanket impls processed so far, as `(self_ty, trait_def_id)`.
66 // FIXME(eddyb) make this a `ty::TraitRef<'tcx>` set.
67 crate generated_synthetics: FxHashSet<(Ty<'tcx>, DefId)>,
68 crate auto_traits: Vec<DefId>,
69 /// The options given to rustdoc that could be relevant to a pass.
70 crate render_options: RenderOptions,
71 /// The traits in scope for a given module.
73 /// See `collect_intra_doc_links::traits_implemented_by` for more details.
74 /// `map<module, set<trait>>`
75 crate module_trait_cache: FxHashMap<DefId, FxHashSet<DefId>>,
76 /// This same cache is used throughout rustdoc, including in [`crate::html::render`].
78 /// Used by [`clean::inline`] to tell if an item has already been inlined.
79 crate inlined: FxHashSet<ItemId>,
80 /// Used by `calculate_doc_coverage`.
81 crate output_format: OutputFormat,
84 impl<'tcx> DocContext<'tcx> {
85 crate fn sess(&self) -> &'tcx Session {
89 crate fn with_param_env<T, F: FnOnce(&mut Self) -> T>(&mut self, def_id: DefId, f: F) -> T {
90 let old_param_env = mem::replace(&mut self.param_env, self.tcx.param_env(def_id));
92 self.param_env = old_param_env;
96 crate fn enter_resolver<F, R>(&self, f: F) -> R
98 F: FnOnce(&mut resolve::Resolver<'_>) -> R,
100 self.resolver.borrow_mut().access(f)
103 /// Call the closure with the given parameters set as
104 /// the substitutions for a type alias' RHS.
105 crate fn enter_alias<F, R>(&mut self, substs: FxHashMap<DefId, clean::SubstParam>, f: F) -> R
107 F: FnOnce(&mut Self) -> R,
109 let old_substs = mem::replace(&mut self.substs, substs);
111 self.substs = old_substs;
115 /// Like `hir().local_def_id_to_hir_id()`, but skips calling it on fake DefIds.
116 /// (This avoids a slice-index-out-of-bounds panic.)
117 crate fn as_local_hir_id(tcx: TyCtxt<'_>, def_id: ItemId) -> Option<HirId> {
119 ItemId::DefId(real_id) => {
120 real_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
122 // FIXME: Can this be `Some` for `Auto` or `Blanket`?
128 /// Creates a new diagnostic `Handler` that can be used to emit warnings and errors.
130 /// If the given `error_format` is `ErrorOutputType::Json` and no `SourceMap` is given, a new one
131 /// will be created for the handler.
132 crate fn new_handler(
133 error_format: ErrorOutputType,
134 source_map: Option<Lrc<source_map::SourceMap>>,
135 debugging_opts: &DebuggingOptions,
136 ) -> rustc_errors::Handler {
137 let emitter: Box<dyn Emitter + sync::Send> = match error_format {
138 ErrorOutputType::HumanReadable(kind) => {
139 let (short, color_config) = kind.unzip();
141 EmitterWriter::stderr(
143 source_map.map(|sm| sm as _),
145 debugging_opts.teach,
146 debugging_opts.terminal_width,
149 .ui_testing(debugging_opts.ui_testing),
152 ErrorOutputType::Json { pretty, json_rendered } => {
153 let source_map = source_map.unwrap_or_else(|| {
154 Lrc::new(source_map::SourceMap::new(source_map::FilePathMapping::empty()))
162 debugging_opts.terminal_width,
165 .ui_testing(debugging_opts.ui_testing),
170 rustc_errors::Handler::with_emitter_and_flags(
172 debugging_opts.diagnostic_handler_flags(true),
176 /// Parse, resolve, and typecheck the given crate.
177 crate fn create_config(
196 ) -> rustc_interface::Config {
197 // Add the doc cfg into the doc build.
198 cfgs.push("doc".to_string());
200 let cpath = Some(input.clone());
201 let input = Input::File(input);
203 // By default, rustdoc ignores all lints.
204 // Specifically unblock lints relevant to documentation or the lint machinery itself.
205 let mut lints_to_show = vec![
206 // it's unclear whether these should be part of rustdoc directly (#77364)
207 rustc_lint::builtin::MISSING_DOCS.name.to_string(),
208 rustc_lint::builtin::INVALID_DOC_ATTRIBUTES.name.to_string(),
209 // these are definitely not part of rustdoc, but we want to warn on them anyway.
210 rustc_lint::builtin::RENAMED_AND_REMOVED_LINTS.name.to_string(),
211 rustc_lint::builtin::UNKNOWN_LINTS.name.to_string(),
213 lints_to_show.extend(crate::lint::RUSTDOC_LINTS.iter().map(|lint| lint.name.to_string()));
215 let (lint_opts, lint_caps) = crate::lint::init_lints(lints_to_show, lint_opts, |lint| {
216 Some((lint.name_lower(), lint::Allow))
220 if proc_macro_crate { vec![CrateType::ProcMacro] } else { vec![CrateType::Rlib] };
221 // plays with error output here!
222 let sessopts = config::Options {
230 target_triple: target,
231 unstable_features: UnstableFeatures::from_environment(crate_name.as_deref()),
232 actually_rustdoc: true,
243 crate_cfg: interface::parse_cfgspecs(cfgs),
249 diagnostic_output: DiagnosticOutput::Default,
252 parse_sess_created: None,
253 register_lints: Some(box crate::lint::register_lints),
254 override_queries: Some(|_sess, providers, _external_providers| {
255 // Most lints will require typechecking, so just don't run them.
256 providers.lint_mod = |_, _| {};
257 // Prevent `rustc_typeck::check_crate` from calling `typeck` on all bodies.
258 providers.typeck_item_bodies = |_, _| {};
259 // hack so that `used_trait_imports` won't try to call typeck
260 providers.used_trait_imports = |_, _| {
261 static EMPTY_SET: SyncLazy<FxHashSet<LocalDefId>> =
262 SyncLazy::new(FxHashSet::default);
265 // In case typeck does end up being called, don't ICE in case there were name resolution errors
266 providers.typeck = move |tcx, def_id| {
267 // Closures' tables come from their outermost function,
268 // as they are part of the same "inference environment".
269 // This avoids emitting errors for the parent twice (see similar code in `typeck_with_fallback`)
270 let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id()).expect_local();
271 if typeck_root_def_id != def_id {
272 return tcx.typeck(typeck_root_def_id);
276 let body = hir.body(hir.body_owned_by(hir.local_def_id_to_hir_id(def_id)));
277 debug!("visiting body for {:?}", def_id);
278 EmitIgnoredResolutionErrors::new(tcx).visit_body(body);
279 (rustc_interface::DEFAULT_QUERY_PROVIDERS.typeck)(tcx, def_id)
282 make_codegen_backend: None,
283 registry: rustc_driver::diagnostics_registry(),
287 crate fn create_resolver<'a>(
288 externs: config::Externs,
289 queries: &Queries<'a>,
291 ) -> Rc<RefCell<interface::BoxedResolver>> {
292 let (krate, resolver, _) = &*abort_on_err(queries.expansion(), sess).peek();
293 let resolver = resolver.clone();
295 let resolver = crate::passes::collect_intra_doc_links::load_intra_link_crates(resolver, krate);
297 // FIXME: somehow rustdoc is still missing crates even though we loaded all
298 // the known necessary crates. Load them all unconditionally until we find a way to fix this.
299 // DO NOT REMOVE THIS without first testing on the reproducer in
300 // https://github.com/jyn514/objr/commit/edcee7b8124abf0e4c63873e8422ff81beb11ebb
301 let extern_names: Vec<String> = externs
303 .filter(|(_, entry)| entry.add_prelude)
304 .map(|(name, _)| name)
307 resolver.borrow_mut().access(|resolver| {
308 sess.time("load_extern_crates", || {
309 for extern_name in &extern_names {
310 debug!("loading extern crate {}", extern_name);
311 if let Err(()) = resolver
312 .resolve_str_path_error(
316 LocalDefId { local_def_index: CRATE_DEF_INDEX }.to_def_id(),
318 warn!("unable to resolve external crate {} (do you have an unused `--extern` crate?)", extern_name)
327 crate fn run_global_ctxt(
329 resolver: Rc<RefCell<interface::BoxedResolver>>,
331 render_options: RenderOptions,
332 output_format: OutputFormat,
333 ) -> (clean::Crate, RenderOptions, Cache) {
334 // Certain queries assume that some checks were run elsewhere
335 // (see https://github.com/rust-lang/rust/pull/73566#issuecomment-656954425),
336 // so type-check everything other than function bodies in this crate before running lints.
338 // NOTE: this does not call `tcx.analysis()` so that we won't
339 // typeck function bodies or run the default rustc lints.
340 // (see `override_queries` in the `config`)
342 // HACK(jynelson) this calls an _extremely_ limited subset of `typeck`
343 // and might break if queries change their assumptions in the future.
345 // NOTE: This is copy/pasted from typeck/lib.rs and should be kept in sync with those changes.
346 tcx.sess.time("item_types_checking", || {
347 tcx.hir().for_each_module(|module| tcx.ensure().check_mod_item_types(module))
349 tcx.sess.abort_if_errors();
350 tcx.sess.time("missing_docs", || {
351 rustc_lint::check_crate(tcx, rustc_lint::builtin::MissingDoc::new);
353 tcx.sess.time("check_mod_attrs", || {
354 tcx.hir().for_each_module(|module| tcx.ensure().check_mod_attrs(module))
356 rustc_passes::stability::check_unused_or_stable_features(tcx);
358 let access_levels = AccessLevels {
359 map: tcx.privacy_access_levels(()).map.iter().map(|(k, v)| (k.to_def_id(), *v)).collect(),
362 let mut ctxt = DocContext {
365 param_env: ParamEnv::empty(),
366 external_traits: Default::default(),
367 active_extern_traits: Default::default(),
368 substs: Default::default(),
369 impl_trait_bounds: Default::default(),
370 generated_synthetics: Default::default(),
375 .filter(|trait_def_id| tcx.trait_is_auto(*trait_def_id))
377 module_trait_cache: FxHashMap::default(),
378 cache: Cache::new(access_levels, render_options.document_private),
379 inlined: FxHashSet::default(),
384 // Small hack to force the Sized trait to be present.
386 // Note that in case of `#![no_core]`, the trait is not available.
387 if let Some(sized_trait_did) = ctxt.tcx.lang_items().sized_trait() {
388 let mut sized_trait = build_external_trait(&mut ctxt, sized_trait_did);
389 sized_trait.is_auto = true;
392 .insert(sized_trait_did, TraitWithExtraInfo { trait_: sized_trait, is_notable: false });
395 debug!("crate: {:?}", tcx.hir().krate());
397 let mut krate = tcx.sess.time("clean_crate", || clean::krate(&mut ctxt));
399 if krate.module.doc_value().map(|d| d.is_empty()).unwrap_or(true) {
401 "The following guide may be of use:\n\
402 {}/rustdoc/how-to-write-documentation.html",
403 crate::DOC_RUST_LANG_ORG_CHANNEL
405 tcx.struct_lint_node(
406 crate::lint::MISSING_CRATE_LEVEL_DOCS,
407 DocContext::as_local_hir_id(tcx, krate.module.def_id).unwrap(),
410 lint.build("no documentation found for this crate's top-level module");
417 fn report_deprecated_attr(name: &str, diag: &rustc_errors::Handler, sp: Span) {
419 diag.struct_span_warn(sp, &format!("the `#![doc({})]` attribute is deprecated", name));
421 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
422 for more information",
425 if name == "no_default_passes" {
426 msg.help("`#![doc(no_default_passes)]` no longer functions; you may want to use `#![doc(document_private_items)]`");
427 } else if name.starts_with("passes") {
428 msg.help("`#![doc(passes = \"...\")]` no longer functions; you may want to use `#![doc(document_private_items)]`");
429 } else if name.starts_with("plugins") {
430 msg.warn("`#![doc(plugins = \"...\")]` no longer functions; see CVE-2018-1000622 <https://nvd.nist.gov/vuln/detail/CVE-2018-1000622>");
436 // Process all of the crate attributes, extracting plugin metadata along
437 // with the passes which we are supposed to run.
438 for attr in krate.module.attrs.lists(sym::doc) {
439 let diag = ctxt.sess().diagnostic();
441 let name = attr.name_or_empty();
442 // `plugins = "..."`, `no_default_passes`, and `passes = "..."` have no effect
443 if attr.is_word() && name == sym::no_default_passes {
444 report_deprecated_attr("no_default_passes", diag, attr.span());
445 } else if attr.value_str().is_some() {
448 report_deprecated_attr("passes = \"...\"", diag, attr.span());
451 report_deprecated_attr("plugins = \"...\"", diag, attr.span());
457 if attr.is_word() && name == sym::document_private_items {
458 ctxt.render_options.document_private = true;
462 info!("Executing passes");
464 for p in passes::defaults(show_coverage) {
465 let run = match p.condition {
467 WhenDocumentPrivate => ctxt.render_options.document_private,
468 WhenNotDocumentPrivate => !ctxt.render_options.document_private,
469 WhenNotDocumentHidden => !ctxt.render_options.document_hidden,
472 debug!("running pass {}", p.pass.name);
473 krate = tcx.sess.time(p.pass.name, || (p.pass.run)(krate, &mut ctxt));
477 if tcx.sess.diagnostic().has_errors_or_lint_errors() {
478 rustc_errors::FatalError.raise();
481 krate = tcx.sess.time("create_format_cache", || Cache::populate(&mut ctxt, krate));
483 (krate, ctxt.render_options, ctxt.cache)
486 /// Due to <https://github.com/rust-lang/rust/pull/73566>,
487 /// the name resolution pass may find errors that are never emitted.
488 /// If typeck is called after this happens, then we'll get an ICE:
489 /// 'Res::Error found but not reported'. To avoid this, emit the errors now.
490 struct EmitIgnoredResolutionErrors<'tcx> {
494 impl<'tcx> EmitIgnoredResolutionErrors<'tcx> {
495 fn new(tcx: TyCtxt<'tcx>) -> Self {
500 impl<'tcx> Visitor<'tcx> for EmitIgnoredResolutionErrors<'tcx> {
501 type Map = Map<'tcx>;
503 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
504 // We need to recurse into nested closures,
505 // since those will fallback to the parent for type checking.
506 NestedVisitorMap::OnlyBodies(self.tcx.hir())
509 fn visit_path(&mut self, path: &'tcx Path<'_>, _id: HirId) {
510 debug!("visiting path {:?}", path);
511 if path.res == Res::Err {
512 // We have less context here than in rustc_resolve,
513 // so we can only emit the name and span.
514 // However we can give a hint that rustc_resolve will have more info.
516 "could not resolve path `{}`",
519 .map(|segment| segment.ident.as_str().to_string())
523 let mut err = rustc_errors::struct_span_err!(
527 "failed to resolve: {}",
530 err.span_label(path.span, label);
531 err.note("this error was originally ignored because you are running `rustdoc`");
532 err.note("try running again with `rustc` or `cargo check` and you may get a more detailed error");
535 // We could have an outer resolution that succeeded,
536 // but with generic parameters that failed.
537 // Recurse into the segments so we catch those too.
538 intravisit::walk_path(self, path);
542 /// `DefId` or parameter index (`ty::ParamTy.index`) of a synthetic type parameter
543 /// for `impl Trait` in argument position.
544 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
545 crate enum ImplTraitParam {
550 impl From<DefId> for ImplTraitParam {
551 fn from(did: DefId) -> Self {
552 ImplTraitParam::DefId(did)
556 impl From<u32> for ImplTraitParam {
557 fn from(idx: u32) -> Self {
558 ImplTraitParam::ParamIndex(idx)