2 use rustc::session::{self, config};
3 use rustc::hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CrateNum, LOCAL_CRATE};
4 use rustc::hir::def::Def;
5 use rustc::hir::{self, HirId, HirVec};
6 use rustc::middle::cstore::CrateStore;
7 use rustc::middle::privacy::AccessLevels;
8 use rustc::ty::{self, TyCtxt};
9 use rustc::lint::{self, LintPass};
10 use rustc::session::config::ErrorOutputType;
11 use rustc::session::DiagnosticOutput;
12 use rustc::util::nodemap::{FxHashMap, FxHashSet};
13 use rustc_interface::interface;
14 use rustc_driver::abort_on_err;
15 use rustc_resolve as resolve;
16 use rustc_metadata::cstore::CStore;
17 use rustc_target::spec::TargetTriple;
19 use syntax::ast::{self, Ident};
20 use syntax::source_map;
21 use syntax::feature_gate::UnstableFeatures;
22 use syntax::json::JsonEmitter;
24 use syntax::symbol::keywords;
25 use syntax_pos::DUMMY_SP;
27 use errors::emitter::{Emitter, EmitterWriter};
28 use parking_lot::ReentrantMutex;
30 use std::cell::RefCell;
32 use rustc_data_structures::sync::{self, Lrc};
36 use crate::visit_ast::RustdocVisitor;
37 use crate::config::{Options as RustdocOptions, RenderOptions};
39 use crate::clean::{get_path_for_type, Clean, MAX_DEF_ID, AttributesExt};
40 use crate::html::render::RenderInfo;
44 pub use rustc::session::config::{Input, Options, CodegenOptions};
45 pub use rustc::session::search_paths::SearchPath;
47 pub type ExternalPaths = FxHashMap<DefId, (Vec<String>, clean::TypeKind)>;
49 pub struct DocContext<'tcx> {
51 pub tcx: TyCtxt<'tcx, 'tcx, 'tcx>,
52 pub resolver: Rc<Option<RefCell<interface::BoxedResolver>>>,
53 /// The stack of module NodeIds up till this point
54 pub crate_name: Option<String>,
55 pub cstore: Lrc<CStore>,
56 /// Later on moved into `html::render::CACHE_KEY`
57 pub renderinfo: RefCell<RenderInfo>,
58 /// Later on moved through `clean::Crate` into `html::render::CACHE_KEY`
59 pub external_traits: Arc<ReentrantMutex<RefCell<FxHashMap<DefId, clean::Trait>>>>,
60 /// Used while populating `external_traits` to ensure we don't process the same trait twice at
62 pub active_extern_traits: RefCell<Vec<DefId>>,
63 // The current set of type and lifetime substitutions,
64 // for expanding type aliases at the HIR level:
66 /// Table type parameter definition -> substituted type
67 pub ty_substs: RefCell<FxHashMap<Def, clean::Type>>,
68 /// Table `NodeId` of lifetime parameter definition -> substituted lifetime
69 pub lt_substs: RefCell<FxHashMap<DefId, clean::Lifetime>>,
70 /// Table node id of const parameter definition -> substituted const
71 pub ct_substs: RefCell<FxHashMap<Def, clean::Constant>>,
72 /// Table DefId of `impl Trait` in argument position -> bounds
73 pub impl_trait_bounds: RefCell<FxHashMap<DefId, Vec<clean::GenericBound>>>,
74 pub send_trait: Option<DefId>,
75 pub fake_def_ids: RefCell<FxHashMap<CrateNum, DefId>>,
76 pub all_fake_def_ids: RefCell<FxHashSet<DefId>>,
77 /// Maps (type_id, trait_id) -> auto trait impl
78 pub generated_synthetics: RefCell<FxHashSet<(DefId, DefId)>>,
79 pub all_traits: Vec<DefId>,
82 impl<'tcx> DocContext<'tcx> {
83 pub fn sess(&self) -> &session::Session {
87 pub fn enter_resolver<F, R>(&self, f: F) -> R
88 where F: FnOnce(&mut resolve::Resolver<'_>) -> R {
89 let resolver = &*self.resolver;
90 let resolver = resolver.as_ref().unwrap();
91 resolver.borrow_mut().access(f)
94 /// Call the closure with the given parameters set as
95 /// the substitutions for a type alias' RHS.
96 pub fn enter_alias<F, R>(&self,
97 ty_substs: FxHashMap<Def, clean::Type>,
98 lt_substs: FxHashMap<DefId, clean::Lifetime>,
99 ct_substs: FxHashMap<Def, clean::Constant>,
101 where F: FnOnce() -> R {
102 let (old_tys, old_lts, old_cts) = (
103 mem::replace(&mut *self.ty_substs.borrow_mut(), ty_substs),
104 mem::replace(&mut *self.lt_substs.borrow_mut(), lt_substs),
105 mem::replace(&mut *self.ct_substs.borrow_mut(), ct_substs),
108 *self.ty_substs.borrow_mut() = old_tys;
109 *self.lt_substs.borrow_mut() = old_lts;
110 *self.ct_substs.borrow_mut() = old_cts;
114 // This is an ugly hack, but it's the simplest way to handle synthetic impls without greatly
115 // refactoring either librustdoc or librustc. In particular, allowing new DefIds to be
116 // registered after the AST is constructed would require storing the defid mapping in a
117 // RefCell, decreasing the performance for normal compilation for very little gain.
119 // Instead, we construct 'fake' def ids, which start immediately after the last DefId in
120 // DefIndexAddressSpace::Low. In the Debug impl for clean::Item, we explicitly check for fake
121 // def ids, as we'll end up with a panic if we use the DefId Debug impl for fake DefIds
122 pub fn next_def_id(&self, crate_num: CrateNum) -> DefId {
124 let next_id = if crate_num == LOCAL_CRATE {
129 .next_id(DefIndexAddressSpace::Low)
132 .def_path_table(crate_num)
133 .next_id(DefIndexAddressSpace::Low)
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).clone();
149 index: DefIndex::from_array_index(
150 def_id.index.as_array_index() + 1,
151 def_id.index.address_space(),
156 MAX_DEF_ID.with(|m| {
158 .entry(def_id.krate.clone())
159 .or_insert(start_def_id);
162 self.all_fake_def_ids.borrow_mut().insert(def_id);
167 /// Like the function of the same name on the HIR map, but skips calling it on fake DefIds.
168 /// (This avoids a slice-index-out-of-bounds panic.)
169 pub fn as_local_node_id(&self, def_id: DefId) -> Option<ast::NodeId> {
170 if self.all_fake_def_ids.borrow().contains(&def_id) {
173 self.tcx.hir().as_local_node_id(def_id)
177 // FIXME(@ljedrz): remove the NodeId variant
178 pub fn as_local_hir_id(&self, def_id: DefId) -> Option<HirId> {
179 if self.all_fake_def_ids.borrow().contains(&def_id) {
182 self.tcx.hir().as_local_hir_id(def_id)
186 pub fn get_real_ty<F>(&self,
189 real_name: &Option<Ident>,
190 generics: &ty::Generics,
192 where F: Fn(DefId) -> Def {
193 let path = get_path_for_type(self.tcx, def_id, def_ctor);
194 let mut segments = path.segments.into_vec();
195 let last = segments.pop().expect("segments were empty");
197 segments.push(hir::PathSegment::new(
198 real_name.unwrap_or(last.ident),
201 self.generics_to_path_params(generics.clone()),
205 let new_path = hir::Path {
208 segments: HirVec::from_vec(segments),
212 node: hir::TyKind::Path(hir::QPath::Resolved(None, P(new_path))),
214 hir_id: hir::DUMMY_HIR_ID,
218 pub fn generics_to_path_params(&self, generics: ty::Generics) -> hir::GenericArgs {
219 let mut args = vec![];
221 for param in generics.params.iter() {
223 ty::GenericParamDefKind::Lifetime => {
224 let name = if param.name == "" {
225 hir::ParamName::Plain(keywords::StaticLifetime.ident())
227 hir::ParamName::Plain(ast::Ident::from_interned_str(param.name))
230 args.push(hir::GenericArg::Lifetime(hir::Lifetime {
231 hir_id: hir::DUMMY_HIR_ID,
233 name: hir::LifetimeName::Param(name),
236 ty::GenericParamDefKind::Type { .. } => {
237 args.push(hir::GenericArg::Type(self.ty_param_to_ty(param.clone())));
239 ty::GenericParamDefKind::Const => {
240 args.push(hir::GenericArg::Const(hir::ConstArg {
241 value: hir::AnonConst {
242 hir_id: hir::DUMMY_HIR_ID,
244 hir_id: hir::DUMMY_HIR_ID,
254 args: HirVec::from_vec(args),
255 bindings: HirVec::new(),
256 parenthesized: false,
260 pub fn ty_param_to_ty(&self, param: ty::GenericParamDef) -> hir::Ty {
261 debug!("ty_param_to_ty({:?}) {:?}", param, param.def_id);
263 node: hir::TyKind::Path(hir::QPath::Resolved(
267 def: Def::TyParam(param.def_id),
268 segments: HirVec::from_vec(vec![
269 hir::PathSegment::from_ident(Ident::from_interned_str(param.name))
274 hir_id: hir::DUMMY_HIR_ID,
279 pub trait DocAccessLevels {
280 fn is_doc_reachable(&self, did: DefId) -> bool;
283 impl DocAccessLevels for AccessLevels<DefId> {
284 fn is_doc_reachable(&self, did: DefId) -> bool {
289 /// Creates a new diagnostic `Handler` that can be used to emit warnings and errors.
291 /// If the given `error_format` is `ErrorOutputType::Json` and no `SourceMap` is given, a new one
292 /// will be created for the handler.
293 pub fn new_handler(error_format: ErrorOutputType,
294 source_map: Option<Lrc<source_map::SourceMap>>,
295 treat_err_as_bug: Option<usize>,
297 ) -> errors::Handler {
298 // rustdoc doesn't override (or allow to override) anything from this that is relevant here, so
299 // stick to the defaults
300 let sessopts = Options::default();
301 let emitter: Box<dyn Emitter + sync::Send> = match error_format {
302 ErrorOutputType::HumanReadable(color_config) => Box::new(
303 EmitterWriter::stderr(
305 source_map.map(|cm| cm as _),
307 sessopts.debugging_opts.teach,
308 ).ui_testing(ui_testing)
310 ErrorOutputType::Json(pretty) => {
311 let source_map = source_map.unwrap_or_else(
312 || Lrc::new(source_map::SourceMap::new(sessopts.file_path_mapping())));
318 ).ui_testing(ui_testing)
321 ErrorOutputType::Short(color_config) => Box::new(
322 EmitterWriter::stderr(
324 source_map.map(|cm| cm as _),
330 errors::Handler::with_emitter_and_flags(
332 errors::HandlerFlags {
333 can_emit_warnings: true,
335 report_delayed_bugs: false,
336 external_macro_backtrace: false,
342 pub fn run_core(options: RustdocOptions) -> (clean::Crate, RenderInfo, RenderOptions, Vec<String>) {
343 // Parse, resolve, and typecheck the given crate.
367 let cpath = Some(input.clone());
368 let input = Input::File(input);
370 let intra_link_resolution_failure_name = lint::builtin::INTRA_DOC_LINK_RESOLUTION_FAILURE.name;
371 let warnings_lint_name = lint::builtin::WARNINGS.name;
372 let missing_docs = rustc_lint::builtin::MISSING_DOCS.name;
373 let missing_doc_example = rustc_lint::builtin::MISSING_DOC_CODE_EXAMPLES.name;
374 let private_doc_tests = rustc_lint::builtin::PRIVATE_DOC_TESTS.name;
376 // In addition to those specific lints, we also need to whitelist those given through
377 // command line, otherwise they'll get ignored and we don't want that.
378 let mut whitelisted_lints = vec![warnings_lint_name.to_owned(),
379 intra_link_resolution_failure_name.to_owned(),
380 missing_docs.to_owned(),
381 missing_doc_example.to_owned(),
382 private_doc_tests.to_owned()];
384 whitelisted_lints.extend(lint_opts.iter().map(|(lint, _)| lint).cloned());
387 lint::builtin::HardwiredLints
390 .chain(rustc_lint::SoftLints.get_lints().into_iter())
393 let lint_opts = lints().filter_map(|lint| {
394 if lint.name == warnings_lint_name ||
395 lint.name == intra_link_resolution_failure_name {
398 Some((lint.name_lower(), lint::Allow))
400 }).chain(lint_opts.into_iter()).collect::<Vec<_>>();
402 let lint_caps = lints().filter_map(|lint| {
403 // We don't want to whitelist *all* lints so let's
404 // ignore those ones.
405 if whitelisted_lints.iter().any(|l| &lint.name == l) {
408 Some((lint::LintId::of(lint), lint::Allow))
412 let host_triple = TargetTriple::from_triple(config::host_triple());
413 // plays with error output here!
414 let sessopts = config::Options {
417 crate_types: vec![config::CrateType::Rlib],
418 lint_opts: if !display_warnings {
423 lint_cap: Some(lint_cap.unwrap_or_else(|| lint::Forbid)),
426 target_triple: target.unwrap_or(host_triple),
427 // Ensure that rustdoc works even if rustc is feature-staged
428 unstable_features: UnstableFeatures::Allow,
429 actually_rustdoc: true,
430 debugging_opts: debugging_options.clone(),
437 let config = interface::Config {
439 crate_cfg: config::parse_cfgspecs(cfgs),
445 diagnostic_output: DiagnosticOutput::Default,
447 crate_name: crate_name.clone(),
451 interface::run_compiler_in_existing_thread_pool(config, |compiler| {
452 let sess = compiler.session();
454 // We need to hold on to the complete resolver, so we cause everything to be
455 // cloned for the analysis passes to use. Suboptimal, but necessary in the
456 // current architecture.
457 let resolver = abort_on_err(compiler.expansion(), sess).peek().1.clone();
459 if sess.err_count() > 0 {
460 sess.fatal("Compilation failed, aborting rustdoc");
463 let mut global_ctxt = abort_on_err(compiler.global_ctxt(), sess).take();
465 global_ctxt.enter(|tcx| {
466 tcx.analysis(LOCAL_CRATE).ok();
468 // Abort if there were any errors so far
469 sess.abort_if_errors();
471 let access_levels = tcx.privacy_access_levels(LOCAL_CRATE);
472 // Convert from a HirId set to a DefId set since we don't always have easy access
473 // to the map from defid -> hirid
474 let access_levels = AccessLevels {
475 map: access_levels.map.iter()
476 .map(|(&k, &v)| (tcx.hir().local_def_id_from_hir_id(k), v))
480 let send_trait = if crate_name == Some("core".to_string()) {
481 clean::path_to_def_local(&tcx, &["marker", "Send"])
483 clean::path_to_def(&tcx, &["core", "marker", "Send"])
486 let mut renderinfo = RenderInfo::default();
487 renderinfo.access_levels = access_levels;
489 let ctxt = DocContext {
493 cstore: compiler.cstore().clone(),
494 external_traits: Default::default(),
495 active_extern_traits: Default::default(),
496 renderinfo: RefCell::new(renderinfo),
497 ty_substs: Default::default(),
498 lt_substs: Default::default(),
499 ct_substs: Default::default(),
500 impl_trait_bounds: Default::default(),
501 send_trait: send_trait,
502 fake_def_ids: Default::default(),
503 all_fake_def_ids: Default::default(),
504 generated_synthetics: Default::default(),
505 all_traits: tcx.all_traits(LOCAL_CRATE).to_vec(),
507 debug!("crate: {:?}", tcx.hir().krate());
510 let mut v = RustdocVisitor::new(&ctxt);
511 v.visit(tcx.hir().krate());
515 fn report_deprecated_attr(name: &str, diag: &errors::Handler) {
516 let mut msg = diag.struct_warn(&format!("the `#![doc({})]` attribute is \
517 considered deprecated", name));
518 msg.warn("please see https://github.com/rust-lang/rust/issues/44136");
520 if name == "no_default_passes" {
521 msg.help("you may want to use `#![doc(document_private_items)]`");
527 // Process all of the crate attributes, extracting plugin metadata along
528 // with the passes which we are supposed to run.
529 for attr in krate.module.as_ref().unwrap().attrs.lists("doc") {
530 let diag = ctxt.sess().diagnostic();
532 let name = attr.ident_str();
534 if name == Some("no_default_passes") {
535 report_deprecated_attr("no_default_passes", diag);
536 if default_passes == passes::DefaultPassOption::Default {
537 default_passes = passes::DefaultPassOption::None;
540 } else if let Some(value) = attr.value_str() {
541 let sink = match name {
543 report_deprecated_attr("passes = \"...\"", diag);
547 report_deprecated_attr("plugins = \"...\"", diag);
548 eprintln!("WARNING: #![doc(plugins = \"...\")] no longer functions; \
549 see CVE-2018-1000622");
554 for p in value.as_str().split_whitespace() {
555 sink.push(p.to_string());
559 if attr.is_word() && name == Some("document_private_items") {
560 if default_passes == passes::DefaultPassOption::Default {
561 default_passes = passes::DefaultPassOption::Private;
566 let mut passes: Vec<String> =
567 passes::defaults(default_passes).iter().map(|p| p.to_string()).collect();
568 passes.extend(manual_passes);
570 info!("Executing passes");
572 for pass_name in &passes {
573 match passes::find_pass(pass_name).map(|p| p.pass) {
575 debug!("running pass {}", pass_name);
576 krate = pass(krate, &ctxt);
578 None => error!("unknown pass {}, skipping", *pass_name),
582 ctxt.sess().abort_if_errors();
584 (krate, ctxt.renderinfo.into_inner(), render_options, passes)