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