]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/core.rs
Rollup merge of #31199 - steveklabnik:gh31181, r=Manishearth
[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};
14 use rustc::session::{self, config};
15 use rustc::middle::def_id::DefId;
16 use rustc::middle::privacy::AccessLevels;
17 use rustc::middle::ty;
18 use rustc::front::map as hir_map;
19 use rustc::lint;
20 use rustc_trans::back::link;
21 use rustc_resolve as resolve;
22 use rustc_front::lowering::{lower_crate, LoweringContext};
23 use rustc_metadata::cstore::CStore;
24
25 use syntax::{ast, codemap, errors};
26 use syntax::errors::emitter::ColorConfig;
27 use syntax::feature_gate::UnstableFeatures;
28 use syntax::parse::token;
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
38 pub use rustc::session::config::Input;
39 pub use rustc::session::search_paths::SearchPaths;
40
41 /// Are we generating documentation (`Typed`) or tests (`NotTyped`)?
42 pub enum MaybeTyped<'a, 'tcx: 'a> {
43     Typed(&'a ty::ctxt<'tcx>),
44     NotTyped(&'a session::Session)
45 }
46
47 pub type ExternalPaths = RefCell<Option<HashMap<DefId,
48                                                 (Vec<String>, clean::TypeKind)>>>;
49
50 pub struct DocContext<'a, 'tcx: 'a> {
51     pub map: &'a hir_map::Map<'tcx>,
52     pub maybe_typed: MaybeTyped<'a, 'tcx>,
53     pub input: Input,
54     pub external_paths: ExternalPaths,
55     pub external_traits: RefCell<Option<HashMap<DefId, clean::Trait>>>,
56     pub external_typarams: RefCell<Option<HashMap<DefId, String>>>,
57     pub inlined: RefCell<Option<HashSet<DefId>>>,
58     pub populated_crate_impls: RefCell<HashSet<ast::CrateNum>>,
59     pub deref_trait_did: Cell<Option<DefId>>,
60 }
61
62 impl<'b, 'tcx> DocContext<'b, 'tcx> {
63     pub fn sess<'a>(&'a self) -> &'a session::Session {
64         match self.maybe_typed {
65             Typed(tcx) => &tcx.sess,
66             NotTyped(ref sess) => sess
67         }
68     }
69
70     pub fn tcx_opt<'a>(&'a self) -> Option<&'a ty::ctxt<'tcx>> {
71         match self.maybe_typed {
72             Typed(tcx) => Some(tcx),
73             NotTyped(_) => None
74         }
75     }
76
77     pub fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> {
78         let tcx_opt = self.tcx_opt();
79         tcx_opt.expect("tcx not present")
80     }
81 }
82
83 pub struct CrateAnalysis {
84     pub access_levels: AccessLevels<DefId>,
85     pub external_paths: ExternalPaths,
86     pub external_typarams: RefCell<Option<HashMap<DefId, String>>>,
87     pub inlined: RefCell<Option<HashSet<DefId>>>,
88     pub deref_trait_did: Option<DefId>,
89 }
90
91 pub type Externs = HashMap<String, Vec<String>>;
92
93 pub fn run_core(search_paths: SearchPaths, cfgs: Vec<String>, externs: Externs,
94                 input: Input, triple: Option<String>)
95                 -> (clean::Crate, CrateAnalysis) {
96
97     // Parse, resolve, and typecheck the given crate.
98
99     let cpath = match input {
100         Input::File(ref p) => Some(p.clone()),
101         _ => None
102     };
103
104     let warning_lint = lint::builtin::WARNINGS.name_lower();
105
106     let sessopts = config::Options {
107         maybe_sysroot: None,
108         search_paths: search_paths,
109         crate_types: vec!(config::CrateTypeRlib),
110         lint_opts: vec!((warning_lint, lint::Allow)),
111         lint_cap: Some(lint::Allow),
112         externs: externs,
113         target_triple: triple.unwrap_or(config::host_triple().to_string()),
114         cfg: config::parse_cfgspecs(cfgs),
115         // Ensure that rustdoc works even if rustc is feature-staged
116         unstable_features: UnstableFeatures::Allow,
117         ..config::basic_options().clone()
118     };
119
120     let codemap = Rc::new(codemap::CodeMap::new());
121     let diagnostic_handler = errors::Handler::with_tty_emitter(ColorConfig::Auto,
122                                                                None,
123                                                                true,
124                                                                false,
125                                                                codemap.clone());
126
127     let cstore = Rc::new(CStore::new(token::get_ident_interner()));
128     let sess = session::build_session_(sessopts, cpath, diagnostic_handler,
129                                        codemap, cstore.clone());
130     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
131
132     let mut cfg = config::build_configuration(&sess);
133     target_features::add_configuration(&mut cfg, &sess);
134
135     let krate = driver::phase_1_parse_input(&sess, cfg, &input);
136
137     let name = link::find_crate_name(Some(&sess), &krate.attrs,
138                                      &input);
139
140     let krate = driver::phase_2_configure_and_expand(&sess, &cstore, krate, &name, None)
141                     .expect("phase_2_configure_and_expand aborted in rustdoc!");
142
143     let krate = driver::assign_node_ids(&sess, krate);
144     // Lower ast -> hir.
145     let lcx = LoweringContext::new(&sess, Some(&krate));
146     let mut hir_forest = hir_map::Forest::new(lower_crate(&lcx, &krate));
147     let arenas = ty::CtxtArenas::new();
148     let hir_map = driver::make_map(&sess, &mut hir_forest);
149
150     driver::phase_3_run_analysis_passes(&sess,
151                                         &cstore,
152                                         hir_map,
153                                         &arenas,
154                                         &name,
155                                         resolve::MakeGlobMap::No,
156                                         |tcx, _, analysis| {
157         let _ignore = tcx.dep_graph.in_ignore();
158         let ty::CrateAnalysis { access_levels, .. } = analysis;
159
160         // Convert from a NodeId set to a DefId set since we don't always have easy access
161         // to the map from defid -> nodeid
162         let access_levels = AccessLevels {
163             map: access_levels.map.into_iter()
164                                   .map(|(k, v)| (tcx.map.local_def_id(k), v))
165                                   .collect()
166         };
167
168         let ctxt = DocContext {
169             map: &tcx.map,
170             maybe_typed: Typed(tcx),
171             input: input,
172             external_traits: RefCell::new(Some(HashMap::new())),
173             external_typarams: RefCell::new(Some(HashMap::new())),
174             external_paths: RefCell::new(Some(HashMap::new())),
175             inlined: RefCell::new(Some(HashSet::new())),
176             populated_crate_impls: RefCell::new(HashSet::new()),
177             deref_trait_did: Cell::new(None),
178         };
179         debug!("crate: {:?}", ctxt.map.krate());
180
181         let mut analysis = CrateAnalysis {
182             access_levels: access_levels,
183             external_paths: RefCell::new(None),
184             external_typarams: RefCell::new(None),
185             inlined: RefCell::new(None),
186             deref_trait_did: None,
187         };
188
189         let krate = {
190             let mut v = RustdocVisitor::new(&ctxt, Some(&analysis));
191             v.visit(ctxt.map.krate());
192             v.clean(&ctxt)
193         };
194
195         let external_paths = ctxt.external_paths.borrow_mut().take();
196         *analysis.external_paths.borrow_mut() = external_paths;
197         let map = ctxt.external_typarams.borrow_mut().take();
198         *analysis.external_typarams.borrow_mut() = map;
199         let map = ctxt.inlined.borrow_mut().take();
200         *analysis.inlined.borrow_mut() = map;
201         analysis.deref_trait_did = ctxt.deref_trait_did.get();
202         (krate, analysis)
203     })
204 }