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::util::nodemap::{FxHashMap, FxHashSet};
22 use rustc_resolve as resolve;
23 use rustc_metadata::creader::CrateLoader;
24 use rustc_metadata::cstore::CStore;
25 use rustc_back::target::TargetTriple;
27 use syntax::ast::NodeId;
29 use syntax::edition::Edition;
30 use syntax::feature_gate::UnstableFeatures;
32 use errors::emitter::ColorConfig;
34 use std::cell::{RefCell, Cell};
36 use rustc_data_structures::sync::Lrc;
38 use std::path::PathBuf;
40 use visit_ast::RustdocVisitor;
43 use html::render::RenderInfo;
45 pub use rustc::session::config::{Input, CodegenOptions};
46 pub use rustc::session::search_paths::SearchPaths;
48 pub type ExternalPaths = FxHashMap<DefId, (Vec<String>, clean::TypeKind)>;
50 pub struct DocContext<'a, 'tcx: 'a, 'rcx: 'a> {
51 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
52 pub resolver: &'a RefCell<resolve::Resolver<'rcx>>,
53 /// The stack of module NodeIds up till this point
54 pub mod_ids: RefCell<Vec<NodeId>>,
55 pub crate_name: Option<String>,
56 pub cstore: Rc<CrateStore>,
57 pub populated_all_crate_impls: Cell<bool>,
58 // Note that external items for which `doc(hidden)` applies to are shown as
59 // non-reachable while local items aren't. This is because we're reusing
60 // the access levels from crateanalysis.
61 /// Later on moved into `clean::Crate`
62 pub access_levels: RefCell<AccessLevels<DefId>>,
63 /// Later on moved into `html::render::CACHE_KEY`
64 pub renderinfo: RefCell<RenderInfo>,
65 /// Later on moved through `clean::Crate` into `html::render::CACHE_KEY`
66 pub external_traits: RefCell<FxHashMap<DefId, clean::Trait>>,
67 /// Used while populating `external_traits` to ensure we don't process the same trait twice at
69 pub active_extern_traits: RefCell<Vec<DefId>>,
70 // The current set of type and lifetime substitutions,
71 // for expanding type aliases at the HIR level:
73 /// Table type parameter definition -> substituted type
74 pub ty_substs: RefCell<FxHashMap<Def, clean::Type>>,
75 /// Table node id of lifetime parameter definition -> substituted lifetime
76 pub lt_substs: RefCell<FxHashMap<DefId, clean::Lifetime>>,
77 /// Table DefId of `impl Trait` in argument position -> bounds
78 pub impl_trait_bounds: RefCell<FxHashMap<DefId, Vec<clean::TyParamBound>>>,
79 pub send_trait: Option<DefId>,
80 pub fake_def_ids: RefCell<FxHashMap<CrateNum, DefId>>,
81 pub all_fake_def_ids: RefCell<FxHashSet<DefId>>,
82 /// Maps (type_id, trait_id) -> auto trait impl
83 pub generated_synthetics: RefCell<FxHashSet<(DefId, DefId)>>
86 impl<'a, 'tcx, 'rcx> DocContext<'a, 'tcx, 'rcx> {
87 pub fn sess(&self) -> &session::Session {
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<Def, clean::Type>,
95 lt_substs: FxHashMap<DefId, clean::Lifetime>,
97 where F: FnOnce() -> R {
98 let (old_tys, old_lts) =
99 (mem::replace(&mut *self.ty_substs.borrow_mut(), ty_substs),
100 mem::replace(&mut *self.lt_substs.borrow_mut(), lt_substs));
102 *self.ty_substs.borrow_mut() = old_tys;
103 *self.lt_substs.borrow_mut() = old_lts;
108 pub trait DocAccessLevels {
109 fn is_doc_reachable(&self, did: DefId) -> bool;
112 impl DocAccessLevels for AccessLevels<DefId> {
113 fn is_doc_reachable(&self, did: DefId) -> bool {
119 pub fn run_core(search_paths: SearchPaths,
121 externs: config::Externs,
123 triple: Option<TargetTriple>,
124 maybe_sysroot: Option<PathBuf>,
125 allow_warnings: bool,
126 crate_name: Option<String>,
127 force_unstable_if_unmarked: bool,
129 cg: CodegenOptions) -> (clean::Crate, RenderInfo)
131 // Parse, resolve, and typecheck the given crate.
133 let cpath = match input {
134 Input::File(ref p) => Some(p.clone()),
138 let warning_lint = lint::builtin::WARNINGS.name_lower();
140 let host_triple = TargetTriple::from_triple(config::host_triple());
141 let sessopts = config::Options {
144 crate_types: vec![config::CrateTypeRlib],
145 lint_opts: if !allow_warnings { vec![(warning_lint, lint::Allow)] } else { vec![] },
146 lint_cap: Some(lint::Allow),
149 target_triple: triple.unwrap_or(host_triple),
150 // Ensure that rustdoc works even if rustc is feature-staged
151 unstable_features: UnstableFeatures::Allow,
152 actually_rustdoc: true,
153 debugging_opts: config::DebuggingOptions {
154 force_unstable_if_unmarked,
156 ..config::basic_debugging_options()
158 ..config::basic_options().clone()
161 let codemap = Lrc::new(codemap::CodeMap::new(sessopts.file_path_mapping()));
162 let diagnostic_handler = errors::Handler::with_tty_emitter(ColorConfig::Auto,
165 Some(codemap.clone()));
167 let mut sess = session::build_session_(
168 sessopts, cpath, diagnostic_handler, codemap,
170 let trans = rustc_driver::get_trans(&sess);
171 let cstore = Rc::new(CStore::new(trans.metadata_loader()));
172 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
174 let mut cfg = config::build_configuration(&sess, config::parse_cfgspecs(cfgs));
175 target_features::add_configuration(&mut cfg, &sess, &*trans);
176 sess.parse_sess.config = cfg;
178 let control = &driver::CompileController::basic();
180 let krate = panictry!(driver::phase_1_parse_input(control, &sess, &input));
182 let name = ::rustc_trans_utils::link::find_crate_name(Some(&sess), &krate.attrs, &input);
184 let mut crate_loader = CrateLoader::new(&sess, &cstore, &name);
186 let resolver_arenas = resolve::Resolver::arenas();
187 let result = driver::phase_2_configure_and_expand_inner(&sess,
193 resolve::MakeGlobMap::No,
197 let driver::InnerExpansionResult {
201 } = abort_on_err(result, &sess);
203 // We need to hold on to the complete resolver, so we clone everything
204 // for the analysis passes to use. Suboptimal, but necessary in the
205 // current architecture.
206 let defs = resolver.definitions.clone();
207 let resolutions = ty::Resolutions {
208 freevars: resolver.freevars.clone(),
209 export_map: resolver.export_map.clone(),
210 trait_map: resolver.trait_map.clone(),
211 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports.clone(),
212 maybe_unused_extern_crates: resolver.maybe_unused_extern_crates.clone(),
214 let analysis = ty::CrateAnalysis {
215 access_levels: Lrc::new(AccessLevels::default()),
216 name: name.to_string(),
217 glob_map: if resolver.make_glob_map { Some(resolver.glob_map.clone()) } else { None },
220 let arenas = AllArenas::new();
221 let hir_map = hir_map::map_crate(&sess, &*cstore, &mut hir_forest, &defs);
222 let output_filenames = driver::build_output_filenames(&input,
228 let resolver = RefCell::new(resolver);
230 abort_on_err(driver::phase_3_run_analysis_passes(&*trans,
240 |tcx, analysis, _, result| {
241 if let Err(_) = result {
242 sess.fatal("Compilation failed, aborting rustdoc");
245 let ty::CrateAnalysis { access_levels, .. } = analysis;
247 // Convert from a NodeId set to a DefId set since we don't always have easy access
248 // to the map from defid -> nodeid
249 let access_levels = AccessLevels {
250 map: access_levels.map.iter()
251 .map(|(&k, &v)| (tcx.hir.local_def_id(k), v))
255 let send_trait = if crate_name == Some("core".to_string()) {
256 clean::get_trait_def_id(&tcx, &["marker", "Send"], true)
258 clean::get_trait_def_id(&tcx, &["core", "marker", "Send"], false)
261 let ctxt = DocContext {
265 cstore: cstore.clone(),
266 populated_all_crate_impls: Cell::new(false),
267 access_levels: RefCell::new(access_levels),
268 external_traits: Default::default(),
269 active_extern_traits: Default::default(),
270 renderinfo: Default::default(),
271 ty_substs: Default::default(),
272 lt_substs: Default::default(),
273 impl_trait_bounds: Default::default(),
274 mod_ids: Default::default(),
275 send_trait: send_trait,
276 fake_def_ids: RefCell::new(FxHashMap()),
277 all_fake_def_ids: RefCell::new(FxHashSet()),
278 generated_synthetics: RefCell::new(FxHashSet()),
280 debug!("crate: {:?}", tcx.hir.krate());
283 let mut v = RustdocVisitor::new(&*cstore, &ctxt);
284 v.visit(tcx.hir.krate());
288 (krate, ctxt.renderinfo.into_inner())