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::{Namespace::TypeNS, Res};
8 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
11 intravisit::{self, NestedVisitorMap, Visitor},
14 use rustc_interface::interface;
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_session::config::{self, CrateType, ErrorOutputType};
20 use rustc_session::lint;
21 use rustc_session::DiagnosticOutput;
22 use rustc_session::Session;
23 use rustc_span::source_map;
24 use rustc_span::symbol::sym;
25 use rustc_span::DUMMY_SP;
27 use std::cell::{Cell, RefCell};
32 use crate::clean::{AttributesExt, MAX_DEF_ID};
33 use crate::config::{Options as RustdocOptions, RenderOptions};
34 use crate::config::{OutputFormat, RenderInfo};
35 use crate::passes::{self, Condition::*, ConditionalPass};
37 crate use rustc_session::config::{DebuggingOptions, Input, Options};
39 crate type ExternalPaths = FxHashMap<DefId, (Vec<String>, clean::TypeKind)>;
41 crate struct DocContext<'tcx> {
42 crate tcx: TyCtxt<'tcx>,
43 crate resolver: Rc<RefCell<interface::BoxedResolver>>,
44 /// Used for normalization.
46 /// Most of this logic is copied from rustc_lint::late.
47 crate param_env: Cell<ParamEnv<'tcx>>,
48 /// Later on moved into `CACHE_KEY`
49 crate renderinfo: RefCell<RenderInfo>,
50 /// Later on moved through `clean::Crate` into `CACHE_KEY`
51 crate external_traits: Rc<RefCell<FxHashMap<DefId, clean::Trait>>>,
52 /// Used while populating `external_traits` to ensure we don't process the same trait twice at
54 crate active_extern_traits: RefCell<FxHashSet<DefId>>,
55 // The current set of type and lifetime substitutions,
56 // for expanding type aliases at the HIR level:
57 /// Table `DefId` of type parameter -> substituted type
58 crate ty_substs: RefCell<FxHashMap<DefId, clean::Type>>,
59 /// Table `DefId` of lifetime parameter -> substituted lifetime
60 crate lt_substs: RefCell<FxHashMap<DefId, clean::Lifetime>>,
61 /// Table `DefId` of const parameter -> substituted const
62 crate ct_substs: RefCell<FxHashMap<DefId, clean::Constant>>,
63 /// Table synthetic type parameter for `impl Trait` in argument position -> bounds
64 crate impl_trait_bounds: RefCell<FxHashMap<ImplTraitParam, Vec<clean::GenericBound>>>,
65 crate fake_def_ids: RefCell<FxHashMap<CrateNum, DefId>>,
66 crate all_fake_def_ids: RefCell<FxHashSet<DefId>>,
67 /// Auto-trait or blanket impls processed so far, as `(self_ty, trait_def_id)`.
68 // FIXME(eddyb) make this a `ty::TraitRef<'tcx>` set.
69 crate generated_synthetics: RefCell<FxHashSet<(Ty<'tcx>, DefId)>>,
70 crate auto_traits: Vec<DefId>,
71 /// The options given to rustdoc that could be relevant to a pass.
72 crate render_options: RenderOptions,
73 /// The traits in scope for a given module.
75 /// See `collect_intra_doc_links::traits_implemented_by` for more details.
76 /// `map<module, set<trait>>`
77 crate module_trait_cache: RefCell<FxHashMap<DefId, FxHashSet<DefId>>>,
80 impl<'tcx> DocContext<'tcx> {
81 crate fn sess(&self) -> &Session {
85 crate fn with_param_env<T, F: FnOnce() -> T>(&self, def_id: DefId, f: F) -> T {
86 let old_param_env = self.param_env.replace(self.tcx.param_env(def_id));
88 self.param_env.set(old_param_env);
92 crate fn enter_resolver<F, R>(&self, f: F) -> R
94 F: FnOnce(&mut resolve::Resolver<'_>) -> R,
96 self.resolver.borrow_mut().access(f)
99 /// Call the closure with the given parameters set as
100 /// the substitutions for a type alias' RHS.
101 crate fn enter_alias<F, R>(
103 ty_substs: FxHashMap<DefId, clean::Type>,
104 lt_substs: FxHashMap<DefId, clean::Lifetime>,
105 ct_substs: FxHashMap<DefId, clean::Constant>,
111 let (old_tys, old_lts, old_cts) = (
112 mem::replace(&mut *self.ty_substs.borrow_mut(), ty_substs),
113 mem::replace(&mut *self.lt_substs.borrow_mut(), lt_substs),
114 mem::replace(&mut *self.ct_substs.borrow_mut(), ct_substs),
117 *self.ty_substs.borrow_mut() = old_tys;
118 *self.lt_substs.borrow_mut() = old_lts;
119 *self.ct_substs.borrow_mut() = old_cts;
123 // This is an ugly hack, but it's the simplest way to handle synthetic impls without greatly
124 // refactoring either librustdoc or librustc_middle. In particular, allowing new DefIds to be
125 // registered after the AST is constructed would require storing the defid mapping in a
126 // RefCell, decreasing the performance for normal compilation for very little gain.
128 // Instead, we construct 'fake' def ids, which start immediately after the last DefId.
129 // In the Debug impl for clean::Item, we explicitly check for fake
130 // def ids, as we'll end up with a panic if we use the DefId Debug impl for fake DefIds
131 crate fn next_def_id(&self, crate_num: CrateNum) -> DefId {
133 let num_def_ids = if crate_num == LOCAL_CRATE {
134 self.tcx.hir().definitions().def_path_table().num_def_ids()
136 self.enter_resolver(|r| r.cstore().num_def_ids(crate_num))
139 DefId { krate: crate_num, index: DefIndex::from_usize(num_def_ids) }
142 let mut fake_ids = self.fake_def_ids.borrow_mut();
144 let def_id = *fake_ids.entry(crate_num).or_insert(start_def_id);
147 DefId { krate: crate_num, index: DefIndex::from(def_id.index.index() + 1) },
150 MAX_DEF_ID.with(|m| {
151 m.borrow_mut().entry(def_id.krate).or_insert(start_def_id);
154 self.all_fake_def_ids.borrow_mut().insert(def_id);
159 /// Like `hir().local_def_id_to_hir_id()`, but skips calling it on fake DefIds.
160 /// (This avoids a slice-index-out-of-bounds panic.)
161 crate fn as_local_hir_id(&self, def_id: DefId) -> Option<HirId> {
162 if self.all_fake_def_ids.borrow().contains(&def_id) {
165 def_id.as_local().map(|def_id| self.tcx.hir().local_def_id_to_hir_id(def_id))
170 /// Creates a new diagnostic `Handler` that can be used to emit warnings and errors.
172 /// If the given `error_format` is `ErrorOutputType::Json` and no `SourceMap` is given, a new one
173 /// will be created for the handler.
174 crate fn new_handler(
175 error_format: ErrorOutputType,
176 source_map: Option<Lrc<source_map::SourceMap>>,
177 debugging_opts: &DebuggingOptions,
178 ) -> rustc_errors::Handler {
179 let emitter: Box<dyn Emitter + sync::Send> = match error_format {
180 ErrorOutputType::HumanReadable(kind) => {
181 let (short, color_config) = kind.unzip();
183 EmitterWriter::stderr(
185 source_map.map(|sm| sm as _),
187 debugging_opts.teach,
188 debugging_opts.terminal_width,
191 .ui_testing(debugging_opts.ui_testing),
194 ErrorOutputType::Json { pretty, json_rendered } => {
195 let source_map = source_map.unwrap_or_else(|| {
196 Lrc::new(source_map::SourceMap::new(source_map::FilePathMapping::empty()))
204 debugging_opts.terminal_width,
207 .ui_testing(debugging_opts.ui_testing),
212 rustc_errors::Handler::with_emitter_and_flags(
214 debugging_opts.diagnostic_handler_flags(true),
218 /// This function is used to setup the lint initialization. By default, in rustdoc, everything
219 /// is "allowed". Depending if we run in test mode or not, we want some of them to be at their
220 /// default level. For example, the "INVALID_CODEBLOCK_ATTRIBUTES" lint is activated in both
223 /// A little detail easy to forget is that there is a way to set the lint level for all lints
224 /// through the "WARNINGS" lint. To prevent this to happen, we set it back to its "normal" level
225 /// inside this function.
227 /// It returns a tuple containing:
228 /// * Vector of tuples of lints' name and their associated "max" level
229 /// * HashMap of lint id with their associated "max" level
230 pub(crate) fn init_lints<F>(
231 mut allowed_lints: Vec<String>,
232 lint_opts: Vec<(String, lint::Level)>,
234 ) -> (Vec<(String, lint::Level)>, FxHashMap<lint::LintId, lint::Level>)
236 F: Fn(&lint::Lint) -> Option<(String, lint::Level)>,
238 let warnings_lint_name = lint::builtin::WARNINGS.name;
240 allowed_lints.push(warnings_lint_name.to_owned());
241 allowed_lints.extend(lint_opts.iter().map(|(lint, _)| lint).cloned());
244 lint::builtin::HardwiredLints::get_lints()
246 .chain(rustc_lint::SoftLints::get_lints().into_iter())
249 let lint_opts = lints()
251 // Permit feature-gated lints to avoid feature errors when trying to
253 if lint.feature_gate.is_some() || allowed_lints.iter().any(|l| lint.name == l) {
259 .chain(lint_opts.into_iter())
260 .collect::<Vec<_>>();
262 let lint_caps = lints()
264 // We don't want to allow *all* lints so let's ignore
266 if allowed_lints.iter().any(|l| lint.name == l) {
269 Some((lint::LintId::of(lint), lint::Allow))
273 (lint_opts, lint_caps)
277 options: RustdocOptions,
278 ) -> (clean::Crate, RenderInfo, RenderOptions, Lrc<Session>) {
279 // Parse, resolve, and typecheck the given crate.
305 let extern_names: Vec<String> = externs
307 .filter(|(_, entry)| entry.add_prelude)
308 .map(|(name, _)| name)
312 // Add the doc cfg into the doc build.
313 cfgs.push("doc".to_string());
315 let cpath = Some(input.clone());
316 let input = Input::File(input);
318 let broken_intra_doc_links = lint::builtin::BROKEN_INTRA_DOC_LINKS.name;
319 let private_intra_doc_links = lint::builtin::PRIVATE_INTRA_DOC_LINKS.name;
320 let missing_docs = rustc_lint::builtin::MISSING_DOCS.name;
321 let missing_doc_example = rustc_lint::builtin::MISSING_DOC_CODE_EXAMPLES.name;
322 let private_doc_tests = rustc_lint::builtin::PRIVATE_DOC_TESTS.name;
323 let no_crate_level_docs = rustc_lint::builtin::MISSING_CRATE_LEVEL_DOCS.name;
324 let invalid_codeblock_attributes_name = rustc_lint::builtin::INVALID_CODEBLOCK_ATTRIBUTES.name;
325 let invalid_html_tags = rustc_lint::builtin::INVALID_HTML_TAGS.name;
326 let renamed_and_removed_lints = rustc_lint::builtin::RENAMED_AND_REMOVED_LINTS.name;
327 let non_autolinks = rustc_lint::builtin::NON_AUTOLINKS.name;
328 let unknown_lints = rustc_lint::builtin::UNKNOWN_LINTS.name;
330 // In addition to those specific lints, we also need to allow those given through
331 // command line, otherwise they'll get ignored and we don't want that.
332 let lints_to_show = vec![
333 broken_intra_doc_links.to_owned(),
334 private_intra_doc_links.to_owned(),
335 missing_docs.to_owned(),
336 missing_doc_example.to_owned(),
337 private_doc_tests.to_owned(),
338 no_crate_level_docs.to_owned(),
339 invalid_codeblock_attributes_name.to_owned(),
340 invalid_html_tags.to_owned(),
341 renamed_and_removed_lints.to_owned(),
342 unknown_lints.to_owned(),
343 non_autolinks.to_owned(),
346 let (lint_opts, lint_caps) = init_lints(lints_to_show, lint_opts, |lint| {
347 // FIXME: why is this necessary?
348 if lint.name == broken_intra_doc_links || lint.name == invalid_codeblock_attributes_name {
351 Some((lint.name_lower(), lint::Allow))
356 if proc_macro_crate { vec![CrateType::ProcMacro] } else { vec![CrateType::Rlib] };
357 // plays with error output here!
358 let sessopts = config::Options {
362 lint_opts: if !display_warnings { lint_opts } else { vec![] },
366 target_triple: target,
367 unstable_features: UnstableFeatures::from_environment(crate_name.as_deref()),
368 actually_rustdoc: true,
377 let config = interface::Config {
379 crate_cfg: interface::parse_cfgspecs(cfgs),
385 diagnostic_output: DiagnosticOutput::Default,
388 register_lints: None,
389 override_queries: Some(|_sess, providers, _external_providers| {
390 // Most lints will require typechecking, so just don't run them.
391 providers.lint_mod = |_, _| {};
392 // Prevent `rustc_typeck::check_crate` from calling `typeck` on all bodies.
393 providers.typeck_item_bodies = |_, _| {};
394 // hack so that `used_trait_imports` won't try to call typeck
395 providers.used_trait_imports = |_, _| {
397 static ref EMPTY_SET: FxHashSet<LocalDefId> = FxHashSet::default();
401 // In case typeck does end up being called, don't ICE in case there were name resolution errors
402 providers.typeck = move |tcx, def_id| {
403 // Closures' tables come from their outermost function,
404 // as they are part of the same "inference environment".
405 // This avoids emitting errors for the parent twice (see similar code in `typeck_with_fallback`)
406 let outer_def_id = tcx.closure_base_def_id(def_id.to_def_id()).expect_local();
407 if outer_def_id != def_id {
408 return tcx.typeck(outer_def_id);
412 let body = hir.body(hir.body_owned_by(hir.local_def_id_to_hir_id(def_id)));
413 debug!("visiting body for {:?}", def_id);
414 EmitIgnoredResolutionErrors::new(tcx).visit_body(body);
415 (rustc_interface::DEFAULT_QUERY_PROVIDERS.typeck)(tcx, def_id)
418 make_codegen_backend: None,
419 registry: rustc_driver::diagnostics_registry(),
422 interface::create_compiler_and_run(config, |compiler| {
423 compiler.enter(|queries| {
424 let sess = compiler.session();
426 // We need to hold on to the complete resolver, so we cause everything to be
427 // cloned for the analysis passes to use. Suboptimal, but necessary in the
428 // current architecture.
430 let parts = abort_on_err(queries.expansion(), sess).peek();
431 let resolver = parts.1.borrow();
433 // Before we actually clone it, let's force all the extern'd crates to
434 // actually be loaded, just in case they're only referred to inside
436 resolver.borrow_mut().access(|resolver| {
437 sess.time("load_extern_crates", || {
438 for extern_name in &extern_names {
439 debug!("loading extern crate {}", extern_name);
441 .resolve_str_path_error(
445 LocalDefId { local_def_index: CRATE_DEF_INDEX }.to_def_id(),
447 .unwrap_or_else(|()| {
448 panic!("Unable to resolve external crate {}", extern_name)
454 // Now we're good to clone the resolver because everything should be loaded
458 if sess.has_errors() {
459 sess.fatal("Compilation failed, aborting rustdoc");
462 let mut global_ctxt = abort_on_err(queries.global_ctxt(), sess).take();
464 let (krate, render_info, opts) = sess.time("run_global_ctxt", || {
465 global_ctxt.enter(|tcx| {
476 (krate, render_info, opts, Lrc::clone(sess))
483 resolver: Rc<RefCell<interface::BoxedResolver>>,
484 mut default_passes: passes::DefaultPassOption,
485 mut manual_passes: Vec<String>,
486 render_options: RenderOptions,
487 output_format: Option<OutputFormat>,
488 ) -> (clean::Crate, RenderInfo, RenderOptions) {
489 // Certain queries assume that some checks were run elsewhere
490 // (see https://github.com/rust-lang/rust/pull/73566#issuecomment-656954425),
491 // so type-check everything other than function bodies in this crate before running lints.
493 // NOTE: this does not call `tcx.analysis()` so that we won't
494 // typeck function bodies or run the default rustc lints.
495 // (see `override_queries` in the `config`)
497 // HACK(jynelson) this calls an _extremely_ limited subset of `typeck`
498 // and might break if queries change their assumptions in the future.
500 // NOTE: This is copy/pasted from typeck/lib.rs and should be kept in sync with those changes.
501 tcx.sess.time("item_types_checking", || {
502 for &module in tcx.hir().krate().modules.keys() {
503 tcx.ensure().check_mod_item_types(tcx.hir().local_def_id(module));
506 tcx.sess.abort_if_errors();
507 tcx.sess.time("missing_docs", || {
508 rustc_lint::check_crate(tcx, rustc_lint::builtin::MissingDoc::new);
510 tcx.sess.time("check_mod_attrs", || {
511 for &module in tcx.hir().krate().modules.keys() {
512 let local_def_id = tcx.hir().local_def_id(module);
513 tcx.ensure().check_mod_attrs(local_def_id);
517 let access_levels = tcx.privacy_access_levels(LOCAL_CRATE);
518 // Convert from a HirId set to a DefId set since we don't always have easy access
519 // to the map from defid -> hirid
520 let access_levels = AccessLevels {
524 .map(|(&k, &v)| (tcx.hir().local_def_id(k).to_def_id(), v))
528 let mut renderinfo = RenderInfo::default();
529 renderinfo.access_levels = access_levels;
530 renderinfo.output_format = output_format;
532 let mut ctxt = DocContext {
535 param_env: Cell::new(ParamEnv::empty()),
536 external_traits: Default::default(),
537 active_extern_traits: Default::default(),
538 renderinfo: RefCell::new(renderinfo),
539 ty_substs: Default::default(),
540 lt_substs: Default::default(),
541 ct_substs: Default::default(),
542 impl_trait_bounds: Default::default(),
543 fake_def_ids: Default::default(),
544 all_fake_def_ids: Default::default(),
545 generated_synthetics: Default::default(),
547 .all_traits(LOCAL_CRATE)
550 .filter(|trait_def_id| tcx.trait_is_auto(*trait_def_id))
553 module_trait_cache: RefCell::new(FxHashMap::default()),
555 debug!("crate: {:?}", tcx.hir().krate());
557 let mut krate = tcx.sess.time("clean_crate", || clean::krate(&mut ctxt));
559 if let Some(ref m) = krate.module {
560 if let None | Some("") = m.doc_value() {
561 let help = "The following guide may be of use:\n\
562 https://doc.rust-lang.org/nightly/rustdoc/how-to-write-documentation.html";
563 tcx.struct_lint_node(
564 rustc_lint::builtin::MISSING_CRATE_LEVEL_DOCS,
565 ctxt.as_local_hir_id(m.def_id).unwrap(),
568 lint.build("no documentation found for this crate's top-level module");
576 fn report_deprecated_attr(name: &str, diag: &rustc_errors::Handler) {
578 .struct_warn(&format!("the `#![doc({})]` attribute is considered deprecated", name));
580 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
581 for more information",
584 if name == "no_default_passes" {
585 msg.help("you may want to use `#![doc(document_private_items)]`");
591 // Process all of the crate attributes, extracting plugin metadata along
592 // with the passes which we are supposed to run.
593 for attr in krate.module.as_ref().unwrap().attrs.lists(sym::doc) {
594 let diag = ctxt.sess().diagnostic();
596 let name = attr.name_or_empty();
598 if name == sym::no_default_passes {
599 report_deprecated_attr("no_default_passes", diag);
600 if default_passes == passes::DefaultPassOption::Default {
601 default_passes = passes::DefaultPassOption::None;
604 } else if let Some(value) = attr.value_str() {
605 let sink = match name {
607 report_deprecated_attr("passes = \"...\"", diag);
611 report_deprecated_attr("plugins = \"...\"", diag);
613 "WARNING: `#![doc(plugins = \"...\")]` \
614 no longer functions; see CVE-2018-1000622"
620 for name in value.as_str().split_whitespace() {
621 sink.push(name.to_string());
625 if attr.is_word() && name == sym::document_private_items {
626 ctxt.render_options.document_private = true;
630 let passes = passes::defaults(default_passes).iter().copied().chain(
631 manual_passes.into_iter().flat_map(|name| {
632 if let Some(pass) = passes::find_pass(&name) {
633 Some(ConditionalPass::always(pass))
635 error!("unknown pass {}, skipping", name);
641 info!("Executing passes");
644 let run = match p.condition {
646 WhenDocumentPrivate => ctxt.render_options.document_private,
647 WhenNotDocumentPrivate => !ctxt.render_options.document_private,
648 WhenNotDocumentHidden => !ctxt.render_options.document_hidden,
651 debug!("running pass {}", p.pass.name);
652 krate = ctxt.tcx.sess.time(p.pass.name, || (p.pass.run)(krate, &ctxt));
656 ctxt.sess().abort_if_errors();
658 (krate, ctxt.renderinfo.into_inner(), ctxt.render_options)
661 /// Due to <https://github.com/rust-lang/rust/pull/73566>,
662 /// the name resolution pass may find errors that are never emitted.
663 /// If typeck is called after this happens, then we'll get an ICE:
664 /// 'Res::Error found but not reported'. To avoid this, emit the errors now.
665 struct EmitIgnoredResolutionErrors<'tcx> {
669 impl<'tcx> EmitIgnoredResolutionErrors<'tcx> {
670 fn new(tcx: TyCtxt<'tcx>) -> Self {
675 impl<'tcx> Visitor<'tcx> for EmitIgnoredResolutionErrors<'tcx> {
676 type Map = Map<'tcx>;
678 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
679 // We need to recurse into nested closures,
680 // since those will fallback to the parent for type checking.
681 NestedVisitorMap::OnlyBodies(self.tcx.hir())
684 fn visit_path(&mut self, path: &'tcx Path<'_>, _id: HirId) {
685 debug!("visiting path {:?}", path);
686 if path.res == Res::Err {
687 // We have less context here than in rustc_resolve,
688 // so we can only emit the name and span.
689 // However we can give a hint that rustc_resolve will have more info.
691 "could not resolve path `{}`",
694 .map(|segment| segment.ident.as_str().to_string())
698 let mut err = rustc_errors::struct_span_err!(
702 "failed to resolve: {}",
705 err.span_label(path.span, label);
706 err.note("this error was originally ignored because you are running `rustdoc`");
707 err.note("try running again with `rustc` or `cargo check` and you may get a more detailed error");
710 // We could have an outer resolution that succeeded,
711 // but with generic parameters that failed.
712 // Recurse into the segments so we catch those too.
713 intravisit::walk_path(self, path);
717 /// `DefId` or parameter index (`ty::ParamTy.index`) of a synthetic type parameter
718 /// for `impl Trait` in argument position.
719 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
720 crate enum ImplTraitParam {
725 impl From<DefId> for ImplTraitParam {
726 fn from(did: DefId) -> Self {
727 ImplTraitParam::DefId(did)
731 impl From<u32> for ImplTraitParam {
732 fn from(idx: u32) -> Self {
733 ImplTraitParam::ParamIndex(idx)