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::session::{self, config};
14 use rustc::hir::def_id::DefId;
15 use rustc::hir::def::Def;
16 use rustc::middle::privacy::AccessLevels;
17 use rustc::ty::{self, TyCtxt, AllArenas};
18 use rustc::hir::map as hir_map;
20 use rustc::util::nodemap::FxHashMap;
22 use rustc_trans::back::link;
23 use rustc_resolve as resolve;
24 use rustc_metadata::cstore::CStore;
27 use syntax::feature_gate::UnstableFeatures;
29 use errors::emitter::ColorConfig;
31 use std::cell::{RefCell, Cell};
34 use std::path::PathBuf;
36 use visit_ast::RustdocVisitor;
39 use html::render::RenderInfo;
41 pub use rustc::session::config::Input;
42 pub use rustc::session::search_paths::SearchPaths;
44 pub type ExternalPaths = FxHashMap<DefId, (Vec<String>, clean::TypeKind)>;
46 pub struct DocContext<'a, 'tcx: 'a> {
47 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
48 pub populated_all_crate_impls: Cell<bool>,
49 // Note that external items for which `doc(hidden)` applies to are shown as
50 // non-reachable while local items aren't. This is because we're reusing
51 // the access levels from crateanalysis.
52 /// Later on moved into `clean::Crate`
53 pub access_levels: RefCell<AccessLevels<DefId>>,
54 /// Later on moved into `html::render::CACHE_KEY`
55 pub renderinfo: RefCell<RenderInfo>,
56 /// Later on moved through `clean::Crate` into `html::render::CACHE_KEY`
57 pub external_traits: RefCell<FxHashMap<DefId, clean::Trait>>,
59 // The current set of type and lifetime substitutions,
60 // for expanding type aliases at the HIR level:
62 /// Table type parameter definition -> substituted type
63 pub ty_substs: RefCell<FxHashMap<Def, clean::Type>>,
64 /// Table node id of lifetime parameter definition -> substituted lifetime
65 pub lt_substs: RefCell<FxHashMap<DefId, clean::Lifetime>>,
68 impl<'a, 'tcx> DocContext<'a, 'tcx> {
69 pub fn sess(&self) -> &session::Session {
73 /// Call the closure with the given parameters set as
74 /// the substitutions for a type alias' RHS.
75 pub fn enter_alias<F, R>(&self,
76 ty_substs: FxHashMap<Def, clean::Type>,
77 lt_substs: FxHashMap<DefId, clean::Lifetime>,
79 where F: FnOnce() -> R {
80 let (old_tys, old_lts) =
81 (mem::replace(&mut *self.ty_substs.borrow_mut(), ty_substs),
82 mem::replace(&mut *self.lt_substs.borrow_mut(), lt_substs));
84 *self.ty_substs.borrow_mut() = old_tys;
85 *self.lt_substs.borrow_mut() = old_lts;
90 pub trait DocAccessLevels {
91 fn is_doc_reachable(&self, did: DefId) -> bool;
94 impl DocAccessLevels for AccessLevels<DefId> {
95 fn is_doc_reachable(&self, did: DefId) -> bool {
101 pub fn run_core(search_paths: SearchPaths,
103 externs: config::Externs,
105 triple: Option<String>,
106 maybe_sysroot: Option<PathBuf>,
107 allow_warnings: bool,
108 force_unstable_if_unmarked: bool) -> (clean::Crate, RenderInfo)
110 // Parse, resolve, and typecheck the given crate.
112 let cpath = match input {
113 Input::File(ref p) => Some(p.clone()),
117 let warning_lint = lint::builtin::WARNINGS.name_lower();
119 let sessopts = config::Options {
122 crate_types: vec![config::CrateTypeRlib],
123 lint_opts: if !allow_warnings { vec![(warning_lint, lint::Allow)] } else { vec![] },
124 lint_cap: Some(lint::Allow),
126 target_triple: triple.unwrap_or(config::host_triple().to_string()),
127 // Ensure that rustdoc works even if rustc is feature-staged
128 unstable_features: UnstableFeatures::Allow,
129 actually_rustdoc: true,
130 debugging_opts: config::DebuggingOptions {
131 force_unstable_if_unmarked,
132 ..config::basic_debugging_options()
134 ..config::basic_options().clone()
137 let codemap = Rc::new(codemap::CodeMap::new(sessopts.file_path_mapping()));
138 let diagnostic_handler = errors::Handler::with_tty_emitter(ColorConfig::Auto,
141 Some(codemap.clone()));
143 let cstore = Rc::new(CStore::new(box rustc_trans::LlvmMetadataLoader));
144 let mut sess = session::build_session_(
145 sessopts, cpath, diagnostic_handler, codemap,
147 rustc_trans::init(&sess);
148 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
150 let mut cfg = config::build_configuration(&sess, config::parse_cfgspecs(cfgs));
151 target_features::add_configuration(&mut cfg, &sess);
152 sess.parse_sess.config = cfg;
154 let control = &driver::CompileController::basic();
156 let krate = panictry!(driver::phase_1_parse_input(control, &sess, &input));
158 let name = link::find_crate_name(Some(&sess), &krate.attrs, &input);
160 let driver::ExpansionResult { defs, analysis, resolutions, mut hir_forest, .. } = {
161 let result = driver::phase_2_configure_and_expand(&sess,
167 resolve::MakeGlobMap::No,
169 abort_on_err(result, &sess)
172 let arenas = AllArenas::new();
173 let hir_map = hir_map::map_crate(&sess, &*cstore, &mut hir_forest, &defs);
174 let output_filenames = driver::build_output_filenames(&input,
180 abort_on_err(driver::phase_3_run_analysis_passes(control,
189 |tcx, analysis, _, result| {
190 if let Err(_) = result {
191 sess.fatal("Compilation failed, aborting rustdoc");
194 let ty::CrateAnalysis { access_levels, .. } = analysis;
196 // Convert from a NodeId set to a DefId set since we don't always have easy access
197 // to the map from defid -> nodeid
198 let access_levels = AccessLevels {
199 map: access_levels.map.iter()
200 .map(|(&k, &v)| (tcx.hir.local_def_id(k), v))
204 let ctxt = DocContext {
206 populated_all_crate_impls: Cell::new(false),
207 access_levels: RefCell::new(access_levels),
208 external_traits: Default::default(),
209 renderinfo: Default::default(),
210 ty_substs: Default::default(),
211 lt_substs: Default::default(),
213 debug!("crate: {:?}", tcx.hir.krate());
216 let mut v = RustdocVisitor::new(&*cstore, &ctxt);
217 v.visit(tcx.hir.krate());
221 (krate, ctxt.renderinfo.into_inner())