1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use rustc_driver::{self, driver, target_features, abort_on_err};
13 use rustc::session::{self, config};
14 use rustc::hir::def_id::{DefId, CrateNum};
15 use rustc::hir::def::Def;
16 use rustc::middle::cstore::CrateStore;
17 use rustc::middle::privacy::AccessLevels;
18 use rustc::ty::{self, TyCtxt, AllArenas};
19 use rustc::hir::map as hir_map;
21 use rustc::session::config::ErrorOutputType;
22 use rustc::util::nodemap::{FxHashMap, FxHashSet};
23 use rustc_resolve as resolve;
24 use rustc_metadata::creader::CrateLoader;
25 use rustc_metadata::cstore::CStore;
26 use rustc_target::spec::TargetTriple;
28 use syntax::ast::NodeId;
30 use syntax::edition::Edition;
31 use syntax::feature_gate::UnstableFeatures;
32 use syntax::json::JsonEmitter;
34 use errors::emitter::{Emitter, EmitterWriter};
36 use std::cell::{RefCell, Cell};
38 use rustc_data_structures::sync::{self, Lrc};
40 use std::path::PathBuf;
42 use visit_ast::RustdocVisitor;
45 use html::render::RenderInfo;
47 pub use rustc::session::config::{Input, CodegenOptions};
48 pub use rustc::session::search_paths::SearchPaths;
50 pub type ExternalPaths = FxHashMap<DefId, (Vec<String>, clean::TypeKind)>;
52 pub struct DocContext<'a, 'tcx: 'a, 'rcx: 'a> {
53 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
54 pub resolver: &'a RefCell<resolve::Resolver<'rcx>>,
55 /// The stack of module NodeIds up till this point
56 pub mod_ids: RefCell<Vec<NodeId>>,
57 pub crate_name: Option<String>,
58 pub cstore: Rc<CrateStore>,
59 pub populated_all_crate_impls: Cell<bool>,
60 // Note that external items for which `doc(hidden)` applies to are shown as
61 // non-reachable while local items aren't. This is because we're reusing
62 // the access levels from crateanalysis.
63 /// Later on moved into `clean::Crate`
64 pub access_levels: RefCell<AccessLevels<DefId>>,
65 /// Later on moved into `html::render::CACHE_KEY`
66 pub renderinfo: RefCell<RenderInfo>,
67 /// Later on moved through `clean::Crate` into `html::render::CACHE_KEY`
68 pub external_traits: RefCell<FxHashMap<DefId, clean::Trait>>,
69 /// Used while populating `external_traits` to ensure we don't process the same trait twice at
71 pub active_extern_traits: RefCell<Vec<DefId>>,
72 // The current set of type and lifetime substitutions,
73 // for expanding type aliases at the HIR level:
75 /// Table type parameter definition -> substituted type
76 pub ty_substs: RefCell<FxHashMap<Def, clean::Type>>,
77 /// Table node id of lifetime parameter definition -> substituted lifetime
78 pub lt_substs: RefCell<FxHashMap<DefId, clean::Lifetime>>,
79 /// Table DefId of `impl Trait` in argument position -> bounds
80 pub impl_trait_bounds: RefCell<FxHashMap<DefId, Vec<clean::TyParamBound>>>,
81 pub send_trait: Option<DefId>,
82 pub fake_def_ids: RefCell<FxHashMap<CrateNum, DefId>>,
83 pub all_fake_def_ids: RefCell<FxHashSet<DefId>>,
84 /// Maps (type_id, trait_id) -> auto trait impl
85 pub generated_synthetics: RefCell<FxHashSet<(DefId, DefId)>>
88 impl<'a, 'tcx, 'rcx> DocContext<'a, 'tcx, 'rcx> {
89 pub fn sess(&self) -> &session::Session {
93 /// Call the closure with the given parameters set as
94 /// the substitutions for a type alias' RHS.
95 pub fn enter_alias<F, R>(&self,
96 ty_substs: FxHashMap<Def, clean::Type>,
97 lt_substs: FxHashMap<DefId, clean::Lifetime>,
99 where F: FnOnce() -> R {
100 let (old_tys, old_lts) =
101 (mem::replace(&mut *self.ty_substs.borrow_mut(), ty_substs),
102 mem::replace(&mut *self.lt_substs.borrow_mut(), lt_substs));
104 *self.ty_substs.borrow_mut() = old_tys;
105 *self.lt_substs.borrow_mut() = old_lts;
110 pub trait DocAccessLevels {
111 fn is_doc_reachable(&self, did: DefId) -> bool;
114 impl DocAccessLevels for AccessLevels<DefId> {
115 fn is_doc_reachable(&self, did: DefId) -> bool {
120 pub fn run_core(search_paths: SearchPaths,
122 externs: config::Externs,
124 triple: Option<TargetTriple>,
125 maybe_sysroot: Option<PathBuf>,
126 allow_warnings: bool,
127 crate_name: Option<String>,
128 force_unstable_if_unmarked: bool,
131 error_format: ErrorOutputType) -> (clean::Crate, RenderInfo)
133 // Parse, resolve, and typecheck the given crate.
135 let cpath = match input {
136 Input::File(ref p) => Some(p.clone()),
140 let warning_lint = lint::builtin::WARNINGS.name_lower();
142 let host_triple = TargetTriple::from_triple(config::host_triple());
143 // plays with error output here!
144 let sessopts = config::Options {
147 crate_types: vec![config::CrateTypeRlib],
148 lint_opts: if !allow_warnings { vec![(warning_lint, lint::Allow)] } else { vec![] },
149 lint_cap: Some(lint::Allow),
152 target_triple: triple.unwrap_or(host_triple),
153 // Ensure that rustdoc works even if rustc is feature-staged
154 unstable_features: UnstableFeatures::Allow,
155 actually_rustdoc: true,
156 debugging_opts: config::DebuggingOptions {
157 force_unstable_if_unmarked,
158 ..config::basic_debugging_options()
162 ..config::basic_options().clone()
164 driver::spawn_thread_pool(sessopts, move |sessopts| {
165 let codemap = Lrc::new(codemap::CodeMap::new(sessopts.file_path_mapping()));
166 let emitter: Box<dyn Emitter + sync::Send> = match error_format {
167 ErrorOutputType::HumanReadable(color_config) => Box::new(
168 EmitterWriter::stderr(
170 Some(codemap.clone()),
172 sessopts.debugging_opts.teach,
173 ).ui_testing(sessopts.debugging_opts.ui_testing)
175 ErrorOutputType::Json(pretty) => Box::new(
180 sessopts.debugging_opts.suggestion_applicability,
181 ).ui_testing(sessopts.debugging_opts.ui_testing)
183 ErrorOutputType::Short(color_config) => Box::new(
184 EmitterWriter::stderr(color_config, Some(codemap.clone()), true, false)
188 let diagnostic_handler = errors::Handler::with_emitter_and_flags(
190 errors::HandlerFlags {
191 can_emit_warnings: true,
192 treat_err_as_bug: false,
193 external_macro_backtrace: false,
198 let mut sess = session::build_session_(
199 sessopts, cpath, diagnostic_handler, codemap,
201 let trans = rustc_driver::get_trans(&sess);
202 let cstore = Rc::new(CStore::new(trans.metadata_loader()));
203 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
205 let mut cfg = config::build_configuration(&sess, config::parse_cfgspecs(cfgs));
206 target_features::add_configuration(&mut cfg, &sess, &*trans);
207 sess.parse_sess.config = cfg;
209 let control = &driver::CompileController::basic();
211 let krate = panictry!(driver::phase_1_parse_input(control, &sess, &input));
213 let name = ::rustc_trans_utils::link::find_crate_name(Some(&sess), &krate.attrs, &input);
215 let mut crate_loader = CrateLoader::new(&sess, &cstore, &name);
217 let resolver_arenas = resolve::Resolver::arenas();
218 let result = driver::phase_2_configure_and_expand_inner(&sess,
224 resolve::MakeGlobMap::No,
228 let driver::InnerExpansionResult {
232 } = abort_on_err(result, &sess);
234 // We need to hold on to the complete resolver, so we clone everything
235 // for the analysis passes to use. Suboptimal, but necessary in the
236 // current architecture.
237 let defs = resolver.definitions.clone();
238 let resolutions = ty::Resolutions {
239 freevars: resolver.freevars.clone(),
240 export_map: resolver.export_map.clone(),
241 trait_map: resolver.trait_map.clone(),
242 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports.clone(),
243 maybe_unused_extern_crates: resolver.maybe_unused_extern_crates.clone(),
245 let analysis = ty::CrateAnalysis {
246 access_levels: Lrc::new(AccessLevels::default()),
247 name: name.to_string(),
248 glob_map: if resolver.make_glob_map { Some(resolver.glob_map.clone()) } else { None },
251 let arenas = AllArenas::new();
252 let hir_map = hir_map::map_crate(&sess, &*cstore, &mut hir_forest, &defs);
253 let output_filenames = driver::build_output_filenames(&input,
259 let resolver = RefCell::new(resolver);
261 abort_on_err(driver::phase_3_run_analysis_passes(&*trans,
271 |tcx, analysis, _, result| {
272 if let Err(_) = result {
273 sess.fatal("Compilation failed, aborting rustdoc");
276 let ty::CrateAnalysis { access_levels, .. } = analysis;
278 // Convert from a NodeId set to a DefId set since we don't always have easy access
279 // to the map from defid -> nodeid
280 let access_levels = AccessLevels {
281 map: access_levels.map.iter()
282 .map(|(&k, &v)| (tcx.hir.local_def_id(k), v))
286 let send_trait = if crate_name == Some("core".to_string()) {
287 clean::get_trait_def_id(&tcx, &["marker", "Send"], true)
289 clean::get_trait_def_id(&tcx, &["core", "marker", "Send"], false)
292 let ctxt = DocContext {
296 cstore: cstore.clone(),
297 populated_all_crate_impls: Cell::new(false),
298 access_levels: RefCell::new(access_levels),
299 external_traits: Default::default(),
300 active_extern_traits: Default::default(),
301 renderinfo: Default::default(),
302 ty_substs: Default::default(),
303 lt_substs: Default::default(),
304 impl_trait_bounds: Default::default(),
305 mod_ids: Default::default(),
306 send_trait: send_trait,
307 fake_def_ids: RefCell::new(FxHashMap()),
308 all_fake_def_ids: RefCell::new(FxHashSet()),
309 generated_synthetics: RefCell::new(FxHashSet()),
311 debug!("crate: {:?}", tcx.hir.krate());
314 let mut v = RustdocVisitor::new(&*cstore, &ctxt);
315 v.visit(tcx.hir.krate());
319 (krate, ctxt.renderinfo.into_inner())