]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/core.rs
add -C parameter to rustdoc
[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::{self, driver, target_features, abort_on_err};
13 use rustc::session::{self, config};
14 use rustc::hir::def_id::{DefId, CrateNum};
15 use rustc::hir::def::Def;
16 use rustc::middle::cstore::CrateStore;
17 use rustc::middle::privacy::AccessLevels;
18 use rustc::ty::{self, TyCtxt, AllArenas};
19 use rustc::hir::map as hir_map;
20 use rustc::lint;
21 use rustc::util::nodemap::{FxHashMap, FxHashSet};
22 use rustc_resolve as resolve;
23 use rustc_metadata::creader::CrateLoader;
24 use rustc_metadata::cstore::CStore;
25 use rustc_back::target::TargetTriple;
26
27 use syntax::ast::NodeId;
28 use syntax::codemap;
29 use syntax::edition::Edition;
30 use syntax::feature_gate::UnstableFeatures;
31 use errors;
32 use errors::emitter::ColorConfig;
33
34 use std::cell::{RefCell, Cell};
35 use std::mem;
36 use rustc_data_structures::sync::Lrc;
37 use std::rc::Rc;
38 use std::path::PathBuf;
39
40 use visit_ast::RustdocVisitor;
41 use clean;
42 use clean::Clean;
43 use html::render::RenderInfo;
44
45 pub use rustc::session::config::{Input, CodegenOptions};
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, 'rcx: 'a> {
51     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
52     pub resolver: &'a RefCell<resolve::Resolver<'rcx>>,
53     /// The stack of module NodeIds up till this point
54     pub mod_ids: RefCell<Vec<NodeId>>,
55     pub crate_name: Option<String>,
56     pub cstore: Rc<CrateStore>,
57     pub populated_all_crate_impls: Cell<bool>,
58     // Note that external items for which `doc(hidden)` applies to are shown as
59     // non-reachable while local items aren't. This is because we're reusing
60     // the access levels from crateanalysis.
61     /// Later on moved into `clean::Crate`
62     pub access_levels: RefCell<AccessLevels<DefId>>,
63     /// Later on moved into `html::render::CACHE_KEY`
64     pub renderinfo: RefCell<RenderInfo>,
65     /// Later on moved through `clean::Crate` into `html::render::CACHE_KEY`
66     pub external_traits: RefCell<FxHashMap<DefId, clean::Trait>>,
67     /// Used while populating `external_traits` to ensure we don't process the same trait twice at
68     /// the same time.
69     pub active_extern_traits: RefCell<Vec<DefId>>,
70     // The current set of type and lifetime substitutions,
71     // for expanding type aliases at the HIR level:
72
73     /// Table type parameter definition -> substituted type
74     pub ty_substs: RefCell<FxHashMap<Def, clean::Type>>,
75     /// Table node id of lifetime parameter definition -> substituted lifetime
76     pub lt_substs: RefCell<FxHashMap<DefId, clean::Lifetime>>,
77     /// Table DefId of `impl Trait` in argument position -> bounds
78     pub impl_trait_bounds: RefCell<FxHashMap<DefId, Vec<clean::TyParamBound>>>,
79     pub send_trait: Option<DefId>,
80     pub fake_def_ids: RefCell<FxHashMap<CrateNum, DefId>>,
81     pub all_fake_def_ids: RefCell<FxHashSet<DefId>>,
82     /// Maps (type_id, trait_id) -> auto trait impl
83     pub generated_synthetics: RefCell<FxHashSet<(DefId, DefId)>>
84 }
85
86 impl<'a, 'tcx, 'rcx> DocContext<'a, 'tcx, 'rcx> {
87     pub fn sess(&self) -> &session::Session {
88         &self.tcx.sess
89     }
90
91     /// Call the closure with the given parameters set as
92     /// the substitutions for a type alias' RHS.
93     pub fn enter_alias<F, R>(&self,
94                              ty_substs: FxHashMap<Def, clean::Type>,
95                              lt_substs: FxHashMap<DefId, clean::Lifetime>,
96                              f: F) -> R
97     where F: FnOnce() -> R {
98         let (old_tys, old_lts) =
99             (mem::replace(&mut *self.ty_substs.borrow_mut(), ty_substs),
100              mem::replace(&mut *self.lt_substs.borrow_mut(), lt_substs));
101         let r = f();
102         *self.ty_substs.borrow_mut() = old_tys;
103         *self.lt_substs.borrow_mut() = old_lts;
104         r
105     }
106 }
107
108 pub trait DocAccessLevels {
109     fn is_doc_reachable(&self, did: DefId) -> bool;
110 }
111
112 impl DocAccessLevels for AccessLevels<DefId> {
113     fn is_doc_reachable(&self, did: DefId) -> bool {
114         self.is_public(did)
115     }
116 }
117
118
119 pub fn run_core(search_paths: SearchPaths,
120                 cfgs: Vec<String>,
121                 externs: config::Externs,
122                 input: Input,
123                 triple: Option<TargetTriple>,
124                 maybe_sysroot: Option<PathBuf>,
125                 allow_warnings: bool,
126                 crate_name: Option<String>,
127                 force_unstable_if_unmarked: bool,
128                 edition: Edition,
129                 cg: CodegenOptions) -> (clean::Crate, RenderInfo)
130 {
131     // Parse, resolve, and typecheck the given crate.
132
133     let cpath = match input {
134         Input::File(ref p) => Some(p.clone()),
135         _ => None
136     };
137
138     let warning_lint = lint::builtin::WARNINGS.name_lower();
139
140     let host_triple = TargetTriple::from_triple(config::host_triple());
141     let sessopts = config::Options {
142         maybe_sysroot,
143         search_paths,
144         crate_types: vec![config::CrateTypeRlib],
145         lint_opts: if !allow_warnings { vec![(warning_lint, lint::Allow)] } else { vec![] },
146         lint_cap: Some(lint::Allow),
147         cg,
148         externs,
149         target_triple: triple.unwrap_or(host_triple),
150         // Ensure that rustdoc works even if rustc is feature-staged
151         unstable_features: UnstableFeatures::Allow,
152         actually_rustdoc: true,
153         debugging_opts: config::DebuggingOptions {
154             force_unstable_if_unmarked,
155             edition,
156             ..config::basic_debugging_options()
157         },
158         ..config::basic_options().clone()
159     };
160
161     let codemap = Lrc::new(codemap::CodeMap::new(sessopts.file_path_mapping()));
162     let diagnostic_handler = errors::Handler::with_tty_emitter(ColorConfig::Auto,
163                                                                true,
164                                                                false,
165                                                                Some(codemap.clone()));
166
167     let mut sess = session::build_session_(
168         sessopts, cpath, diagnostic_handler, codemap,
169     );
170     let trans = rustc_driver::get_trans(&sess);
171     let cstore = Rc::new(CStore::new(trans.metadata_loader()));
172     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
173
174     let mut cfg = config::build_configuration(&sess, config::parse_cfgspecs(cfgs));
175     target_features::add_configuration(&mut cfg, &sess, &*trans);
176     sess.parse_sess.config = cfg;
177
178     let control = &driver::CompileController::basic();
179
180     let krate = panictry!(driver::phase_1_parse_input(control, &sess, &input));
181
182     let name = ::rustc_trans_utils::link::find_crate_name(Some(&sess), &krate.attrs, &input);
183
184     let mut crate_loader = CrateLoader::new(&sess, &cstore, &name);
185
186     let resolver_arenas = resolve::Resolver::arenas();
187     let result = driver::phase_2_configure_and_expand_inner(&sess,
188                                                       &cstore,
189                                                       krate,
190                                                       None,
191                                                       &name,
192                                                       None,
193                                                       resolve::MakeGlobMap::No,
194                                                       &resolver_arenas,
195                                                       &mut crate_loader,
196                                                       |_| Ok(()));
197     let driver::InnerExpansionResult {
198         mut hir_forest,
199         resolver,
200         ..
201     } = abort_on_err(result, &sess);
202
203     // We need to hold on to the complete resolver, so we clone everything
204     // for the analysis passes to use. Suboptimal, but necessary in the
205     // current architecture.
206     let defs = resolver.definitions.clone();
207     let resolutions = ty::Resolutions {
208         freevars: resolver.freevars.clone(),
209         export_map: resolver.export_map.clone(),
210         trait_map: resolver.trait_map.clone(),
211         maybe_unused_trait_imports: resolver.maybe_unused_trait_imports.clone(),
212         maybe_unused_extern_crates: resolver.maybe_unused_extern_crates.clone(),
213     };
214     let analysis = ty::CrateAnalysis {
215         access_levels: Lrc::new(AccessLevels::default()),
216         name: name.to_string(),
217         glob_map: if resolver.make_glob_map { Some(resolver.glob_map.clone()) } else { None },
218     };
219
220     let arenas = AllArenas::new();
221     let hir_map = hir_map::map_crate(&sess, &*cstore, &mut hir_forest, &defs);
222     let output_filenames = driver::build_output_filenames(&input,
223                                                           &None,
224                                                           &None,
225                                                           &[],
226                                                           &sess);
227
228     let resolver = RefCell::new(resolver);
229
230     abort_on_err(driver::phase_3_run_analysis_passes(&*trans,
231                                                      control,
232                                                      &sess,
233                                                      &*cstore,
234                                                      hir_map,
235                                                      analysis,
236                                                      resolutions,
237                                                      &arenas,
238                                                      &name,
239                                                      &output_filenames,
240                                                      |tcx, analysis, _, result| {
241         if let Err(_) = result {
242             sess.fatal("Compilation failed, aborting rustdoc");
243         }
244
245         let ty::CrateAnalysis { access_levels, .. } = analysis;
246
247         // Convert from a NodeId set to a DefId set since we don't always have easy access
248         // to the map from defid -> nodeid
249         let access_levels = AccessLevels {
250             map: access_levels.map.iter()
251                                   .map(|(&k, &v)| (tcx.hir.local_def_id(k), v))
252                                   .collect()
253         };
254
255         let send_trait = if crate_name == Some("core".to_string()) {
256             clean::get_trait_def_id(&tcx, &["marker", "Send"], true)
257         } else {
258             clean::get_trait_def_id(&tcx, &["core", "marker", "Send"], false)
259         };
260
261         let ctxt = DocContext {
262             tcx,
263             resolver: &resolver,
264             crate_name,
265             cstore: cstore.clone(),
266             populated_all_crate_impls: Cell::new(false),
267             access_levels: RefCell::new(access_levels),
268             external_traits: Default::default(),
269             active_extern_traits: Default::default(),
270             renderinfo: Default::default(),
271             ty_substs: Default::default(),
272             lt_substs: Default::default(),
273             impl_trait_bounds: Default::default(),
274             mod_ids: Default::default(),
275             send_trait: send_trait,
276             fake_def_ids: RefCell::new(FxHashMap()),
277             all_fake_def_ids: RefCell::new(FxHashSet()),
278             generated_synthetics: RefCell::new(FxHashSet()),
279         };
280         debug!("crate: {:?}", tcx.hir.krate());
281
282         let krate = {
283             let mut v = RustdocVisitor::new(&*cstore, &ctxt);
284             v.visit(tcx.hir.krate());
285             v.clean(&ctxt)
286         };
287
288         (krate, ctxt.renderinfo.into_inner())
289     }), &sess)
290 }