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