]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/core.rs
Rollup merge of #52594 - Mark-Simulacrum:error-index-stage0, r=alexcrichton
[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::{self, driver, target_features, abort_on_err};
13 use rustc::session::{self, config};
14 use rustc::hir::def_id::{DefId, CrateNum};
15 use rustc::hir::def::Def;
16 use rustc::middle::cstore::CrateStore;
17 use rustc::middle::privacy::AccessLevels;
18 use rustc::ty::{self, TyCtxt, AllArenas};
19 use rustc::hir::map as hir_map;
20 use rustc::lint::{self, LintPass};
21 use rustc::session::config::ErrorOutputType;
22 use rustc::util::nodemap::{FxHashMap, FxHashSet};
23 use rustc_resolve as resolve;
24 use rustc_metadata::creader::CrateLoader;
25 use rustc_metadata::cstore::CStore;
26 use rustc_target::spec::TargetTriple;
27
28 use syntax::ast::{Name, NodeId};
29 use syntax::codemap;
30 use syntax::edition::Edition;
31 use syntax::feature_gate::UnstableFeatures;
32 use syntax::json::JsonEmitter;
33 use errors;
34 use errors::emitter::{Emitter, EmitterWriter};
35
36 use std::cell::{RefCell, Cell};
37 use std::mem;
38 use rustc_data_structures::sync::{self, Lrc};
39 use std::rc::Rc;
40 use std::path::PathBuf;
41
42 use visit_ast::RustdocVisitor;
43 use clean;
44 use clean::Clean;
45 use html::render::RenderInfo;
46
47 pub use rustc::session::config::{Input, CodegenOptions};
48 pub use rustc::session::search_paths::SearchPaths;
49
50 pub type ExternalPaths = FxHashMap<DefId, (Vec<String>, clean::TypeKind)>;
51
52 pub struct DocContext<'a, 'tcx: 'a, 'rcx: 'a> {
53     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
54     pub resolver: &'a RefCell<resolve::Resolver<'rcx>>,
55     /// The stack of module NodeIds up till this point
56     pub mod_ids: RefCell<Vec<NodeId>>,
57     pub crate_name: Option<String>,
58     pub cstore: Rc<CrateStore>,
59     pub populated_all_crate_impls: Cell<bool>,
60     // Note that external items for which `doc(hidden)` applies to are shown as
61     // non-reachable while local items aren't. This is because we're reusing
62     // the access levels from crateanalysis.
63     /// Later on moved into `clean::Crate`
64     pub access_levels: RefCell<AccessLevels<DefId>>,
65     /// Later on moved into `html::render::CACHE_KEY`
66     pub renderinfo: RefCell<RenderInfo>,
67     /// Later on moved through `clean::Crate` into `html::render::CACHE_KEY`
68     pub external_traits: RefCell<FxHashMap<DefId, clean::Trait>>,
69     /// Used while populating `external_traits` to ensure we don't process the same trait twice at
70     /// the same time.
71     pub active_extern_traits: RefCell<Vec<DefId>>,
72     // The current set of type and lifetime substitutions,
73     // for expanding type aliases at the HIR level:
74
75     /// Table type parameter definition -> substituted type
76     pub ty_substs: RefCell<FxHashMap<Def, clean::Type>>,
77     /// Table node id of lifetime parameter definition -> substituted lifetime
78     pub lt_substs: RefCell<FxHashMap<DefId, clean::Lifetime>>,
79     /// Table DefId of `impl Trait` in argument position -> bounds
80     pub impl_trait_bounds: RefCell<FxHashMap<DefId, Vec<clean::GenericBound>>>,
81     pub send_trait: Option<DefId>,
82     pub fake_def_ids: RefCell<FxHashMap<CrateNum, DefId>>,
83     pub all_fake_def_ids: RefCell<FxHashSet<DefId>>,
84     /// Maps (type_id, trait_id) -> auto trait impl
85     pub generated_synthetics: RefCell<FxHashSet<(DefId, DefId)>>,
86     pub current_item_name: RefCell<Option<Name>>,
87 }
88
89 impl<'a, 'tcx, 'rcx> DocContext<'a, 'tcx, 'rcx> {
90     pub fn sess(&self) -> &session::Session {
91         &self.tcx.sess
92     }
93
94     /// Call the closure with the given parameters set as
95     /// the substitutions for a type alias' RHS.
96     pub fn enter_alias<F, R>(&self,
97                              ty_substs: FxHashMap<Def, clean::Type>,
98                              lt_substs: FxHashMap<DefId, clean::Lifetime>,
99                              f: F) -> R
100     where F: FnOnce() -> R {
101         let (old_tys, old_lts) =
102             (mem::replace(&mut *self.ty_substs.borrow_mut(), ty_substs),
103              mem::replace(&mut *self.lt_substs.borrow_mut(), lt_substs));
104         let r = f();
105         *self.ty_substs.borrow_mut() = old_tys;
106         *self.lt_substs.borrow_mut() = old_lts;
107         r
108     }
109 }
110
111 pub trait DocAccessLevels {
112     fn is_doc_reachable(&self, did: DefId) -> bool;
113 }
114
115 impl DocAccessLevels for AccessLevels<DefId> {
116     fn is_doc_reachable(&self, did: DefId) -> bool {
117         self.is_public(did)
118     }
119 }
120
121 /// Creates a new diagnostic `Handler` that can be used to emit warnings and errors.
122 ///
123 /// If the given `error_format` is `ErrorOutputType::Json` and no `CodeMap` is given, a new one
124 /// will be created for the handler.
125 pub fn new_handler(error_format: ErrorOutputType, codemap: Option<Lrc<codemap::CodeMap>>)
126     -> errors::Handler
127 {
128     // rustdoc doesn't override (or allow to override) anything from this that is relevant here, so
129     // stick to the defaults
130     let sessopts = config::basic_options();
131     let emitter: Box<dyn Emitter + sync::Send> = match error_format {
132         ErrorOutputType::HumanReadable(color_config) => Box::new(
133             EmitterWriter::stderr(
134                 color_config,
135                 codemap.map(|cm| cm as _),
136                 false,
137                 sessopts.debugging_opts.teach,
138             ).ui_testing(sessopts.debugging_opts.ui_testing)
139         ),
140         ErrorOutputType::Json(pretty) => {
141             let codemap = codemap.unwrap_or_else(
142                 || Lrc::new(codemap::CodeMap::new(sessopts.file_path_mapping())));
143             Box::new(
144                 JsonEmitter::stderr(
145                     None,
146                     codemap,
147                     pretty,
148                 ).ui_testing(sessopts.debugging_opts.ui_testing)
149             )
150         },
151         ErrorOutputType::Short(color_config) => Box::new(
152             EmitterWriter::stderr(
153                 color_config,
154                 codemap.map(|cm| cm as _),
155                 true,
156                 false)
157         ),
158     };
159
160     errors::Handler::with_emitter_and_flags(
161         emitter,
162         errors::HandlerFlags {
163             can_emit_warnings: true,
164             treat_err_as_bug: false,
165             external_macro_backtrace: false,
166             ..Default::default()
167         },
168     )
169 }
170
171 pub fn run_core(search_paths: SearchPaths,
172                 cfgs: Vec<String>,
173                 externs: config::Externs,
174                 input: Input,
175                 triple: Option<TargetTriple>,
176                 maybe_sysroot: Option<PathBuf>,
177                 allow_warnings: bool,
178                 crate_name: Option<String>,
179                 force_unstable_if_unmarked: bool,
180                 edition: Edition,
181                 cg: CodegenOptions,
182                 error_format: ErrorOutputType,
183                 cmd_lints: Vec<(String, lint::Level)>,
184                 lint_cap: Option<lint::Level>,
185                 describe_lints: bool) -> (clean::Crate, RenderInfo)
186 {
187     // Parse, resolve, and typecheck the given crate.
188
189     let cpath = match input {
190         Input::File(ref p) => Some(p.clone()),
191         _ => None
192     };
193
194     let intra_link_resolution_failure_name = lint::builtin::INTRA_DOC_LINK_RESOLUTION_FAILURE.name;
195     let warnings_lint_name = lint::builtin::WARNINGS.name;
196     let missing_docs = rustc_lint::builtin::MISSING_DOCS.name;
197
198     // In addition to those specific lints, we also need to whitelist those given through
199     // command line, otherwise they'll get ignored and we don't want that.
200     let mut whitelisted_lints = vec![warnings_lint_name.to_owned(),
201                                      intra_link_resolution_failure_name.to_owned(),
202                                      missing_docs.to_owned()];
203
204     for (lint, _) in &cmd_lints {
205         whitelisted_lints.push(lint.clone());
206     }
207
208     let lints = lint::builtin::HardwiredLints.get_lints()
209                     .into_iter()
210                     .chain(rustc_lint::SoftLints.get_lints().into_iter())
211                     .filter_map(|lint| {
212                         if lint.name == warnings_lint_name ||
213                            lint.name == intra_link_resolution_failure_name {
214                             None
215                         } else {
216                             Some((lint.name_lower(), lint::Allow))
217                         }
218                     })
219                     .chain(cmd_lints.into_iter())
220                     .collect::<Vec<_>>();
221
222     let host_triple = TargetTriple::from_triple(config::host_triple());
223     // plays with error output here!
224     let sessopts = config::Options {
225         maybe_sysroot,
226         search_paths,
227         crate_types: vec![config::CrateTypeRlib],
228         lint_opts: if !allow_warnings {
229             lints
230         } else {
231             vec![]
232         },
233         lint_cap: Some(lint_cap.unwrap_or_else(|| lint::Forbid)),
234         cg,
235         externs,
236         target_triple: triple.unwrap_or(host_triple),
237         // Ensure that rustdoc works even if rustc is feature-staged
238         unstable_features: UnstableFeatures::Allow,
239         actually_rustdoc: true,
240         debugging_opts: config::DebuggingOptions {
241             force_unstable_if_unmarked,
242             ..config::basic_debugging_options()
243         },
244         error_format,
245         edition,
246         describe_lints,
247         ..config::basic_options()
248     };
249     driver::spawn_thread_pool(sessopts, move |sessopts| {
250         let codemap = Lrc::new(codemap::CodeMap::new(sessopts.file_path_mapping()));
251         let diagnostic_handler = new_handler(error_format, Some(codemap.clone()));
252
253         let mut sess = session::build_session_(
254             sessopts, cpath, diagnostic_handler, codemap,
255         );
256
257         lint::builtin::HardwiredLints.get_lints()
258                                      .into_iter()
259                                      .chain(rustc_lint::SoftLints.get_lints().into_iter())
260                                      .filter_map(|lint| {
261                                          // We don't want to whitelist *all* lints so let's
262                                          // ignore those ones.
263                                          if whitelisted_lints.iter().any(|l| &lint.name == l) {
264                                              None
265                                          } else {
266                                              Some(lint)
267                                          }
268                                      })
269                                      .for_each(|l| {
270                                          sess.driver_lint_caps.insert(lint::LintId::of(l),
271                                                                       lint::Allow);
272                                      });
273
274         let codegen_backend = rustc_driver::get_codegen_backend(&sess);
275         let cstore = Rc::new(CStore::new(codegen_backend.metadata_loader()));
276         rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
277
278         let mut cfg = config::build_configuration(&sess, config::parse_cfgspecs(cfgs));
279         target_features::add_configuration(&mut cfg, &sess, &*codegen_backend);
280         sess.parse_sess.config = cfg;
281
282         let control = &driver::CompileController::basic();
283
284         let krate = panictry!(driver::phase_1_parse_input(control, &sess, &input));
285
286         let name = match crate_name {
287             Some(ref crate_name) => crate_name.clone(),
288             None => ::rustc_codegen_utils::link::find_crate_name(Some(&sess), &krate.attrs, &input),
289         };
290
291         let mut crate_loader = CrateLoader::new(&sess, &cstore, &name);
292
293         let resolver_arenas = resolve::Resolver::arenas();
294         let result = driver::phase_2_configure_and_expand_inner(&sess,
295                                                         &cstore,
296                                                         krate,
297                                                         None,
298                                                         &name,
299                                                         None,
300                                                         resolve::MakeGlobMap::No,
301                                                         &resolver_arenas,
302                                                         &mut crate_loader,
303                                                         |_| Ok(()));
304         let driver::InnerExpansionResult {
305             mut hir_forest,
306             mut resolver,
307             ..
308         } = abort_on_err(result, &sess);
309
310         resolver.ignore_extern_prelude_feature = true;
311
312         // We need to hold on to the complete resolver, so we clone everything
313         // for the analysis passes to use. Suboptimal, but necessary in the
314         // current architecture.
315         let defs = resolver.definitions.clone();
316         let resolutions = ty::Resolutions {
317             freevars: resolver.freevars.clone(),
318             export_map: resolver.export_map.clone(),
319             trait_map: resolver.trait_map.clone(),
320             maybe_unused_trait_imports: resolver.maybe_unused_trait_imports.clone(),
321             maybe_unused_extern_crates: resolver.maybe_unused_extern_crates.clone(),
322         };
323         let analysis = ty::CrateAnalysis {
324             access_levels: Lrc::new(AccessLevels::default()),
325             name: name.to_string(),
326             glob_map: if resolver.make_glob_map { Some(resolver.glob_map.clone()) } else { None },
327         };
328
329         let arenas = AllArenas::new();
330         let hir_map = hir_map::map_crate(&sess, &*cstore, &mut hir_forest, &defs);
331         let output_filenames = driver::build_output_filenames(&input,
332                                                             &None,
333                                                             &None,
334                                                             &[],
335                                                             &sess);
336
337         let resolver = RefCell::new(resolver);
338         abort_on_err(driver::phase_3_run_analysis_passes(&*codegen_backend,
339                                                         control,
340                                                         &sess,
341                                                         &*cstore,
342                                                         hir_map,
343                                                         analysis,
344                                                         resolutions,
345                                                         &arenas,
346                                                         &name,
347                                                         &output_filenames,
348                                                         |tcx, analysis, _, result| {
349             if let Err(_) = result {
350                 sess.fatal("Compilation failed, aborting rustdoc");
351             }
352
353             let ty::CrateAnalysis { access_levels, .. } = analysis;
354
355             // Convert from a NodeId set to a DefId set since we don't always have easy access
356             // to the map from defid -> nodeid
357             let access_levels = AccessLevels {
358                 map: access_levels.map.iter()
359                                     .map(|(&k, &v)| (tcx.hir.local_def_id(k), v))
360                                     .collect()
361             };
362
363             let send_trait = if crate_name == Some("core".to_string()) {
364                 clean::get_trait_def_id(&tcx, &["marker", "Send"], true)
365             } else {
366                 clean::get_trait_def_id(&tcx, &["core", "marker", "Send"], false)
367             };
368
369             let ctxt = DocContext {
370                 tcx,
371                 resolver: &resolver,
372                 crate_name,
373                 cstore: cstore.clone(),
374                 populated_all_crate_impls: Cell::new(false),
375                 access_levels: RefCell::new(access_levels),
376                 external_traits: Default::default(),
377                 active_extern_traits: Default::default(),
378                 renderinfo: Default::default(),
379                 ty_substs: Default::default(),
380                 lt_substs: Default::default(),
381                 impl_trait_bounds: Default::default(),
382                 mod_ids: Default::default(),
383                 send_trait: send_trait,
384                 fake_def_ids: RefCell::new(FxHashMap()),
385                 all_fake_def_ids: RefCell::new(FxHashSet()),
386                 generated_synthetics: RefCell::new(FxHashSet()),
387                 current_item_name: RefCell::new(None),
388             };
389             debug!("crate: {:?}", tcx.hir.krate());
390
391             let krate = {
392                 let mut v = RustdocVisitor::new(&*cstore, &ctxt);
393                 v.visit(tcx.hir.krate());
394                 v.clean(&ctxt)
395             };
396
397             (krate, ctxt.renderinfo.into_inner())
398         }), &sess)
399     })
400 }