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