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::{driver, target_features, abort_on_err};
13 use rustc_driver::pretty::ReplaceBodyWithLoop;
14 use rustc::dep_graph::DepGraph;
15 use rustc::session::{self, config};
16 use rustc::hir::def_id::DefId;
17 use rustc::hir::def::Def;
18 use rustc::middle::privacy::AccessLevels;
19 use rustc::ty::{self, TyCtxt, GlobalArenas};
20 use rustc::hir::map as hir_map;
22 use rustc::util::nodemap::FxHashMap;
24 use rustc_trans::back::link;
25 use rustc_resolve as resolve;
26 use rustc_metadata::cstore::CStore;
28 use syntax::{ast, codemap};
29 use syntax::feature_gate::UnstableFeatures;
30 use syntax::fold::Folder;
32 use errors::emitter::ColorConfig;
34 use std::cell::{RefCell, Cell};
37 use std::path::PathBuf;
39 use visit_ast::RustdocVisitor;
42 use html::render::RenderInfo;
43 use arena::DroplessArena;
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> {
51 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
52 pub populated_all_crate_impls: Cell<bool>,
53 // Note that external items for which `doc(hidden)` applies to are shown as
54 // non-reachable while local items aren't. This is because we're reusing
55 // the access levels from crateanalysis.
56 /// Later on moved into `clean::Crate`
57 pub access_levels: RefCell<AccessLevels<DefId>>,
58 /// Later on moved into `html::render::CACHE_KEY`
59 pub renderinfo: RefCell<RenderInfo>,
60 /// Later on moved through `clean::Crate` into `html::render::CACHE_KEY`
61 pub external_traits: RefCell<FxHashMap<DefId, clean::Trait>>,
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 node id of lifetime parameter definition -> substituted lifetime
69 pub lt_substs: RefCell<FxHashMap<ast::NodeId, clean::Lifetime>>,
72 impl<'a, 'tcx> DocContext<'a, 'tcx> {
73 pub fn sess(&self) -> &session::Session {
77 /// Call the closure with the given parameters set as
78 /// the substitutions for a type alias' RHS.
79 pub fn enter_alias<F, R>(&self,
80 ty_substs: FxHashMap<Def, clean::Type>,
81 lt_substs: FxHashMap<ast::NodeId, clean::Lifetime>,
83 where F: FnOnce() -> R {
84 let (old_tys, old_lts) =
85 (mem::replace(&mut *self.ty_substs.borrow_mut(), ty_substs),
86 mem::replace(&mut *self.lt_substs.borrow_mut(), lt_substs));
88 *self.ty_substs.borrow_mut() = old_tys;
89 *self.lt_substs.borrow_mut() = old_lts;
94 pub trait DocAccessLevels {
95 fn is_doc_reachable(&self, did: DefId) -> bool;
98 impl DocAccessLevels for AccessLevels<DefId> {
99 fn is_doc_reachable(&self, did: DefId) -> bool {
105 pub fn run_core(search_paths: SearchPaths,
107 externs: config::Externs,
109 triple: Option<String>,
110 maybe_sysroot: Option<PathBuf>,
111 allow_warnings: bool,
112 force_unstable_if_unmarked: bool) -> (clean::Crate, RenderInfo)
114 // Parse, resolve, and typecheck the given crate.
116 let cpath = match input {
117 Input::File(ref p) => Some(p.clone()),
121 let warning_lint = lint::builtin::WARNINGS.name_lower();
123 let sessopts = config::Options {
126 crate_types: vec![config::CrateTypeRlib],
127 lint_opts: if !allow_warnings { vec![(warning_lint, lint::Allow)] } else { vec![] },
128 lint_cap: Some(lint::Allow),
130 target_triple: triple.unwrap_or(config::host_triple().to_string()),
131 // Ensure that rustdoc works even if rustc is feature-staged
132 unstable_features: UnstableFeatures::Allow,
133 actually_rustdoc: true,
134 debugging_opts: config::DebuggingOptions {
135 force_unstable_if_unmarked,
136 ..config::basic_debugging_options()
138 ..config::basic_options().clone()
141 let codemap = Rc::new(codemap::CodeMap::new(sessopts.file_path_mapping()));
142 let diagnostic_handler = errors::Handler::with_tty_emitter(ColorConfig::Auto,
145 Some(codemap.clone()));
147 let dep_graph = DepGraph::new(false);
148 let _ignore = dep_graph.in_ignore();
149 let cstore = Rc::new(CStore::new(box rustc_trans::LlvmMetadataLoader));
150 let mut sess = session::build_session_(
151 sessopts, &dep_graph, cpath, diagnostic_handler, codemap
153 rustc_trans::init(&sess);
154 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
156 let mut cfg = config::build_configuration(&sess, config::parse_cfgspecs(cfgs));
157 target_features::add_configuration(&mut cfg, &sess);
158 sess.parse_sess.config = cfg;
160 let krate = panictry!(driver::phase_1_parse_input(&driver::CompileController::basic(),
163 let krate = ReplaceBodyWithLoop::new().fold_crate(krate);
165 let name = link::find_crate_name(Some(&sess), &krate.attrs, &input);
167 let driver::ExpansionResult { defs, analysis, resolutions, mut hir_forest, .. } = {
168 let result = driver::phase_2_configure_and_expand(&sess,
174 resolve::MakeGlobMap::No,
176 abort_on_err(result, &sess)
179 let arena = DroplessArena::new();
180 let arenas = GlobalArenas::new();
181 let hir_map = hir_map::map_crate(&mut hir_forest, defs);
183 abort_on_err(driver::phase_3_run_analysis_passes(&sess,
191 |tcx, analysis, _, result| {
192 if let Err(_) = result {
193 sess.fatal("Compilation failed, aborting rustdoc");
196 let ty::CrateAnalysis { access_levels, .. } = analysis;
198 // Convert from a NodeId set to a DefId set since we don't always have easy access
199 // to the map from defid -> nodeid
200 let access_levels = AccessLevels {
201 map: access_levels.map.iter()
202 .map(|(&k, &v)| (tcx.hir.local_def_id(k), v))
206 let ctxt = DocContext {
208 populated_all_crate_impls: Cell::new(false),
209 access_levels: RefCell::new(access_levels),
210 external_traits: Default::default(),
211 renderinfo: Default::default(),
212 ty_substs: Default::default(),
213 lt_substs: Default::default(),
215 debug!("crate: {:?}", tcx.hir.krate());
218 let mut v = RustdocVisitor::new(&ctxt);
219 v.visit(tcx.hir.krate());
223 (krate, ctxt.renderinfo.into_inner())