]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/core.rs
Remove the `cstore` reference from Session in order to prepare encapsulating CrateSto...
[rust.git] / src / librustdoc / core.rs
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.
4 //
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.
10
11 use rustc_lint;
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;
21 use rustc::lint;
22 use rustc::util::nodemap::FxHashMap;
23 use rustc_trans;
24 use rustc_trans::back::link;
25 use rustc_resolve as resolve;
26 use rustc_metadata::cstore::CStore;
27
28 use syntax::{ast, codemap};
29 use syntax::feature_gate::UnstableFeatures;
30 use syntax::fold::Folder;
31 use errors;
32 use errors::emitter::ColorConfig;
33
34 use std::cell::{RefCell, Cell};
35 use std::mem;
36 use std::rc::Rc;
37 use std::path::PathBuf;
38
39 use visit_ast::RustdocVisitor;
40 use clean;
41 use clean::Clean;
42 use html::render::RenderInfo;
43 use arena::DroplessArena;
44
45 pub use rustc::session::config::Input;
46 pub use rustc::session::search_paths::SearchPaths;
47
48 pub type ExternalPaths = FxHashMap<DefId, (Vec<String>, clean::TypeKind)>;
49
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>>,
62
63     // The current set of type and lifetime substitutions,
64     // for expanding type aliases at the HIR level:
65
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>>,
70 }
71
72 impl<'a, 'tcx> DocContext<'a, 'tcx> {
73     pub fn sess(&self) -> &session::Session {
74         &self.tcx.sess
75     }
76
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>,
82                              f: F) -> R
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));
87         let r = f();
88         *self.ty_substs.borrow_mut() = old_tys;
89         *self.lt_substs.borrow_mut() = old_lts;
90         r
91     }
92 }
93
94 pub trait DocAccessLevels {
95     fn is_doc_reachable(&self, did: DefId) -> bool;
96 }
97
98 impl DocAccessLevels for AccessLevels<DefId> {
99     fn is_doc_reachable(&self, did: DefId) -> bool {
100         self.is_public(did)
101     }
102 }
103
104
105 pub fn run_core(search_paths: SearchPaths,
106                 cfgs: Vec<String>,
107                 externs: config::Externs,
108                 input: Input,
109                 triple: Option<String>,
110                 maybe_sysroot: Option<PathBuf>,
111                 allow_warnings: bool,
112                 force_unstable_if_unmarked: bool) -> (clean::Crate, RenderInfo)
113 {
114     // Parse, resolve, and typecheck the given crate.
115
116     let cpath = match input {
117         Input::File(ref p) => Some(p.clone()),
118         _ => None
119     };
120
121     let warning_lint = lint::builtin::WARNINGS.name_lower();
122
123     let sessopts = config::Options {
124         maybe_sysroot,
125         search_paths,
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),
129         externs,
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()
137         },
138         ..config::basic_options().clone()
139     };
140
141     let codemap = Rc::new(codemap::CodeMap::new(sessopts.file_path_mapping()));
142     let diagnostic_handler = errors::Handler::with_tty_emitter(ColorConfig::Auto,
143                                                                true,
144                                                                false,
145                                                                Some(codemap.clone()));
146
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
152     );
153     rustc_trans::init(&sess);
154     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
155
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;
159
160     let krate = panictry!(driver::phase_1_parse_input(&driver::CompileController::basic(),
161                                                       &sess,
162                                                       &input));
163     let krate = ReplaceBodyWithLoop::new().fold_crate(krate);
164
165     let name = link::find_crate_name(Some(&sess), &krate.attrs, &input);
166
167     let driver::ExpansionResult { defs, analysis, resolutions, mut hir_forest, .. } = {
168         let result = driver::phase_2_configure_and_expand(&sess,
169                                                           &cstore,
170                                                           krate,
171                                                           None,
172                                                           &name,
173                                                           None,
174                                                           resolve::MakeGlobMap::No,
175                                                           |_| Ok(()));
176         abort_on_err(result, &sess)
177     };
178
179     let arena = DroplessArena::new();
180     let arenas = GlobalArenas::new();
181     let hir_map = hir_map::map_crate(&mut hir_forest, defs);
182
183     abort_on_err(driver::phase_3_run_analysis_passes(&sess,
184                                                      &*cstore,
185                                                      hir_map,
186                                                      analysis,
187                                                      resolutions,
188                                                      &arena,
189                                                      &arenas,
190                                                      &name,
191                                                      |tcx, analysis, _, result| {
192         if let Err(_) = result {
193             sess.fatal("Compilation failed, aborting rustdoc");
194         }
195
196         let ty::CrateAnalysis { access_levels, .. } = analysis;
197
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))
203                                   .collect()
204         };
205
206         let ctxt = DocContext {
207             tcx,
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(),
214         };
215         debug!("crate: {:?}", tcx.hir.krate());
216
217         let krate = {
218             let mut v = RustdocVisitor::new(&ctxt);
219             v.visit(tcx.hir.krate());
220             v.clean(&ctxt)
221         };
222
223         (krate, ctxt.renderinfo.into_inner())
224     }), &sess)
225 }