1 use rustc_ast::ast::CRATE_NODE_ID;
2 use rustc_attr as attr;
3 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
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;
9 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LOCAL_CRATE};
11 use rustc_interface::interface;
12 use rustc_middle::middle::cstore::CrateStore;
13 use rustc_middle::middle::privacy::AccessLevels;
14 use rustc_middle::ty::{Ty, TyCtxt};
15 use rustc_resolve as resolve;
16 use rustc_session::config::ErrorOutputType;
17 use rustc_session::lint;
18 use rustc_session::DiagnosticOutput;
19 use rustc_session::{config, Session};
20 use rustc_span::source_map;
21 use rustc_span::symbol::sym;
22 use rustc_span::DUMMY_SP;
24 use rustc_data_structures::sync::{self, Lrc};
25 use std::cell::RefCell;
30 use crate::clean::{AttributesExt, MAX_DEF_ID};
31 use crate::config::{Options as RustdocOptions, RenderOptions};
32 use crate::html::render::RenderInfo;
34 use crate::passes::{self, Condition::*, ConditionalPass};
36 pub use rustc_session::config::{CodegenOptions, DebuggingOptions, Input, Options};
37 pub use rustc_session::search_paths::SearchPath;
39 pub type ExternalPaths = FxHashMap<DefId, (Vec<String>, clean::TypeKind)>;
41 pub struct DocContext<'tcx> {
42 pub tcx: TyCtxt<'tcx>,
43 pub resolver: Rc<RefCell<interface::BoxedResolver>>,
44 /// Later on moved into `html::render::CACHE_KEY`
45 pub renderinfo: RefCell<RenderInfo>,
46 /// Later on moved through `clean::Crate` into `html::render::CACHE_KEY`
47 pub external_traits: Rc<RefCell<FxHashMap<DefId, clean::Trait>>>,
48 /// Used while populating `external_traits` to ensure we don't process the same trait twice at
50 pub active_extern_traits: RefCell<FxHashSet<DefId>>,
51 // The current set of type and lifetime substitutions,
52 // for expanding type aliases at the HIR level:
53 /// Table `DefId` of type parameter -> substituted type
54 pub ty_substs: RefCell<FxHashMap<DefId, clean::Type>>,
55 /// Table `DefId` of lifetime parameter -> substituted lifetime
56 pub lt_substs: RefCell<FxHashMap<DefId, clean::Lifetime>>,
57 /// Table `DefId` of const parameter -> substituted const
58 pub ct_substs: RefCell<FxHashMap<DefId, clean::Constant>>,
59 /// Table synthetic type parameter for `impl Trait` in argument position -> bounds
60 pub impl_trait_bounds: RefCell<FxHashMap<ImplTraitParam, Vec<clean::GenericBound>>>,
61 pub fake_def_ids: RefCell<FxHashMap<CrateNum, DefId>>,
62 pub all_fake_def_ids: RefCell<FxHashSet<DefId>>,
63 /// Auto-trait or blanket impls processed so far, as `(self_ty, trait_def_id)`.
64 // FIXME(eddyb) make this a `ty::TraitRef<'tcx>` set.
65 pub generated_synthetics: RefCell<FxHashSet<(Ty<'tcx>, DefId)>>,
66 pub auto_traits: Vec<DefId>,
69 impl<'tcx> DocContext<'tcx> {
70 pub fn sess(&self) -> &Session {
74 pub fn enter_resolver<F, R>(&self, f: F) -> R
76 F: FnOnce(&mut resolve::Resolver<'_>) -> R,
78 self.resolver.borrow_mut().access(f)
81 /// Call the closure with the given parameters set as
82 /// the substitutions for a type alias' RHS.
83 pub fn enter_alias<F, R>(
85 ty_substs: FxHashMap<DefId, clean::Type>,
86 lt_substs: FxHashMap<DefId, clean::Lifetime>,
87 ct_substs: FxHashMap<DefId, clean::Constant>,
93 let (old_tys, old_lts, old_cts) = (
94 mem::replace(&mut *self.ty_substs.borrow_mut(), ty_substs),
95 mem::replace(&mut *self.lt_substs.borrow_mut(), lt_substs),
96 mem::replace(&mut *self.ct_substs.borrow_mut(), ct_substs),
99 *self.ty_substs.borrow_mut() = old_tys;
100 *self.lt_substs.borrow_mut() = old_lts;
101 *self.ct_substs.borrow_mut() = old_cts;
105 // This is an ugly hack, but it's the simplest way to handle synthetic impls without greatly
106 // refactoring either librustdoc or librustc_middle. In particular, allowing new DefIds to be
107 // registered after the AST is constructed would require storing the defid mapping in a
108 // RefCell, decreasing the performance for normal compilation for very little gain.
110 // Instead, we construct 'fake' def ids, which start immediately after the last DefId.
111 // In the Debug impl for clean::Item, we explicitly check for fake
112 // def ids, as we'll end up with a panic if we use the DefId Debug impl for fake DefIds
113 pub fn next_def_id(&self, crate_num: CrateNum) -> DefId {
115 let next_id = if crate_num == LOCAL_CRATE {
116 self.tcx.hir().definitions().def_path_table().next_id()
118 self.enter_resolver(|r| r.cstore().def_path_table(crate_num).next_id())
121 DefId { krate: crate_num, index: next_id }
124 let mut fake_ids = self.fake_def_ids.borrow_mut();
126 let def_id = *fake_ids.entry(crate_num).or_insert(start_def_id);
129 DefId { krate: crate_num, index: DefIndex::from(def_id.index.index() + 1) },
132 MAX_DEF_ID.with(|m| {
133 m.borrow_mut().entry(def_id.krate.clone()).or_insert(start_def_id);
136 self.all_fake_def_ids.borrow_mut().insert(def_id);
141 /// Like the function of the same name on the HIR map, but skips calling it on fake DefIds.
142 /// (This avoids a slice-index-out-of-bounds panic.)
143 pub fn as_local_hir_id(&self, def_id: DefId) -> Option<HirId> {
144 if self.all_fake_def_ids.borrow().contains(&def_id) {
147 self.tcx.hir().as_local_hir_id(def_id)
151 pub fn stability(&self, id: HirId) -> Option<attr::Stability> {
154 .opt_local_def_id(id)
155 .and_then(|def_id| self.tcx.lookup_stability(def_id))
159 pub fn deprecation(&self, id: HirId) -> Option<attr::Deprecation> {
160 self.tcx.hir().opt_local_def_id(id).and_then(|def_id| self.tcx.lookup_deprecation(def_id))
164 /// Creates a new diagnostic `Handler` that can be used to emit warnings and errors.
166 /// If the given `error_format` is `ErrorOutputType::Json` and no `SourceMap` is given, a new one
167 /// will be created for the handler.
169 error_format: ErrorOutputType,
170 source_map: Option<Lrc<source_map::SourceMap>>,
171 debugging_opts: &DebuggingOptions,
172 ) -> rustc_errors::Handler {
173 let emitter: Box<dyn Emitter + sync::Send> = match error_format {
174 ErrorOutputType::HumanReadable(kind) => {
175 let (short, color_config) = kind.unzip();
177 EmitterWriter::stderr(
179 source_map.map(|sm| sm as _),
181 debugging_opts.teach,
182 debugging_opts.terminal_width,
185 .ui_testing(debugging_opts.ui_testing()),
188 ErrorOutputType::Json { pretty, json_rendered } => {
189 let source_map = source_map.unwrap_or_else(|| {
190 Lrc::new(source_map::SourceMap::new(source_map::FilePathMapping::empty()))
193 JsonEmitter::stderr(None, source_map, pretty, json_rendered, false)
194 .ui_testing(debugging_opts.ui_testing()),
199 rustc_errors::Handler::with_emitter_and_flags(
201 debugging_opts.diagnostic_handler_flags(true),
205 pub fn run_core(options: RustdocOptions) -> (clean::Crate, RenderInfo, RenderOptions) {
206 // Parse, resolve, and typecheck the given crate.
225 mut document_private,
234 let extern_names: Vec<String> = externs
236 .filter(|(_, entry)| entry.add_prelude)
237 .map(|(name, _)| name)
241 // Add the doc cfg into the doc build.
242 cfgs.push("doc".to_string());
244 let cpath = Some(input.clone());
245 let input = Input::File(input);
247 let intra_link_resolution_failure_name = lint::builtin::INTRA_DOC_LINK_RESOLUTION_FAILURE.name;
248 let warnings_lint_name = lint::builtin::WARNINGS.name;
249 let missing_docs = rustc_lint::builtin::MISSING_DOCS.name;
250 let missing_doc_example = rustc_lint::builtin::MISSING_DOC_CODE_EXAMPLES.name;
251 let private_doc_tests = rustc_lint::builtin::PRIVATE_DOC_TESTS.name;
252 let no_crate_level_docs = rustc_lint::builtin::MISSING_CRATE_LEVEL_DOCS.name;
254 // In addition to those specific lints, we also need to whitelist those given through
255 // command line, otherwise they'll get ignored and we don't want that.
256 let mut whitelisted_lints = vec![
257 warnings_lint_name.to_owned(),
258 intra_link_resolution_failure_name.to_owned(),
259 missing_docs.to_owned(),
260 missing_doc_example.to_owned(),
261 private_doc_tests.to_owned(),
262 no_crate_level_docs.to_owned(),
265 whitelisted_lints.extend(lint_opts.iter().map(|(lint, _)| lint).cloned());
268 lint::builtin::HardwiredLints::get_lints()
270 .chain(rustc_lint::SoftLints::get_lints().into_iter())
273 let lint_opts = lints()
275 if lint.name == warnings_lint_name || lint.name == intra_link_resolution_failure_name {
278 Some((lint.name_lower(), lint::Allow))
281 .chain(lint_opts.into_iter())
282 .collect::<Vec<_>>();
284 let lint_caps = lints()
286 // We don't want to whitelist *all* lints so let's
287 // ignore those ones.
288 if whitelisted_lints.iter().any(|l| lint.name == l) {
291 Some((lint::LintId::of(lint), lint::Allow))
296 let crate_types = if proc_macro_crate {
297 vec![config::CrateType::ProcMacro]
299 vec![config::CrateType::Rlib]
301 // plays with error output here!
302 let sessopts = config::Options {
306 lint_opts: if !display_warnings { lint_opts } else { vec![] },
307 lint_cap: Some(lint_cap.unwrap_or_else(|| lint::Forbid)),
310 target_triple: target,
311 unstable_features: UnstableFeatures::from_environment(),
312 actually_rustdoc: true,
313 debugging_opts: debugging_options,
320 let config = interface::Config {
322 crate_cfg: interface::parse_cfgspecs(cfgs),
328 diagnostic_output: DiagnosticOutput::Default,
332 register_lints: None,
333 override_queries: None,
334 registry: rustc_driver::diagnostics_registry(),
337 interface::run_compiler_in_existing_thread_pool(config, |compiler| {
338 compiler.enter(|queries| {
339 let sess = compiler.session();
341 // We need to hold on to the complete resolver, so we cause everything to be
342 // cloned for the analysis passes to use. Suboptimal, but necessary in the
343 // current architecture.
345 let parts = abort_on_err(queries.expansion(), sess).peek();
346 let resolver = parts.1.borrow();
348 // Before we actually clone it, let's force all the extern'd crates to
349 // actually be loaded, just in case they're only referred to inside
351 resolver.borrow_mut().access(|resolver| {
352 for extern_name in &extern_names {
354 .resolve_str_path_error(DUMMY_SP, extern_name, TypeNS, CRATE_NODE_ID)
355 .unwrap_or_else(|()| {
356 panic!("Unable to resolve external crate {}", extern_name)
361 // Now we're good to clone the resolver because everything should be loaded
365 if sess.has_errors() {
366 sess.fatal("Compilation failed, aborting rustdoc");
369 let mut global_ctxt = abort_on_err(queries.global_ctxt(), sess).take();
371 global_ctxt.enter(|tcx| {
372 tcx.analysis(LOCAL_CRATE).ok();
374 // Abort if there were any errors so far
375 sess.abort_if_errors();
377 let access_levels = tcx.privacy_access_levels(LOCAL_CRATE);
378 // Convert from a HirId set to a DefId set since we don't always have easy access
379 // to the map from defid -> hirid
380 let access_levels = AccessLevels {
384 .map(|(&k, &v)| (tcx.hir().local_def_id(k), v))
388 let mut renderinfo = RenderInfo::default();
389 renderinfo.access_levels = access_levels;
390 renderinfo.output_format = output_format;
392 let mut ctxt = DocContext {
395 external_traits: Default::default(),
396 active_extern_traits: Default::default(),
397 renderinfo: RefCell::new(renderinfo),
398 ty_substs: Default::default(),
399 lt_substs: Default::default(),
400 ct_substs: Default::default(),
401 impl_trait_bounds: Default::default(),
402 fake_def_ids: Default::default(),
403 all_fake_def_ids: Default::default(),
404 generated_synthetics: Default::default(),
406 .all_traits(LOCAL_CRATE)
409 .filter(|trait_def_id| tcx.trait_is_auto(*trait_def_id))
412 debug!("crate: {:?}", tcx.hir().krate());
414 let mut krate = clean::krate(&mut ctxt);
416 if let Some(ref m) = krate.module {
417 if let None | Some("") = m.doc_value() {
418 let help = "The following guide may be of use:\n\
419 https://doc.rust-lang.org/nightly/rustdoc/how-to-write-documentation\
421 tcx.struct_lint_node(
422 rustc_lint::builtin::MISSING_CRATE_LEVEL_DOCS,
423 ctxt.as_local_hir_id(m.def_id).unwrap(),
425 let mut diag = lint.build(
426 "no documentation found for this crate's top-level module",
435 fn report_deprecated_attr(name: &str, diag: &rustc_errors::Handler) {
436 let mut msg = diag.struct_warn(&format!(
437 "the `#![doc({})]` attribute is considered deprecated",
441 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
442 for more information",
445 if name == "no_default_passes" {
446 msg.help("you may want to use `#![doc(document_private_items)]`");
452 // Process all of the crate attributes, extracting plugin metadata along
453 // with the passes which we are supposed to run.
454 for attr in krate.module.as_ref().unwrap().attrs.lists(sym::doc) {
455 let diag = ctxt.sess().diagnostic();
457 let name = attr.name_or_empty();
459 if name == sym::no_default_passes {
460 report_deprecated_attr("no_default_passes", diag);
461 if default_passes == passes::DefaultPassOption::Default {
462 default_passes = passes::DefaultPassOption::None;
465 } else if let Some(value) = attr.value_str() {
466 let sink = match name {
468 report_deprecated_attr("passes = \"...\"", diag);
472 report_deprecated_attr("plugins = \"...\"", diag);
474 "WARNING: `#![doc(plugins = \"...\")]` \
475 no longer functions; see CVE-2018-1000622"
481 for name in value.as_str().split_whitespace() {
482 sink.push(name.to_string());
486 if attr.is_word() && name == sym::document_private_items {
487 document_private = true;
491 let passes = passes::defaults(default_passes).iter().copied().chain(
492 manual_passes.into_iter().flat_map(|name| {
493 if let Some(pass) = passes::find_pass(&name) {
494 Some(ConditionalPass::always(pass))
496 error!("unknown pass {}, skipping", name);
502 info!("Executing passes");
505 let run = match p.condition {
507 WhenDocumentPrivate => document_private,
508 WhenNotDocumentPrivate => !document_private,
509 WhenNotDocumentHidden => !document_hidden,
512 debug!("running pass {}", p.pass.name);
513 krate = (p.pass.run)(krate, &ctxt);
517 ctxt.sess().abort_if_errors();
519 (krate, ctxt.renderinfo.into_inner(), render_options)
525 /// `DefId` or parameter index (`ty::ParamTy.index`) of a synthetic type parameter
526 /// for `impl Trait` in argument position.
527 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
528 pub enum ImplTraitParam {
533 impl From<DefId> for ImplTraitParam {
534 fn from(did: DefId) -> Self {
535 ImplTraitParam::DefId(did)
539 impl From<u32> for ImplTraitParam {
540 fn from(idx: u32) -> Self {
541 ImplTraitParam::ParamIndex(idx)