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