2 use rustc_driver::{self, driver, target_features, abort_on_err};
3 use rustc::session::{self, config};
4 use rustc::hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CrateNum, LOCAL_CRATE};
5 use rustc::hir::def::Def;
6 use rustc::hir::{self, HirVec};
7 use rustc::middle::cstore::CrateStore;
8 use rustc::middle::privacy::AccessLevels;
9 use rustc::ty::{self, TyCtxt, AllArenas};
10 use rustc::hir::map as hir_map;
11 use rustc::lint::{self, LintPass};
12 use rustc::session::config::ErrorOutputType;
13 use rustc::util::nodemap::{FxHashMap, FxHashSet};
14 use rustc_resolve as resolve;
15 use rustc_metadata::creader::CrateLoader;
16 use rustc_metadata::cstore::CStore;
17 use rustc_target::spec::TargetTriple;
19 use syntax::ast::{self, Ident, NodeId};
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;
26 use errors::{self, FatalError};
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 visit_ast::RustdocVisitor;
37 use config::{Options as RustdocOptions, RenderOptions};
39 use clean::{get_path_for_type, Clean, MAX_DEF_ID, AttributesExt};
40 use html::render::RenderInfo;
43 pub use rustc::session::config::{Input, Options, CodegenOptions};
44 pub use rustc::session::search_paths::SearchPath;
46 pub type ExternalPaths = FxHashMap<DefId, (Vec<String>, clean::TypeKind)>;
48 pub struct DocContext<'a, 'tcx: 'a, 'rcx: 'a> {
49 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
50 pub resolver: &'a RefCell<resolve::Resolver<'rcx>>,
51 /// The stack of module NodeIds up till this point
52 pub crate_name: Option<String>,
53 pub cstore: Rc<CStore>,
54 /// Later on moved into `html::render::CACHE_KEY`
55 pub renderinfo: RefCell<RenderInfo>,
56 /// Later on moved through `clean::Crate` into `html::render::CACHE_KEY`
57 pub external_traits: Arc<ReentrantMutex<RefCell<FxHashMap<DefId, clean::Trait>>>>,
58 /// Used while populating `external_traits` to ensure we don't process the same trait twice at
60 pub active_extern_traits: RefCell<Vec<DefId>>,
61 // The current set of type and lifetime substitutions,
62 // for expanding type aliases at the HIR level:
64 /// Table type parameter definition -> substituted type
65 pub ty_substs: RefCell<FxHashMap<Def, clean::Type>>,
66 /// Table `NodeId` of lifetime parameter definition -> substituted lifetime
67 pub lt_substs: RefCell<FxHashMap<DefId, clean::Lifetime>>,
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 /// Maps (type_id, trait_id) -> auto trait impl
74 pub generated_synthetics: RefCell<FxHashSet<(DefId, DefId)>>,
75 pub all_traits: Vec<DefId>,
78 impl<'a, 'tcx, 'rcx> DocContext<'a, 'tcx, 'rcx> {
79 pub fn sess(&self) -> &session::Session {
83 /// Call the closure with the given parameters set as
84 /// the substitutions for a type alias' RHS.
85 pub fn enter_alias<F, R>(&self,
86 ty_substs: FxHashMap<Def, clean::Type>,
87 lt_substs: FxHashMap<DefId, clean::Lifetime>,
89 where F: FnOnce() -> R {
90 let (old_tys, old_lts) =
91 (mem::replace(&mut *self.ty_substs.borrow_mut(), ty_substs),
92 mem::replace(&mut *self.lt_substs.borrow_mut(), lt_substs));
94 *self.ty_substs.borrow_mut() = old_tys;
95 *self.lt_substs.borrow_mut() = old_lts;
99 // This is an ugly hack, but it's the simplest way to handle synthetic impls without greatly
100 // refactoring either librustdoc or librustc. In particular, allowing new DefIds to be
101 // registered after the AST is constructed would require storing the defid mapping in a
102 // RefCell, decreasing the performance for normal compilation for very little gain.
104 // Instead, we construct 'fake' def ids, which start immediately after the last DefId in
105 // DefIndexAddressSpace::Low. In the Debug impl for clean::Item, we explicitly check for fake
106 // def ids, as we'll end up with a panic if we use the DefId Debug impl for fake DefIds
107 pub fn next_def_id(&self, crate_num: CrateNum) -> DefId {
109 let next_id = if crate_num == LOCAL_CRATE {
114 .next_id(DefIndexAddressSpace::Low)
117 .def_path_table(crate_num)
118 .next_id(DefIndexAddressSpace::Low)
127 let mut fake_ids = self.fake_def_ids.borrow_mut();
129 let def_id = fake_ids.entry(crate_num).or_insert(start_def_id).clone();
134 index: DefIndex::from_array_index(
135 def_id.index.as_array_index() + 1,
136 def_id.index.address_space(),
141 MAX_DEF_ID.with(|m| {
143 .entry(def_id.krate.clone())
144 .or_insert(start_def_id);
147 self.all_fake_def_ids.borrow_mut().insert(def_id);
152 /// Like the function of the same name on the HIR map, but skips calling it on fake DefIds.
153 /// (This avoids a slice-index-out-of-bounds panic.)
154 pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
155 if self.all_fake_def_ids.borrow().contains(&def_id) {
158 self.tcx.hir().as_local_node_id(def_id)
162 pub fn get_real_ty<F>(&self,
165 real_name: &Option<Ident>,
166 generics: &ty::Generics,
168 where F: Fn(DefId) -> Def {
169 let path = get_path_for_type(self.tcx, def_id, def_ctor);
170 let mut segments = path.segments.into_vec();
171 let last = segments.pop().expect("segments were empty");
173 segments.push(hir::PathSegment::new(
174 real_name.unwrap_or(last.ident),
178 self.generics_to_path_params(generics.clone()),
182 let new_path = hir::Path {
185 segments: HirVec::from_vec(segments),
189 id: ast::DUMMY_NODE_ID,
190 node: hir::TyKind::Path(hir::QPath::Resolved(None, P(new_path))),
192 hir_id: hir::DUMMY_HIR_ID,
196 pub fn generics_to_path_params(&self, generics: ty::Generics) -> hir::GenericArgs {
197 let mut args = vec![];
199 for param in generics.params.iter() {
201 ty::GenericParamDefKind::Lifetime => {
202 let name = if param.name == "" {
203 hir::ParamName::Plain(keywords::StaticLifetime.ident())
205 hir::ParamName::Plain(ast::Ident::from_interned_str(param.name))
208 args.push(hir::GenericArg::Lifetime(hir::Lifetime {
209 id: ast::DUMMY_NODE_ID,
210 hir_id: hir::DUMMY_HIR_ID,
212 name: hir::LifetimeName::Param(name),
215 ty::GenericParamDefKind::Type {..} => {
216 args.push(hir::GenericArg::Type(self.ty_param_to_ty(param.clone())));
222 args: HirVec::from_vec(args),
223 bindings: HirVec::new(),
224 parenthesized: false,
228 pub fn ty_param_to_ty(&self, param: ty::GenericParamDef) -> hir::Ty {
229 debug!("ty_param_to_ty({:?}) {:?}", param, param.def_id);
231 id: ast::DUMMY_NODE_ID,
232 node: hir::TyKind::Path(hir::QPath::Resolved(
236 def: Def::TyParam(param.def_id),
237 segments: HirVec::from_vec(vec![
238 hir::PathSegment::from_ident(Ident::from_interned_str(param.name))
243 hir_id: hir::DUMMY_HIR_ID,
248 pub trait DocAccessLevels {
249 fn is_doc_reachable(&self, did: DefId) -> bool;
252 impl DocAccessLevels for AccessLevels<DefId> {
253 fn is_doc_reachable(&self, did: DefId) -> bool {
258 /// Creates a new diagnostic `Handler` that can be used to emit warnings and errors.
260 /// If the given `error_format` is `ErrorOutputType::Json` and no `SourceMap` is given, a new one
261 /// will be created for the handler.
262 pub fn new_handler(error_format: ErrorOutputType,
263 source_map: Option<Lrc<source_map::SourceMap>>,
264 treat_err_as_bug: bool,
266 ) -> errors::Handler {
267 // rustdoc doesn't override (or allow to override) anything from this that is relevant here, so
268 // stick to the defaults
269 let sessopts = Options::default();
270 let emitter: Box<dyn Emitter + sync::Send> = match error_format {
271 ErrorOutputType::HumanReadable(color_config) => Box::new(
272 EmitterWriter::stderr(
274 source_map.map(|cm| cm as _),
276 sessopts.debugging_opts.teach,
277 ).ui_testing(ui_testing)
279 ErrorOutputType::Json(pretty) => {
280 let source_map = source_map.unwrap_or_else(
281 || Lrc::new(source_map::SourceMap::new(sessopts.file_path_mapping())));
287 ).ui_testing(ui_testing)
290 ErrorOutputType::Short(color_config) => Box::new(
291 EmitterWriter::stderr(
293 source_map.map(|cm| cm as _),
299 errors::Handler::with_emitter_and_flags(
301 errors::HandlerFlags {
302 can_emit_warnings: true,
304 report_delayed_bugs: false,
305 external_macro_backtrace: false,
311 pub fn run_core(options: RustdocOptions) -> (clean::Crate, RenderInfo, RenderOptions, Vec<String>) {
312 // Parse, resolve, and typecheck the given crate.
336 let cpath = Some(input.clone());
337 let input = Input::File(input);
339 let intra_link_resolution_failure_name = lint::builtin::INTRA_DOC_LINK_RESOLUTION_FAILURE.name;
340 let warnings_lint_name = lint::builtin::WARNINGS.name;
341 let missing_docs = rustc_lint::builtin::MISSING_DOCS.name;
342 let missing_doc_example = rustc_lint::builtin::MISSING_DOC_CODE_EXAMPLES.name;
343 let private_doc_tests = rustc_lint::builtin::PRIVATE_DOC_TESTS.name;
345 // In addition to those specific lints, we also need to whitelist those given through
346 // command line, otherwise they'll get ignored and we don't want that.
347 let mut whitelisted_lints = vec![warnings_lint_name.to_owned(),
348 intra_link_resolution_failure_name.to_owned(),
349 missing_docs.to_owned(),
350 missing_doc_example.to_owned(),
351 private_doc_tests.to_owned()];
353 whitelisted_lints.extend(lint_opts.iter().map(|(lint, _)| lint).cloned());
355 let lints = lint::builtin::HardwiredLints.get_lints()
357 .chain(rustc_lint::SoftLints.get_lints().into_iter())
359 if lint.name == warnings_lint_name ||
360 lint.name == intra_link_resolution_failure_name {
363 Some((lint.name_lower(), lint::Allow))
366 .chain(lint_opts.into_iter())
367 .collect::<Vec<_>>();
369 let host_triple = TargetTriple::from_triple(config::host_triple());
370 // plays with error output here!
371 let sessopts = config::Options {
374 crate_types: vec![config::CrateType::Rlib],
375 lint_opts: if !display_warnings {
380 lint_cap: Some(lint_cap.unwrap_or_else(|| lint::Forbid)),
383 target_triple: target.unwrap_or(host_triple),
384 // Ensure that rustdoc works even if rustc is feature-staged
385 unstable_features: UnstableFeatures::Allow,
386 actually_rustdoc: true,
387 debugging_opts: debugging_options.clone(),
393 driver::spawn_thread_pool(sessopts, move |sessopts| {
394 let source_map = Lrc::new(source_map::SourceMap::new(sessopts.file_path_mapping()));
395 let diagnostic_handler = new_handler(error_format,
396 Some(source_map.clone()),
397 debugging_options.treat_err_as_bug,
398 debugging_options.ui_testing);
400 let mut sess = session::build_session_(
401 sessopts, cpath, diagnostic_handler, source_map,
404 lint::builtin::HardwiredLints.get_lints()
406 .chain(rustc_lint::SoftLints.get_lints().into_iter())
408 // We don't want to whitelist *all* lints so let's
409 // ignore those ones.
410 if whitelisted_lints.iter().any(|l| &lint.name == l) {
417 sess.driver_lint_caps.insert(lint::LintId::of(l),
421 let codegen_backend = rustc_driver::get_codegen_backend(&sess);
422 let cstore = Rc::new(CStore::new(codegen_backend.metadata_loader()));
423 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
425 let mut cfg = config::build_configuration(&sess, config::parse_cfgspecs(cfgs));
426 target_features::add_configuration(&mut cfg, &sess, &*codegen_backend);
427 sess.parse_sess.config = cfg;
429 let control = &driver::CompileController::basic();
431 let krate = match driver::phase_1_parse_input(control, &sess, &input) {
439 let name = match crate_name {
440 Some(ref crate_name) => crate_name.clone(),
441 None => ::rustc_codegen_utils::link::find_crate_name(Some(&sess), &krate.attrs, &input),
444 let mut crate_loader = CrateLoader::new(&sess, &cstore, &name);
446 let resolver_arenas = resolve::Resolver::arenas();
447 let result = driver::phase_2_configure_and_expand_inner(&sess,
456 let driver::InnerExpansionResult {
460 } = abort_on_err(result, &sess);
462 // We need to hold on to the complete resolver, so we clone everything
463 // for the analysis passes to use. Suboptimal, but necessary in the
464 // current architecture.
465 let defs = resolver.definitions.clone();
466 let resolutions = ty::Resolutions {
467 freevars: resolver.freevars.clone(),
468 export_map: resolver.export_map.clone(),
469 trait_map: resolver.trait_map.clone(),
470 glob_map: resolver.glob_map.clone(),
471 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports.clone(),
472 maybe_unused_extern_crates: resolver.maybe_unused_extern_crates.clone(),
473 extern_prelude: resolver.extern_prelude.iter().map(|(ident, entry)| {
474 (ident.name, entry.introduced_by_item)
478 let mut arenas = AllArenas::new();
479 let hir_map = hir_map::map_crate(&sess, &*cstore, &mut hir_forest, &defs);
480 let output_filenames = driver::build_output_filenames(&input,
486 let resolver = RefCell::new(resolver);
487 abort_on_err(driver::phase_3_run_analysis_passes(&*codegen_backend,
498 sess.fatal("Compilation failed, aborting rustdoc");
501 let access_levels = tcx.privacy_access_levels(LOCAL_CRATE);
503 // Convert from a NodeId set to a DefId set since we don't always have easy access
504 // to the map from defid -> nodeid
505 let access_levels = AccessLevels {
506 map: access_levels.map.iter()
507 .map(|(&k, &v)| (tcx.hir().local_def_id(k), v))
511 let send_trait = if crate_name == Some("core".to_string()) {
512 clean::path_to_def_local(&tcx, &["marker", "Send"])
514 clean::path_to_def(&tcx, &["core", "marker", "Send"])
517 let mut renderinfo = RenderInfo::default();
518 renderinfo.access_levels = access_levels;
520 let ctxt = DocContext {
524 cstore: cstore.clone(),
525 external_traits: Default::default(),
526 active_extern_traits: Default::default(),
527 renderinfo: RefCell::new(renderinfo),
528 ty_substs: Default::default(),
529 lt_substs: Default::default(),
530 impl_trait_bounds: Default::default(),
531 send_trait: send_trait,
532 fake_def_ids: Default::default(),
533 all_fake_def_ids: Default::default(),
534 generated_synthetics: Default::default(),
535 all_traits: tcx.all_traits(LOCAL_CRATE).to_vec(),
537 debug!("crate: {:?}", tcx.hir().krate());
540 let mut v = RustdocVisitor::new(&ctxt);
541 v.visit(tcx.hir().krate());
545 fn report_deprecated_attr(name: &str, diag: &errors::Handler) {
546 let mut msg = diag.struct_warn(&format!("the `#![doc({})]` attribute is \
547 considered deprecated", name));
548 msg.warn("please see https://github.com/rust-lang/rust/issues/44136");
550 if name == "no_default_passes" {
551 msg.help("you may want to use `#![doc(document_private_items)]`");
557 // Process all of the crate attributes, extracting plugin metadata along
558 // with the passes which we are supposed to run.
559 for attr in krate.module.as_ref().unwrap().attrs.lists("doc") {
560 let diag = ctxt.sess().diagnostic();
562 let name = attr.name().map(|s| s.as_str());
563 let name = name.as_ref().map(|s| &s[..]);
565 if name == Some("no_default_passes") {
566 report_deprecated_attr("no_default_passes", diag);
567 if default_passes == passes::DefaultPassOption::Default {
568 default_passes = passes::DefaultPassOption::None;
571 } else if let Some(value) = attr.value_str() {
572 let sink = match name {
574 report_deprecated_attr("passes = \"...\"", diag);
578 report_deprecated_attr("plugins = \"...\"", diag);
579 eprintln!("WARNING: #![doc(plugins = \"...\")] no longer functions; \
580 see CVE-2018-1000622");
585 for p in value.as_str().split_whitespace() {
586 sink.push(p.to_string());
590 if attr.is_word() && name == Some("document_private_items") {
591 if default_passes == passes::DefaultPassOption::Default {
592 default_passes = passes::DefaultPassOption::Private;
597 let mut passes: Vec<String> =
598 passes::defaults(default_passes).iter().map(|p| p.to_string()).collect();
599 passes.extend(manual_passes);
601 for pass in &passes {
602 // the "unknown pass" error will be reported when late passes are run
603 if let Some(pass) = passes::find_pass(pass).and_then(|p| p.early_fn()) {
604 krate = pass(krate, &ctxt);
608 ctxt.sess().abort_if_errors();
610 (krate, ctxt.renderinfo.into_inner(), render_options, passes)