]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/core.rs
Rollup merge of #35558 - lukehinds:master, r=nikomatsakis
[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 pub use self::MaybeTyped::*;
11
12 use rustc_lint;
13 use rustc_driver::{driver, target_features, abort_on_err};
14 use rustc::dep_graph::DepGraph;
15 use rustc::session::{self, config};
16 use rustc::hir::def_id::DefId;
17 use rustc::middle::privacy::AccessLevels;
18 use rustc::ty::{self, TyCtxt};
19 use rustc::hir::map as hir_map;
20 use rustc::lint;
21 use rustc_trans::back::link;
22 use rustc_resolve as resolve;
23 use rustc_metadata::cstore::CStore;
24
25 use syntax::{ast, codemap};
26 use syntax::feature_gate::UnstableFeatures;
27 use errors;
28 use errors::emitter::ColorConfig;
29
30 use std::cell::{RefCell, Cell};
31 use std::collections::{HashMap, HashSet};
32 use std::rc::Rc;
33
34 use visit_ast::RustdocVisitor;
35 use clean;
36 use clean::Clean;
37 use html::render::RenderInfo;
38
39 pub use rustc::session::config::Input;
40 pub use rustc::session::search_paths::SearchPaths;
41
42 /// Are we generating documentation (`Typed`) or tests (`NotTyped`)?
43 pub enum MaybeTyped<'a, 'tcx: 'a> {
44     Typed(TyCtxt<'a, 'tcx, 'tcx>),
45     NotTyped(&'a session::Session)
46 }
47
48 pub type Externs = HashMap<String, Vec<String>>;
49 pub type ExternalPaths = HashMap<DefId, (Vec<String>, clean::TypeKind)>;
50
51 pub struct DocContext<'a, 'tcx: 'a> {
52     pub map: &'a hir_map::Map<'tcx>,
53     pub maybe_typed: MaybeTyped<'a, 'tcx>,
54     pub input: Input,
55     pub populated_crate_impls: RefCell<HashSet<ast::CrateNum>>,
56     pub deref_trait_did: Cell<Option<DefId>>,
57     // Note that external items for which `doc(hidden)` applies to are shown as
58     // non-reachable while local items aren't. This is because we're reusing
59     // the access levels from crateanalysis.
60     /// Later on moved into `clean::Crate`
61     pub access_levels: RefCell<AccessLevels<DefId>>,
62     /// Later on moved into `html::render::CACHE_KEY`
63     pub renderinfo: RefCell<RenderInfo>,
64     /// Later on moved through `clean::Crate` into `html::render::CACHE_KEY`
65     pub external_traits: RefCell<HashMap<DefId, clean::Trait>>,
66 }
67
68 impl<'b, 'tcx> DocContext<'b, 'tcx> {
69     pub fn sess<'a>(&'a self) -> &'a session::Session {
70         match self.maybe_typed {
71             Typed(tcx) => &tcx.sess,
72             NotTyped(ref sess) => sess
73         }
74     }
75
76     pub fn tcx_opt<'a>(&'a self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> {
77         match self.maybe_typed {
78             Typed(tcx) => Some(tcx),
79             NotTyped(_) => None
80         }
81     }
82
83     pub fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
84         let tcx_opt = self.tcx_opt();
85         tcx_opt.expect("tcx not present")
86     }
87 }
88
89 pub trait DocAccessLevels {
90     fn is_doc_reachable(&self, DefId) -> bool;
91 }
92
93 impl DocAccessLevels for AccessLevels<DefId> {
94     fn is_doc_reachable(&self, did: DefId) -> bool {
95         self.is_public(did)
96     }
97 }
98
99
100 pub fn run_core(search_paths: SearchPaths,
101                 cfgs: Vec<String>,
102                 externs: Externs,
103                 input: Input,
104                 triple: Option<String>) -> (clean::Crate, RenderInfo)
105 {
106     // Parse, resolve, and typecheck the given crate.
107
108     let cpath = match input {
109         Input::File(ref p) => Some(p.clone()),
110         _ => None
111     };
112
113     let warning_lint = lint::builtin::WARNINGS.name_lower();
114
115     let sessopts = config::Options {
116         maybe_sysroot: None,
117         search_paths: search_paths,
118         crate_types: vec!(config::CrateTypeRlib),
119         lint_opts: vec!((warning_lint, lint::Allow)),
120         lint_cap: Some(lint::Allow),
121         externs: externs,
122         target_triple: triple.unwrap_or(config::host_triple().to_string()),
123         cfg: config::parse_cfgspecs(cfgs),
124         // Ensure that rustdoc works even if rustc is feature-staged
125         unstable_features: UnstableFeatures::Allow,
126         ..config::basic_options().clone()
127     };
128
129     let codemap = Rc::new(codemap::CodeMap::new());
130     let diagnostic_handler = errors::Handler::with_tty_emitter(ColorConfig::Auto,
131                                                                true,
132                                                                false,
133                                                                Some(codemap.clone()));
134
135     let dep_graph = DepGraph::new(false);
136     let _ignore = dep_graph.in_ignore();
137     let cstore = Rc::new(CStore::new(&dep_graph));
138     let sess = session::build_session_(sessopts, &dep_graph, cpath, diagnostic_handler,
139                                        codemap, cstore.clone());
140     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
141
142     let mut cfg = config::build_configuration(&sess);
143     target_features::add_configuration(&mut cfg, &sess);
144
145     let krate = panictry!(driver::phase_1_parse_input(&sess, cfg, &input));
146
147     let name = link::find_crate_name(Some(&sess), &krate.attrs, &input);
148
149     let driver::ExpansionResult { defs, analysis, resolutions, mut hir_forest, .. } = {
150         driver::phase_2_configure_and_expand(
151             &sess, &cstore, krate, &name, None, resolve::MakeGlobMap::No, |_| Ok(()),
152         ).expect("phase_2_configure_and_expand aborted in rustdoc!")
153     };
154
155     let arenas = ty::CtxtArenas::new();
156     let hir_map = hir_map::map_crate(&mut hir_forest, defs);
157
158     abort_on_err(driver::phase_3_run_analysis_passes(&sess,
159                                                      hir_map,
160                                                      analysis,
161                                                      resolutions,
162                                                      &arenas,
163                                                      &name,
164                                                      |tcx, _, analysis, result| {
165         if let Err(_) = result {
166             sess.fatal("Compilation failed, aborting rustdoc");
167         }
168
169         let ty::CrateAnalysis { access_levels, .. } = analysis;
170
171         // Convert from a NodeId set to a DefId set since we don't always have easy access
172         // to the map from defid -> nodeid
173         let access_levels = AccessLevels {
174             map: access_levels.map.into_iter()
175                                   .map(|(k, v)| (tcx.map.local_def_id(k), v))
176                                   .collect()
177         };
178
179         let ctxt = DocContext {
180             map: &tcx.map,
181             maybe_typed: Typed(tcx),
182             input: input,
183             populated_crate_impls: RefCell::new(HashSet::new()),
184             deref_trait_did: Cell::new(None),
185             access_levels: RefCell::new(access_levels),
186             external_traits: RefCell::new(HashMap::new()),
187             renderinfo: RefCell::new(Default::default()),
188         };
189         debug!("crate: {:?}", ctxt.map.krate());
190
191         let krate = {
192             let mut v = RustdocVisitor::new(&ctxt);
193             v.visit(ctxt.map.krate());
194             v.clean(&ctxt)
195         };
196
197         (krate, ctxt.renderinfo.into_inner())
198     }), &sess)
199 }