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