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::dep_graph::DepGraph;
14 use rustc::session::{self, config};
15 use rustc::hir::def_id::DefId;
16 use rustc::hir::def::Def;
17 use rustc::middle::privacy::AccessLevels;
18 use rustc::ty::{self, TyCtxt, GlobalArenas};
19 use rustc::hir::map as hir_map;
21 use rustc::util::nodemap::FxHashMap;
23 use rustc_trans::back::link;
24 use rustc_resolve as resolve;
25 use rustc_metadata::cstore::CStore;
27 use syntax::{ast, codemap};
28 use syntax::feature_gate::UnstableFeatures;
30 use errors::emitter::ColorConfig;
32 use std::cell::{RefCell, Cell};
35 use std::path::PathBuf;
37 use visit_ast::RustdocVisitor;
40 use html::render::RenderInfo;
41 use arena::DroplessArena;
43 pub use rustc::session::config::Input;
44 pub use rustc::session::search_paths::SearchPaths;
46 pub type ExternalPaths = FxHashMap<DefId, (Vec<String>, clean::TypeKind)>;
48 pub struct DocContext<'a, 'tcx: 'a> {
49 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
50 pub populated_all_crate_impls: Cell<bool>,
51 // Note that external items for which `doc(hidden)` applies to are shown as
52 // non-reachable while local items aren't. This is because we're reusing
53 // the access levels from crateanalysis.
54 /// Later on moved into `clean::Crate`
55 pub access_levels: RefCell<AccessLevels<DefId>>,
56 /// Later on moved into `html::render::CACHE_KEY`
57 pub renderinfo: RefCell<RenderInfo>,
58 /// Later on moved through `clean::Crate` into `html::render::CACHE_KEY`
59 pub external_traits: RefCell<FxHashMap<DefId, clean::Trait>>,
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 node id of lifetime parameter definition -> substituted lifetime
67 pub lt_substs: RefCell<FxHashMap<ast::NodeId, clean::Lifetime>>,
70 impl<'a, 'tcx> DocContext<'a, 'tcx> {
71 pub fn sess(&self) -> &session::Session {
75 /// Call the closure with the given parameters set as
76 /// the substitutions for a type alias' RHS.
77 pub fn enter_alias<F, R>(&self,
78 ty_substs: FxHashMap<Def, clean::Type>,
79 lt_substs: FxHashMap<ast::NodeId, clean::Lifetime>,
81 where F: FnOnce() -> R {
82 let (old_tys, old_lts) =
83 (mem::replace(&mut *self.ty_substs.borrow_mut(), ty_substs),
84 mem::replace(&mut *self.lt_substs.borrow_mut(), lt_substs));
86 *self.ty_substs.borrow_mut() = old_tys;
87 *self.lt_substs.borrow_mut() = old_lts;
92 pub trait DocAccessLevels {
93 fn is_doc_reachable(&self, did: DefId) -> bool;
96 impl DocAccessLevels for AccessLevels<DefId> {
97 fn is_doc_reachable(&self, did: DefId) -> bool {
103 pub fn run_core(search_paths: SearchPaths,
105 externs: config::Externs,
107 triple: Option<String>,
108 maybe_sysroot: Option<PathBuf>,
109 allow_warnings: bool) -> (clean::Crate, RenderInfo)
111 // Parse, resolve, and typecheck the given crate.
113 let cpath = match input {
114 Input::File(ref p) => Some(p.clone()),
118 let warning_lint = lint::builtin::WARNINGS.name_lower();
120 let sessopts = config::Options {
121 maybe_sysroot: maybe_sysroot,
122 search_paths: search_paths,
123 crate_types: vec![config::CrateTypeRlib],
124 lint_opts: if !allow_warnings { vec![(warning_lint, lint::Allow)] } else { vec![] },
125 lint_cap: Some(lint::Allow),
127 target_triple: triple.unwrap_or(config::host_triple().to_string()),
128 // Ensure that rustdoc works even if rustc is feature-staged
129 unstable_features: UnstableFeatures::Allow,
130 actually_rustdoc: true,
131 ..config::basic_options().clone()
134 let codemap = Rc::new(codemap::CodeMap::new(sessopts.file_path_mapping()));
135 let diagnostic_handler = errors::Handler::with_tty_emitter(ColorConfig::Auto,
138 Some(codemap.clone()));
140 let dep_graph = DepGraph::new(false);
141 let _ignore = dep_graph.in_ignore();
142 let cstore = Rc::new(CStore::new(&dep_graph, box rustc_trans::LlvmMetadataLoader));
143 let mut sess = session::build_session_(
144 sessopts, &dep_graph, cpath, diagnostic_handler, codemap, cstore.clone()
146 rustc_trans::init(&sess);
147 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
149 let mut cfg = config::build_configuration(&sess, config::parse_cfgspecs(cfgs));
150 target_features::add_configuration(&mut cfg, &sess);
151 sess.parse_sess.config = cfg;
153 let krate = panictry!(driver::phase_1_parse_input(&sess, &input));
155 let name = link::find_crate_name(Some(&sess), &krate.attrs, &input);
157 let driver::ExpansionResult { defs, analysis, resolutions, mut hir_forest, .. } = {
158 let result = driver::phase_2_configure_and_expand(&sess,
164 resolve::MakeGlobMap::No,
166 abort_on_err(result, &sess)
169 let arena = DroplessArena::new();
170 let arenas = GlobalArenas::new();
171 let hir_map = hir_map::map_crate(&mut hir_forest, defs);
173 abort_on_err(driver::phase_3_run_analysis_passes(&sess,
180 |tcx, analysis, _, result| {
181 if let Err(_) = result {
182 sess.fatal("Compilation failed, aborting rustdoc");
185 let ty::CrateAnalysis { access_levels, .. } = analysis;
187 // Convert from a NodeId set to a DefId set since we don't always have easy access
188 // to the map from defid -> nodeid
189 let access_levels = AccessLevels {
190 map: access_levels.map.iter()
191 .map(|(&k, &v)| (tcx.hir.local_def_id(k), v))
195 let ctxt = DocContext {
197 populated_all_crate_impls: Cell::new(false),
198 access_levels: RefCell::new(access_levels),
199 external_traits: Default::default(),
200 renderinfo: Default::default(),
201 ty_substs: Default::default(),
202 lt_substs: Default::default(),
204 debug!("crate: {:?}", tcx.hir.krate());
207 let mut v = RustdocVisitor::new(&ctxt);
208 v.visit(tcx.hir.krate());
212 (krate, ctxt.renderinfo.into_inner())