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_resolve as resolve;
23 use rustc_metadata::creader::CrateLoader;
24 use rustc_metadata::cstore::CStore;
26 use syntax::ast::NodeId;
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::markdown::RenderType;
41 use html::render::RenderInfo;
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, 'rcx: 'a> {
49 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
50 pub resolver: &'a RefCell<resolve::Resolver<'rcx>>,
51 /// The stack of module NodeIds up till this point
52 pub mod_ids: RefCell<Vec<NodeId>>,
53 pub populated_all_crate_impls: Cell<bool>,
54 // Note that external items for which `doc(hidden)` applies to are shown as
55 // non-reachable while local items aren't. This is because we're reusing
56 // the access levels from crateanalysis.
57 /// Later on moved into `clean::Crate`
58 pub access_levels: RefCell<AccessLevels<DefId>>,
59 /// Later on moved into `html::render::CACHE_KEY`
60 pub renderinfo: RefCell<RenderInfo>,
61 /// Later on moved through `clean::Crate` into `html::render::CACHE_KEY`
62 pub external_traits: RefCell<FxHashMap<DefId, clean::Trait>>,
63 /// Which markdown renderer to use when extracting links.
64 pub render_type: RenderType,
66 // The current set of type and lifetime substitutions,
67 // for expanding type aliases at the HIR level:
69 /// Table type parameter definition -> substituted type
70 pub ty_substs: RefCell<FxHashMap<Def, clean::Type>>,
71 /// Table node id of lifetime parameter definition -> substituted lifetime
72 pub lt_substs: RefCell<FxHashMap<DefId, clean::Lifetime>>,
75 impl<'a, 'tcx, 'rcx> DocContext<'a, 'tcx, 'rcx> {
76 pub fn sess(&self) -> &session::Session {
80 /// Call the closure with the given parameters set as
81 /// the substitutions for a type alias' RHS.
82 pub fn enter_alias<F, R>(&self,
83 ty_substs: FxHashMap<Def, clean::Type>,
84 lt_substs: FxHashMap<DefId, clean::Lifetime>,
86 where F: FnOnce() -> R {
87 let (old_tys, old_lts) =
88 (mem::replace(&mut *self.ty_substs.borrow_mut(), ty_substs),
89 mem::replace(&mut *self.lt_substs.borrow_mut(), lt_substs));
91 *self.ty_substs.borrow_mut() = old_tys;
92 *self.lt_substs.borrow_mut() = old_lts;
97 pub trait DocAccessLevels {
98 fn is_doc_reachable(&self, did: DefId) -> bool;
101 impl DocAccessLevels for AccessLevels<DefId> {
102 fn is_doc_reachable(&self, did: DefId) -> bool {
108 pub fn run_core(search_paths: SearchPaths,
110 externs: config::Externs,
112 triple: Option<String>,
113 maybe_sysroot: Option<PathBuf>,
114 allow_warnings: bool,
115 force_unstable_if_unmarked: bool,
116 render_type: RenderType) -> (clean::Crate, RenderInfo)
118 // Parse, resolve, and typecheck the given crate.
120 let cpath = match input {
121 Input::File(ref p) => Some(p.clone()),
125 let warning_lint = lint::builtin::WARNINGS.name_lower();
127 let sessopts = config::Options {
130 crate_types: vec![config::CrateTypeRlib],
131 lint_opts: if !allow_warnings { vec![(warning_lint, lint::Allow)] } else { vec![] },
132 lint_cap: Some(lint::Allow),
134 target_triple: triple.unwrap_or(config::host_triple().to_string()),
135 // Ensure that rustdoc works even if rustc is feature-staged
136 unstable_features: UnstableFeatures::Allow,
137 actually_rustdoc: true,
138 debugging_opts: config::DebuggingOptions {
139 force_unstable_if_unmarked,
140 ..config::basic_debugging_options()
142 ..config::basic_options().clone()
145 let codemap = Rc::new(codemap::CodeMap::new(sessopts.file_path_mapping()));
146 let diagnostic_handler = errors::Handler::with_tty_emitter(ColorConfig::Auto,
149 Some(codemap.clone()));
151 let mut sess = session::build_session_(
152 sessopts, cpath, diagnostic_handler, codemap,
154 let trans = rustc_trans::LlvmTransCrate::new(&sess);
155 let cstore = Rc::new(CStore::new(trans.metadata_loader()));
156 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
158 let mut cfg = config::build_configuration(&sess, config::parse_cfgspecs(cfgs));
159 target_features::add_configuration(&mut cfg, &sess, &*trans);
160 sess.parse_sess.config = cfg;
162 let control = &driver::CompileController::basic();
164 let krate = panictry!(driver::phase_1_parse_input(control, &sess, &input));
166 let name = ::rustc_trans_utils::link::find_crate_name(Some(&sess), &krate.attrs, &input);
168 let mut crate_loader = CrateLoader::new(&sess, &cstore, &name);
170 let resolver_arenas = resolve::Resolver::arenas();
171 let result = driver::phase_2_configure_and_expand_inner(&sess,
177 resolve::MakeGlobMap::No,
181 let driver::InnerExpansionResult {
185 } = abort_on_err(result, &sess);
187 // We need to hold on to the complete resolver, so we clone everything
188 // for the analysis passes to use. Suboptimal, but necessary in the
189 // current architecture.
190 let defs = resolver.definitions.clone();
191 let resolutions = ty::Resolutions {
192 freevars: resolver.freevars.clone(),
193 export_map: resolver.export_map.clone(),
194 trait_map: resolver.trait_map.clone(),
195 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports.clone(),
196 maybe_unused_extern_crates: resolver.maybe_unused_extern_crates.clone(),
198 let analysis = ty::CrateAnalysis {
199 access_levels: Rc::new(AccessLevels::default()),
200 name: name.to_string(),
201 glob_map: if resolver.make_glob_map { Some(resolver.glob_map.clone()) } else { None },
204 let arenas = AllArenas::new();
205 let hir_map = hir_map::map_crate(&sess, &*cstore, &mut hir_forest, &defs);
206 let output_filenames = driver::build_output_filenames(&input,
212 let resolver = RefCell::new(resolver);
214 abort_on_err(driver::phase_3_run_analysis_passes(&*trans,
224 |tcx, analysis, _, result| {
225 if let Err(_) = result {
226 sess.fatal("Compilation failed, aborting rustdoc");
229 let ty::CrateAnalysis { access_levels, .. } = analysis;
231 // Convert from a NodeId set to a DefId set since we don't always have easy access
232 // to the map from defid -> nodeid
233 let access_levels = AccessLevels {
234 map: access_levels.map.iter()
235 .map(|(&k, &v)| (tcx.hir.local_def_id(k), v))
239 let ctxt = DocContext {
242 populated_all_crate_impls: Cell::new(false),
243 access_levels: RefCell::new(access_levels),
244 external_traits: Default::default(),
245 renderinfo: Default::default(),
247 ty_substs: Default::default(),
248 lt_substs: Default::default(),
249 mod_ids: Default::default(),
251 debug!("crate: {:?}", tcx.hir.krate());
254 let mut v = RustdocVisitor::new(&*cstore, &ctxt);
255 v.visit(tcx.hir.krate());
259 (krate, ctxt.renderinfo.into_inner())