]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/core.rs
Rollup merge of #47439 - eddyb:issue-45662, r=nagisa
[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::creader::CrateLoader;
24 use rustc_metadata::cstore::CStore;
25
26 use syntax::ast::NodeId;
27 use syntax::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::markdown::RenderType;
41 use html::render::RenderInfo;
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, 'rcx: 'a> {
49     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
50     pub resolver: &'a RefCell<resolve::Resolver<'rcx>>,
51     /// The stack of module NodeIds up till this point
52     pub mod_ids: RefCell<Vec<NodeId>>,
53     pub populated_all_crate_impls: Cell<bool>,
54     // Note that external items for which `doc(hidden)` applies to are shown as
55     // non-reachable while local items aren't. This is because we're reusing
56     // the access levels from crateanalysis.
57     /// Later on moved into `clean::Crate`
58     pub access_levels: RefCell<AccessLevels<DefId>>,
59     /// Later on moved into `html::render::CACHE_KEY`
60     pub renderinfo: RefCell<RenderInfo>,
61     /// Later on moved through `clean::Crate` into `html::render::CACHE_KEY`
62     pub external_traits: RefCell<FxHashMap<DefId, clean::Trait>>,
63     /// Which markdown renderer to use when extracting links.
64     pub render_type: RenderType,
65
66     // The current set of type and lifetime substitutions,
67     // for expanding type aliases at the HIR level:
68
69     /// Table type parameter definition -> substituted type
70     pub ty_substs: RefCell<FxHashMap<Def, clean::Type>>,
71     /// Table node id of lifetime parameter definition -> substituted lifetime
72     pub lt_substs: RefCell<FxHashMap<DefId, clean::Lifetime>>,
73 }
74
75 impl<'a, 'tcx, 'rcx> DocContext<'a, 'tcx, 'rcx> {
76     pub fn sess(&self) -> &session::Session {
77         &self.tcx.sess
78     }
79
80     /// Call the closure with the given parameters set as
81     /// the substitutions for a type alias' RHS.
82     pub fn enter_alias<F, R>(&self,
83                              ty_substs: FxHashMap<Def, clean::Type>,
84                              lt_substs: FxHashMap<DefId, clean::Lifetime>,
85                              f: F) -> R
86     where F: FnOnce() -> R {
87         let (old_tys, old_lts) =
88             (mem::replace(&mut *self.ty_substs.borrow_mut(), ty_substs),
89              mem::replace(&mut *self.lt_substs.borrow_mut(), lt_substs));
90         let r = f();
91         *self.ty_substs.borrow_mut() = old_tys;
92         *self.lt_substs.borrow_mut() = old_lts;
93         r
94     }
95 }
96
97 pub trait DocAccessLevels {
98     fn is_doc_reachable(&self, did: DefId) -> bool;
99 }
100
101 impl DocAccessLevels for AccessLevels<DefId> {
102     fn is_doc_reachable(&self, did: DefId) -> bool {
103         self.is_public(did)
104     }
105 }
106
107
108 pub fn run_core(search_paths: SearchPaths,
109                 cfgs: Vec<String>,
110                 externs: config::Externs,
111                 input: Input,
112                 triple: Option<String>,
113                 maybe_sysroot: Option<PathBuf>,
114                 allow_warnings: bool,
115                 force_unstable_if_unmarked: bool,
116                 render_type: RenderType) -> (clean::Crate, RenderInfo)
117 {
118     // Parse, resolve, and typecheck the given crate.
119
120     let cpath = match input {
121         Input::File(ref p) => Some(p.clone()),
122         _ => None
123     };
124
125     let warning_lint = lint::builtin::WARNINGS.name_lower();
126
127     let sessopts = config::Options {
128         maybe_sysroot,
129         search_paths,
130         crate_types: vec![config::CrateTypeRlib],
131         lint_opts: if !allow_warnings { vec![(warning_lint, lint::Allow)] } else { vec![] },
132         lint_cap: Some(lint::Allow),
133         externs,
134         target_triple: triple.unwrap_or(config::host_triple().to_string()),
135         // Ensure that rustdoc works even if rustc is feature-staged
136         unstable_features: UnstableFeatures::Allow,
137         actually_rustdoc: true,
138         debugging_opts: config::DebuggingOptions {
139             force_unstable_if_unmarked,
140             ..config::basic_debugging_options()
141         },
142         ..config::basic_options().clone()
143     };
144
145     let codemap = Rc::new(codemap::CodeMap::new(sessopts.file_path_mapping()));
146     let diagnostic_handler = errors::Handler::with_tty_emitter(ColorConfig::Auto,
147                                                                true,
148                                                                false,
149                                                                Some(codemap.clone()));
150
151     let mut sess = session::build_session_(
152         sessopts, cpath, diagnostic_handler, codemap,
153     );
154     let trans = rustc_trans::LlvmTransCrate::new(&sess);
155     let cstore = Rc::new(CStore::new(trans.metadata_loader()));
156     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
157
158     let mut cfg = config::build_configuration(&sess, config::parse_cfgspecs(cfgs));
159     target_features::add_configuration(&mut cfg, &sess, &*trans);
160     sess.parse_sess.config = cfg;
161
162     let control = &driver::CompileController::basic();
163
164     let krate = panictry!(driver::phase_1_parse_input(control, &sess, &input));
165
166     let name = ::rustc_trans_utils::link::find_crate_name(Some(&sess), &krate.attrs, &input);
167
168     let mut crate_loader = CrateLoader::new(&sess, &cstore, &name);
169
170     let resolver_arenas = resolve::Resolver::arenas();
171     let result = driver::phase_2_configure_and_expand_inner(&sess,
172                                                       &cstore,
173                                                       krate,
174                                                       None,
175                                                       &name,
176                                                       None,
177                                                       resolve::MakeGlobMap::No,
178                                                       &resolver_arenas,
179                                                       &mut crate_loader,
180                                                       |_| Ok(()));
181     let driver::InnerExpansionResult {
182         mut hir_forest,
183         resolver,
184         ..
185     } = abort_on_err(result, &sess);
186
187     // We need to hold on to the complete resolver, so we clone everything
188     // for the analysis passes to use. Suboptimal, but necessary in the
189     // current architecture.
190     let defs = resolver.definitions.clone();
191     let resolutions = ty::Resolutions {
192         freevars: resolver.freevars.clone(),
193         export_map: resolver.export_map.clone(),
194         trait_map: resolver.trait_map.clone(),
195         maybe_unused_trait_imports: resolver.maybe_unused_trait_imports.clone(),
196         maybe_unused_extern_crates: resolver.maybe_unused_extern_crates.clone(),
197     };
198     let analysis = ty::CrateAnalysis {
199         access_levels: Rc::new(AccessLevels::default()),
200         name: name.to_string(),
201         glob_map: if resolver.make_glob_map { Some(resolver.glob_map.clone()) } else { None },
202     };
203
204     let arenas = AllArenas::new();
205     let hir_map = hir_map::map_crate(&sess, &*cstore, &mut hir_forest, &defs);
206     let output_filenames = driver::build_output_filenames(&input,
207                                                           &None,
208                                                           &None,
209                                                           &[],
210                                                           &sess);
211
212     let resolver = RefCell::new(resolver);
213
214     abort_on_err(driver::phase_3_run_analysis_passes(&*trans,
215                                                      control,
216                                                      &sess,
217                                                      &*cstore,
218                                                      hir_map,
219                                                      analysis,
220                                                      resolutions,
221                                                      &arenas,
222                                                      &name,
223                                                      &output_filenames,
224                                                      |tcx, analysis, _, result| {
225         if let Err(_) = result {
226             sess.fatal("Compilation failed, aborting rustdoc");
227         }
228
229         let ty::CrateAnalysis { access_levels, .. } = analysis;
230
231         // Convert from a NodeId set to a DefId set since we don't always have easy access
232         // to the map from defid -> nodeid
233         let access_levels = AccessLevels {
234             map: access_levels.map.iter()
235                                   .map(|(&k, &v)| (tcx.hir.local_def_id(k), v))
236                                   .collect()
237         };
238
239         let ctxt = DocContext {
240             tcx,
241             resolver: &resolver,
242             populated_all_crate_impls: Cell::new(false),
243             access_levels: RefCell::new(access_levels),
244             external_traits: Default::default(),
245             renderinfo: Default::default(),
246             render_type,
247             ty_substs: Default::default(),
248             lt_substs: Default::default(),
249             mod_ids: Default::default(),
250         };
251         debug!("crate: {:?}", tcx.hir.krate());
252
253         let krate = {
254             let mut v = RustdocVisitor::new(&*cstore, &ctxt);
255             v.visit(tcx.hir.krate());
256             v.clean(&ctxt)
257         };
258
259         (krate, ctxt.renderinfo.into_inner())
260     }), &sess)
261 }