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;
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,
128 edition: Edition) -> (clean::Crate, RenderInfo)
130 // Parse, resolve, and typecheck the given crate.
132 let cpath = match input {
133 Input::File(ref p) => Some(p.clone()),
137 let warning_lint = lint::builtin::WARNINGS.name_lower();
139 let host_triple = TargetTriple::from_triple(config::host_triple());
140 let sessopts = config::Options {
143 crate_types: vec![config::CrateTypeRlib],
144 lint_opts: if !allow_warnings { vec![(warning_lint, lint::Allow)] } else { vec![] },
145 lint_cap: Some(lint::Allow),
147 target_triple: triple.unwrap_or(host_triple),
148 // Ensure that rustdoc works even if rustc is feature-staged
149 unstable_features: UnstableFeatures::Allow,
150 actually_rustdoc: true,
151 debugging_opts: config::DebuggingOptions {
152 force_unstable_if_unmarked,
154 ..config::basic_debugging_options()
156 ..config::basic_options().clone()
159 let codemap = Lrc::new(codemap::CodeMap::new(sessopts.file_path_mapping()));
160 let diagnostic_handler = errors::Handler::with_tty_emitter(ColorConfig::Auto,
163 Some(codemap.clone()));
165 let mut sess = session::build_session_(
166 sessopts, cpath, diagnostic_handler, codemap,
168 let trans = rustc_driver::get_trans(&sess);
169 let cstore = Rc::new(CStore::new(trans.metadata_loader()));
170 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
172 let mut cfg = config::build_configuration(&sess, config::parse_cfgspecs(cfgs));
173 target_features::add_configuration(&mut cfg, &sess, &*trans);
174 sess.parse_sess.config = cfg;
176 let control = &driver::CompileController::basic();
178 let krate = panictry!(driver::phase_1_parse_input(control, &sess, &input));
180 let name = ::rustc_trans_utils::link::find_crate_name(Some(&sess), &krate.attrs, &input);
182 let mut crate_loader = CrateLoader::new(&sess, &cstore, &name);
184 let resolver_arenas = resolve::Resolver::arenas();
185 let result = driver::phase_2_configure_and_expand_inner(&sess,
191 resolve::MakeGlobMap::No,
195 let driver::InnerExpansionResult {
199 } = abort_on_err(result, &sess);
201 // We need to hold on to the complete resolver, so we clone everything
202 // for the analysis passes to use. Suboptimal, but necessary in the
203 // current architecture.
204 let defs = resolver.definitions.clone();
205 let resolutions = ty::Resolutions {
206 freevars: resolver.freevars.clone(),
207 export_map: resolver.export_map.clone(),
208 trait_map: resolver.trait_map.clone(),
209 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports.clone(),
210 maybe_unused_extern_crates: resolver.maybe_unused_extern_crates.clone(),
212 let analysis = ty::CrateAnalysis {
213 access_levels: Lrc::new(AccessLevels::default()),
214 name: name.to_string(),
215 glob_map: if resolver.make_glob_map { Some(resolver.glob_map.clone()) } else { None },
218 let arenas = AllArenas::new();
219 let hir_map = hir_map::map_crate(&sess, &*cstore, &mut hir_forest, &defs);
220 let output_filenames = driver::build_output_filenames(&input,
226 let resolver = RefCell::new(resolver);
228 abort_on_err(driver::phase_3_run_analysis_passes(&*trans,
238 |tcx, analysis, _, result| {
239 if let Err(_) = result {
240 sess.fatal("Compilation failed, aborting rustdoc");
243 let ty::CrateAnalysis { access_levels, .. } = analysis;
245 // Convert from a NodeId set to a DefId set since we don't always have easy access
246 // to the map from defid -> nodeid
247 let access_levels = AccessLevels {
248 map: access_levels.map.iter()
249 .map(|(&k, &v)| (tcx.hir.local_def_id(k), v))
253 let send_trait = if crate_name == Some("core".to_string()) {
254 clean::get_trait_def_id(&tcx, &["marker", "Send"], true)
256 clean::get_trait_def_id(&tcx, &["core", "marker", "Send"], false)
259 let ctxt = DocContext {
263 cstore: cstore.clone(),
264 populated_all_crate_impls: Cell::new(false),
265 access_levels: RefCell::new(access_levels),
266 external_traits: Default::default(),
267 active_extern_traits: Default::default(),
268 renderinfo: Default::default(),
269 ty_substs: Default::default(),
270 lt_substs: Default::default(),
271 impl_trait_bounds: Default::default(),
272 mod_ids: Default::default(),
273 send_trait: send_trait,
274 fake_def_ids: RefCell::new(FxHashMap()),
275 all_fake_def_ids: RefCell::new(FxHashSet()),
276 generated_synthetics: RefCell::new(FxHashSet()),
278 debug!("crate: {:?}", tcx.hir.krate());
281 let mut v = RustdocVisitor::new(&*cstore, &ctxt);
282 v.visit(tcx.hir.krate());
286 (krate, ctxt.renderinfo.into_inner())