2 use rustc::session::{self, config};
3 use rustc::hir::def_id::{DefId, DefIndex, CrateNum, LOCAL_CRATE};
5 use rustc::middle::cstore::CrateStore;
6 use rustc::middle::privacy::AccessLevels;
7 use rustc::ty::{Ty, TyCtxt};
8 use rustc::lint::{self, LintPass};
9 use rustc::session::config::ErrorOutputType;
10 use rustc::session::DiagnosticOutput;
11 use rustc::util::nodemap::{FxHashMap, FxHashSet};
12 use rustc_interface::interface;
13 use rustc_driver::abort_on_err;
14 use rustc_resolve as resolve;
15 use rustc_metadata::cstore::CStore;
16 use rustc_target::spec::TargetTriple;
18 use syntax::source_map;
19 use syntax::feature_gate::UnstableFeatures;
20 use syntax::json::JsonEmitter;
21 use syntax::symbol::sym;
23 use errors::emitter::{Emitter, EmitterWriter};
24 use parking_lot::ReentrantMutex;
26 use std::cell::RefCell;
28 use rustc_data_structures::sync::{self, Lrc};
32 use crate::visit_ast::RustdocVisitor;
33 use crate::config::{Options as RustdocOptions, RenderOptions};
35 use crate::clean::{Clean, MAX_DEF_ID, AttributesExt};
36 use crate::html::render::RenderInfo;
40 pub use rustc::session::config::{Input, Options, CodegenOptions};
41 pub use rustc::session::search_paths::SearchPath;
43 pub type ExternalPaths = FxHashMap<DefId, (Vec<String>, clean::TypeKind)>;
45 pub struct DocContext<'tcx> {
47 pub tcx: TyCtxt<'tcx, 'tcx, 'tcx>,
48 pub resolver: Rc<Option<RefCell<interface::BoxedResolver>>>,
49 /// The stack of module NodeIds up till this point
50 pub crate_name: Option<String>,
51 pub cstore: Lrc<CStore>,
52 /// Later on moved into `html::render::CACHE_KEY`
53 pub renderinfo: RefCell<RenderInfo>,
54 /// Later on moved through `clean::Crate` into `html::render::CACHE_KEY`
55 pub external_traits: Arc<ReentrantMutex<RefCell<FxHashMap<DefId, clean::Trait>>>>,
56 /// Used while populating `external_traits` to ensure we don't process the same trait twice at
58 pub active_extern_traits: RefCell<Vec<DefId>>,
59 // The current set of type and lifetime substitutions,
60 // for expanding type aliases at the HIR level:
62 /// Table `DefId` of type parameter -> substituted type
63 pub ty_substs: RefCell<FxHashMap<DefId, clean::Type>>,
64 /// Table `DefId` of lifetime parameter -> substituted lifetime
65 pub lt_substs: RefCell<FxHashMap<DefId, clean::Lifetime>>,
66 /// Table `DefId` of const parameter -> substituted const
67 pub ct_substs: RefCell<FxHashMap<DefId, clean::Constant>>,
68 /// Table DefId of `impl Trait` in argument position -> bounds
69 pub impl_trait_bounds: RefCell<FxHashMap<DefId, Vec<clean::GenericBound>>>,
70 pub send_trait: Option<DefId>,
71 pub fake_def_ids: RefCell<FxHashMap<CrateNum, DefId>>,
72 pub all_fake_def_ids: RefCell<FxHashSet<DefId>>,
73 /// Auto-trait or blanket impls processed so far, as `(self_ty, trait_def_id)`.
74 // FIXME(eddyb) make this a `ty::TraitRef<'tcx>` set.
75 pub generated_synthetics: RefCell<FxHashSet<(Ty<'tcx>, DefId)>>,
76 pub all_traits: Vec<DefId>,
79 impl<'tcx> DocContext<'tcx> {
80 pub fn sess(&self) -> &session::Session {
84 pub fn enter_resolver<F, R>(&self, f: F) -> R
85 where F: FnOnce(&mut resolve::Resolver<'_>) -> R {
86 let resolver = &*self.resolver;
87 let resolver = resolver.as_ref().unwrap();
88 resolver.borrow_mut().access(f)
91 /// Call the closure with the given parameters set as
92 /// the substitutions for a type alias' RHS.
93 pub fn enter_alias<F, R>(&self,
94 ty_substs: FxHashMap<DefId, clean::Type>,
95 lt_substs: FxHashMap<DefId, clean::Lifetime>,
96 ct_substs: FxHashMap<DefId, clean::Constant>,
98 where F: FnOnce() -> R {
99 let (old_tys, old_lts, old_cts) = (
100 mem::replace(&mut *self.ty_substs.borrow_mut(), ty_substs),
101 mem::replace(&mut *self.lt_substs.borrow_mut(), lt_substs),
102 mem::replace(&mut *self.ct_substs.borrow_mut(), ct_substs),
105 *self.ty_substs.borrow_mut() = old_tys;
106 *self.lt_substs.borrow_mut() = old_lts;
107 *self.ct_substs.borrow_mut() = old_cts;
111 // This is an ugly hack, but it's the simplest way to handle synthetic impls without greatly
112 // refactoring either librustdoc or librustc. In particular, allowing new DefIds to be
113 // registered after the AST is constructed would require storing the defid mapping in a
114 // RefCell, decreasing the performance for normal compilation for very little gain.
116 // Instead, we construct 'fake' def ids, which start immediately after the last DefId.
117 // In the Debug impl for clean::Item, we explicitly check for fake
118 // def ids, as we'll end up with a panic if we use the DefId Debug impl for fake DefIds
119 pub fn next_def_id(&self, crate_num: CrateNum) -> DefId {
121 let next_id = if crate_num == LOCAL_CRATE {
129 .def_path_table(crate_num)
139 let mut fake_ids = self.fake_def_ids.borrow_mut();
141 let def_id = fake_ids.entry(crate_num).or_insert(start_def_id).clone();
146 index: DefIndex::from(def_id.index.index() + 1),
150 MAX_DEF_ID.with(|m| {
152 .entry(def_id.krate.clone())
153 .or_insert(start_def_id);
156 self.all_fake_def_ids.borrow_mut().insert(def_id);
161 /// Like the function of the same name on the HIR map, but skips calling it on fake DefIds.
162 /// (This avoids a slice-index-out-of-bounds panic.)
163 pub fn as_local_hir_id(&self, def_id: DefId) -> Option<HirId> {
164 if self.all_fake_def_ids.borrow().contains(&def_id) {
167 self.tcx.hir().as_local_hir_id(def_id)
172 pub trait DocAccessLevels {
173 fn is_doc_reachable(&self, did: DefId) -> bool;
176 impl DocAccessLevels for AccessLevels<DefId> {
177 fn is_doc_reachable(&self, did: DefId) -> bool {
182 /// Creates a new diagnostic `Handler` that can be used to emit warnings and errors.
184 /// If the given `error_format` is `ErrorOutputType::Json` and no `SourceMap` is given, a new one
185 /// will be created for the handler.
186 pub fn new_handler(error_format: ErrorOutputType,
187 source_map: Option<Lrc<source_map::SourceMap>>,
188 treat_err_as_bug: Option<usize>,
190 ) -> errors::Handler {
191 // rustdoc doesn't override (or allow to override) anything from this that is relevant here, so
192 // stick to the defaults
193 let sessopts = Options::default();
194 let emitter: Box<dyn Emitter + sync::Send> = match error_format {
195 ErrorOutputType::HumanReadable(kind) => {
196 let (short, color_config) = kind.unzip();
198 EmitterWriter::stderr(
200 source_map.map(|cm| cm as _),
202 sessopts.debugging_opts.teach,
203 ).ui_testing(ui_testing)
206 ErrorOutputType::Json { pretty, json_rendered } => {
207 let source_map = source_map.unwrap_or_else(
208 || Lrc::new(source_map::SourceMap::new(sessopts.file_path_mapping())));
215 ).ui_testing(ui_testing)
220 errors::Handler::with_emitter_and_flags(
222 errors::HandlerFlags {
223 can_emit_warnings: true,
225 report_delayed_bugs: false,
226 external_macro_backtrace: false,
232 pub fn run_core(options: RustdocOptions) -> (clean::Crate, RenderInfo, RenderOptions, Vec<String>) {
233 // Parse, resolve, and typecheck the given crate.
257 let cpath = Some(input.clone());
258 let input = Input::File(input);
260 let intra_link_resolution_failure_name = lint::builtin::INTRA_DOC_LINK_RESOLUTION_FAILURE.name;
261 let warnings_lint_name = lint::builtin::WARNINGS.name;
262 let missing_docs = rustc_lint::builtin::MISSING_DOCS.name;
263 let missing_doc_example = rustc_lint::builtin::MISSING_DOC_CODE_EXAMPLES.name;
264 let private_doc_tests = rustc_lint::builtin::PRIVATE_DOC_TESTS.name;
266 // In addition to those specific lints, we also need to whitelist those given through
267 // command line, otherwise they'll get ignored and we don't want that.
268 let mut whitelisted_lints = vec![warnings_lint_name.to_owned(),
269 intra_link_resolution_failure_name.to_owned(),
270 missing_docs.to_owned(),
271 missing_doc_example.to_owned(),
272 private_doc_tests.to_owned()];
274 whitelisted_lints.extend(lint_opts.iter().map(|(lint, _)| lint).cloned());
277 lint::builtin::HardwiredLints
280 .chain(rustc_lint::SoftLints.get_lints().into_iter())
283 let lint_opts = lints().filter_map(|lint| {
284 if lint.name == warnings_lint_name ||
285 lint.name == intra_link_resolution_failure_name {
288 Some((lint.name_lower(), lint::Allow))
290 }).chain(lint_opts.into_iter()).collect::<Vec<_>>();
292 let lint_caps = lints().filter_map(|lint| {
293 // We don't want to whitelist *all* lints so let's
294 // ignore those ones.
295 if whitelisted_lints.iter().any(|l| &lint.name == l) {
298 Some((lint::LintId::of(lint), lint::Allow))
302 let host_triple = TargetTriple::from_triple(config::host_triple());
303 // plays with error output here!
304 let sessopts = config::Options {
307 crate_types: vec![config::CrateType::Rlib],
308 lint_opts: if !display_warnings {
313 lint_cap: Some(lint_cap.unwrap_or_else(|| lint::Forbid)),
316 target_triple: target.unwrap_or(host_triple),
317 // Ensure that rustdoc works even if rustc is feature-staged
318 unstable_features: UnstableFeatures::Allow,
319 actually_rustdoc: true,
320 debugging_opts: debugging_options.clone(),
327 let config = interface::Config {
329 crate_cfg: config::parse_cfgspecs(cfgs),
335 diagnostic_output: DiagnosticOutput::Default,
337 crate_name: crate_name.clone(),
341 interface::run_compiler_in_existing_thread_pool(config, |compiler| {
342 let sess = compiler.session();
344 // We need to hold on to the complete resolver, so we cause everything to be
345 // cloned for the analysis passes to use. Suboptimal, but necessary in the
346 // current architecture.
347 let resolver = abort_on_err(compiler.expansion(), sess).peek().1.clone();
349 if sess.err_count() > 0 {
350 sess.fatal("Compilation failed, aborting rustdoc");
353 let mut global_ctxt = abort_on_err(compiler.global_ctxt(), sess).take();
355 global_ctxt.enter(|tcx| {
356 tcx.analysis(LOCAL_CRATE).ok();
358 // Abort if there were any errors so far
359 sess.abort_if_errors();
361 let access_levels = tcx.privacy_access_levels(LOCAL_CRATE);
362 // Convert from a HirId set to a DefId set since we don't always have easy access
363 // to the map from defid -> hirid
364 let access_levels = AccessLevels {
365 map: access_levels.map.iter()
366 .map(|(&k, &v)| (tcx.hir().local_def_id_from_hir_id(k), v))
370 let send_trait = if crate_name == Some("core".to_string()) {
371 clean::path_to_def_local(tcx, &[sym::marker, sym::Send])
373 clean::path_to_def(tcx, &[sym::core, sym::marker, sym::Send])
376 let mut renderinfo = RenderInfo::default();
377 renderinfo.access_levels = access_levels;
379 let ctxt = DocContext {
383 cstore: compiler.cstore().clone(),
384 external_traits: Default::default(),
385 active_extern_traits: Default::default(),
386 renderinfo: RefCell::new(renderinfo),
387 ty_substs: Default::default(),
388 lt_substs: Default::default(),
389 ct_substs: Default::default(),
390 impl_trait_bounds: Default::default(),
391 send_trait: send_trait,
392 fake_def_ids: Default::default(),
393 all_fake_def_ids: Default::default(),
394 generated_synthetics: Default::default(),
395 all_traits: tcx.all_traits(LOCAL_CRATE).to_vec(),
397 debug!("crate: {:?}", tcx.hir().krate());
400 let mut v = RustdocVisitor::new(&ctxt);
401 v.visit(tcx.hir().krate());
405 fn report_deprecated_attr(name: &str, diag: &errors::Handler) {
406 let mut msg = diag.struct_warn(&format!("the `#![doc({})]` attribute is \
407 considered deprecated", name));
408 msg.warn("please see https://github.com/rust-lang/rust/issues/44136");
410 if name == "no_default_passes" {
411 msg.help("you may want to use `#![doc(document_private_items)]`");
417 // Process all of the crate attributes, extracting plugin metadata along
418 // with the passes which we are supposed to run.
419 for attr in krate.module.as_ref().unwrap().attrs.lists(sym::doc) {
420 let diag = ctxt.sess().diagnostic();
422 let name = attr.name_or_empty();
424 if name == sym::no_default_passes {
425 report_deprecated_attr("no_default_passes", diag);
426 if default_passes == passes::DefaultPassOption::Default {
427 default_passes = passes::DefaultPassOption::None;
430 } else if let Some(value) = attr.value_str() {
431 let sink = match name {
433 report_deprecated_attr("passes = \"...\"", diag);
437 report_deprecated_attr("plugins = \"...\"", diag);
438 eprintln!("WARNING: #![doc(plugins = \"...\")] no longer functions; \
439 see CVE-2018-1000622");
444 for p in value.as_str().split_whitespace() {
445 sink.push(p.to_string());
449 if attr.is_word() && name == sym::document_private_items {
450 if default_passes == passes::DefaultPassOption::Default {
451 default_passes = passes::DefaultPassOption::Private;
456 let mut passes: Vec<String> =
457 passes::defaults(default_passes).iter().map(|p| p.to_string()).collect();
458 passes.extend(manual_passes);
460 info!("Executing passes");
462 for pass_name in &passes {
463 match passes::find_pass(pass_name).map(|p| p.pass) {
465 debug!("running pass {}", pass_name);
466 krate = pass(krate, &ctxt);
468 None => error!("unknown pass {}, skipping", *pass_name),
472 ctxt.sess().abort_if_errors();
474 (krate, ctxt.renderinfo.into_inner(), render_options, passes)