]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/core.rs
rustc: factor most DefId-containing variants out of Def and into DefKind.
[rust.git] / src / librustdoc / core.rs
1 use rustc_lint;
2 use rustc::session::{self, config};
3 use rustc::hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CrateNum, LOCAL_CRATE};
4 use rustc::hir::def::Def;
5 use rustc::hir::HirId;
6 use rustc::middle::cstore::CrateStore;
7 use rustc::middle::privacy::AccessLevels;
8 use rustc::ty::{Ty, TyCtxt};
9 use rustc::lint::{self, LintPass};
10 use rustc::session::config::ErrorOutputType;
11 use rustc::session::DiagnosticOutput;
12 use rustc::util::nodemap::{FxHashMap, FxHashSet};
13 use rustc_interface::interface;
14 use rustc_driver::abort_on_err;
15 use rustc_resolve as resolve;
16 use rustc_metadata::cstore::CStore;
17 use rustc_target::spec::TargetTriple;
18
19 use syntax::source_map;
20 use syntax::feature_gate::UnstableFeatures;
21 use syntax::json::JsonEmitter;
22 use errors;
23 use errors::emitter::{Emitter, EmitterWriter};
24 use parking_lot::ReentrantMutex;
25
26 use std::cell::RefCell;
27 use std::mem;
28 use rustc_data_structures::sync::{self, Lrc};
29 use std::sync::Arc;
30 use std::rc::Rc;
31
32 use crate::visit_ast::RustdocVisitor;
33 use crate::config::{Options as RustdocOptions, RenderOptions};
34 use crate::clean;
35 use crate::clean::{Clean, MAX_DEF_ID, AttributesExt};
36 use crate::html::render::RenderInfo;
37
38 use crate::passes;
39
40 pub use rustc::session::config::{Input, Options, CodegenOptions};
41 pub use rustc::session::search_paths::SearchPath;
42
43 pub type ExternalPaths = FxHashMap<DefId, (Vec<String>, clean::TypeKind)>;
44
45 pub struct DocContext<'tcx> {
46
47     pub tcx: TyCtxt<'tcx, 'tcx, 'tcx>,
48     pub resolver: Rc<Option<RefCell<interface::BoxedResolver>>>,
49     /// The stack of module NodeIds up till this point
50     pub crate_name: Option<String>,
51     pub cstore: Lrc<CStore>,
52     /// Later on moved into `html::render::CACHE_KEY`
53     pub renderinfo: RefCell<RenderInfo>,
54     /// Later on moved through `clean::Crate` into `html::render::CACHE_KEY`
55     pub external_traits: Arc<ReentrantMutex<RefCell<FxHashMap<DefId, clean::Trait>>>>,
56     /// Used while populating `external_traits` to ensure we don't process the same trait twice at
57     /// the same time.
58     pub active_extern_traits: RefCell<Vec<DefId>>,
59     // The current set of type and lifetime substitutions,
60     // for expanding type aliases at the HIR level:
61
62     /// Table type parameter definition -> substituted type
63     pub ty_substs: RefCell<FxHashMap<Def, clean::Type>>,
64     /// Table `NodeId` of lifetime parameter definition -> substituted lifetime
65     pub lt_substs: RefCell<FxHashMap<DefId, clean::Lifetime>>,
66     /// Table node id of const parameter definition -> substituted const
67     pub ct_substs: RefCell<FxHashMap<Def, clean::Constant>>,
68     /// Table DefId of `impl Trait` in argument position -> bounds
69     pub impl_trait_bounds: RefCell<FxHashMap<DefId, Vec<clean::GenericBound>>>,
70     pub send_trait: Option<DefId>,
71     pub fake_def_ids: RefCell<FxHashMap<CrateNum, DefId>>,
72     pub all_fake_def_ids: RefCell<FxHashSet<DefId>>,
73     /// Auto-trait or blanket impls processed so far, as `(self_ty, trait_def_id)`.
74     // FIXME(eddyb) make this a `ty::TraitRef<'tcx>` set.
75     pub generated_synthetics: RefCell<FxHashSet<(Ty<'tcx>, DefId)>>,
76     pub all_traits: Vec<DefId>,
77 }
78
79 impl<'tcx> DocContext<'tcx> {
80     pub fn sess(&self) -> &session::Session {
81         &self.tcx.sess
82     }
83
84     pub fn enter_resolver<F, R>(&self, f: F) -> R
85     where F: FnOnce(&mut resolve::Resolver<'_>) -> R {
86         let resolver = &*self.resolver;
87         let resolver = resolver.as_ref().unwrap();
88         resolver.borrow_mut().access(f)
89     }
90
91     /// Call the closure with the given parameters set as
92     /// the substitutions for a type alias' RHS.
93     pub fn enter_alias<F, R>(&self,
94                              ty_substs: FxHashMap<Def, clean::Type>,
95                              lt_substs: FxHashMap<DefId, clean::Lifetime>,
96                              ct_substs: FxHashMap<Def, clean::Constant>,
97                              f: F) -> R
98     where F: FnOnce() -> R {
99         let (old_tys, old_lts, old_cts) = (
100             mem::replace(&mut *self.ty_substs.borrow_mut(), ty_substs),
101             mem::replace(&mut *self.lt_substs.borrow_mut(), lt_substs),
102             mem::replace(&mut *self.ct_substs.borrow_mut(), ct_substs),
103         );
104         let r = f();
105         *self.ty_substs.borrow_mut() = old_tys;
106         *self.lt_substs.borrow_mut() = old_lts;
107         *self.ct_substs.borrow_mut() = old_cts;
108         r
109     }
110
111     // This is an ugly hack, but it's the simplest way to handle synthetic impls without greatly
112     // refactoring either librustdoc or librustc. In particular, allowing new DefIds to be
113     // registered after the AST is constructed would require storing the defid mapping in a
114     // RefCell, decreasing the performance for normal compilation for very little gain.
115     //
116     // Instead, we construct 'fake' def ids, which start immediately after the last DefId in
117     // DefIndexAddressSpace::Low. In the Debug impl for clean::Item, we explicitly check for fake
118     // def ids, as we'll end up with a panic if we use the DefId Debug impl for fake DefIds
119     pub fn next_def_id(&self, crate_num: CrateNum) -> DefId {
120         let start_def_id = {
121             let next_id = if crate_num == LOCAL_CRATE {
122                 self.tcx
123                     .hir()
124                     .definitions()
125                     .def_path_table()
126                     .next_id(DefIndexAddressSpace::Low)
127             } else {
128                 self.cstore
129                     .def_path_table(crate_num)
130                     .next_id(DefIndexAddressSpace::Low)
131             };
132
133             DefId {
134                 krate: crate_num,
135                 index: next_id,
136             }
137         };
138
139         let mut fake_ids = self.fake_def_ids.borrow_mut();
140
141         let def_id = fake_ids.entry(crate_num).or_insert(start_def_id).clone();
142         fake_ids.insert(
143             crate_num,
144             DefId {
145                 krate: crate_num,
146                 index: DefIndex::from_array_index(
147                     def_id.index.as_array_index() + 1,
148                     def_id.index.address_space(),
149                 ),
150             },
151         );
152
153         MAX_DEF_ID.with(|m| {
154             m.borrow_mut()
155                 .entry(def_id.krate.clone())
156                 .or_insert(start_def_id);
157         });
158
159         self.all_fake_def_ids.borrow_mut().insert(def_id);
160
161         def_id.clone()
162     }
163
164     /// Like the function of the same name on the HIR map, but skips calling it on fake DefIds.
165     /// (This avoids a slice-index-out-of-bounds panic.)
166     pub fn as_local_hir_id(&self, def_id: DefId) -> Option<HirId> {
167         if self.all_fake_def_ids.borrow().contains(&def_id) {
168             None
169         } else {
170             self.tcx.hir().as_local_hir_id(def_id)
171         }
172     }
173 }
174
175 pub trait DocAccessLevels {
176     fn is_doc_reachable(&self, did: DefId) -> bool;
177 }
178
179 impl DocAccessLevels for AccessLevels<DefId> {
180     fn is_doc_reachable(&self, did: DefId) -> bool {
181         self.is_public(did)
182     }
183 }
184
185 /// Creates a new diagnostic `Handler` that can be used to emit warnings and errors.
186 ///
187 /// If the given `error_format` is `ErrorOutputType::Json` and no `SourceMap` is given, a new one
188 /// will be created for the handler.
189 pub fn new_handler(error_format: ErrorOutputType,
190                    source_map: Option<Lrc<source_map::SourceMap>>,
191                    treat_err_as_bug: Option<usize>,
192                    ui_testing: bool,
193 ) -> errors::Handler {
194     // rustdoc doesn't override (or allow to override) anything from this that is relevant here, so
195     // stick to the defaults
196     let sessopts = Options::default();
197     let emitter: Box<dyn Emitter + sync::Send> = match error_format {
198         ErrorOutputType::HumanReadable(kind) => {
199             let (short, color_config) = kind.unzip();
200             Box::new(
201                 EmitterWriter::stderr(
202                     color_config,
203                     source_map.map(|cm| cm as _),
204                     short,
205                     sessopts.debugging_opts.teach,
206                 ).ui_testing(ui_testing)
207             )
208         },
209         ErrorOutputType::Json { pretty, json_rendered } => {
210             let source_map = source_map.unwrap_or_else(
211                 || Lrc::new(source_map::SourceMap::new(sessopts.file_path_mapping())));
212             Box::new(
213                 JsonEmitter::stderr(
214                     None,
215                     source_map,
216                     pretty,
217                     json_rendered,
218                 ).ui_testing(ui_testing)
219             )
220         },
221     };
222
223     errors::Handler::with_emitter_and_flags(
224         emitter,
225         errors::HandlerFlags {
226             can_emit_warnings: true,
227             treat_err_as_bug,
228             report_delayed_bugs: false,
229             external_macro_backtrace: false,
230             ..Default::default()
231         },
232     )
233 }
234
235 pub fn run_core(options: RustdocOptions) -> (clean::Crate, RenderInfo, RenderOptions, Vec<String>) {
236     // Parse, resolve, and typecheck the given crate.
237
238     let RustdocOptions {
239         input,
240         crate_name,
241         error_format,
242         libs,
243         externs,
244         cfgs,
245         codegen_options,
246         debugging_options,
247         target,
248         edition,
249         maybe_sysroot,
250         lint_opts,
251         describe_lints,
252         lint_cap,
253         mut default_passes,
254         mut manual_passes,
255         display_warnings,
256         render_options,
257         ..
258     } = options;
259
260     let cpath = Some(input.clone());
261     let input = Input::File(input);
262
263     let intra_link_resolution_failure_name = lint::builtin::INTRA_DOC_LINK_RESOLUTION_FAILURE.name;
264     let warnings_lint_name = lint::builtin::WARNINGS.name;
265     let missing_docs = rustc_lint::builtin::MISSING_DOCS.name;
266     let missing_doc_example = rustc_lint::builtin::MISSING_DOC_CODE_EXAMPLES.name;
267     let private_doc_tests = rustc_lint::builtin::PRIVATE_DOC_TESTS.name;
268
269     // In addition to those specific lints, we also need to whitelist those given through
270     // command line, otherwise they'll get ignored and we don't want that.
271     let mut whitelisted_lints = vec![warnings_lint_name.to_owned(),
272                                      intra_link_resolution_failure_name.to_owned(),
273                                      missing_docs.to_owned(),
274                                      missing_doc_example.to_owned(),
275                                      private_doc_tests.to_owned()];
276
277     whitelisted_lints.extend(lint_opts.iter().map(|(lint, _)| lint).cloned());
278
279     let lints = || {
280         lint::builtin::HardwiredLints
281             .get_lints()
282             .into_iter()
283             .chain(rustc_lint::SoftLints.get_lints().into_iter())
284     };
285
286     let lint_opts = lints().filter_map(|lint| {
287         if lint.name == warnings_lint_name ||
288             lint.name == intra_link_resolution_failure_name {
289             None
290         } else {
291             Some((lint.name_lower(), lint::Allow))
292         }
293     }).chain(lint_opts.into_iter()).collect::<Vec<_>>();
294
295     let lint_caps = lints().filter_map(|lint| {
296         // We don't want to whitelist *all* lints so let's
297         // ignore those ones.
298         if whitelisted_lints.iter().any(|l| &lint.name == l) {
299             None
300         } else {
301             Some((lint::LintId::of(lint), lint::Allow))
302         }
303     }).collect();
304
305     let host_triple = TargetTriple::from_triple(config::host_triple());
306     // plays with error output here!
307     let sessopts = config::Options {
308         maybe_sysroot,
309         search_paths: libs,
310         crate_types: vec![config::CrateType::Rlib],
311         lint_opts: if !display_warnings {
312             lint_opts
313         } else {
314             vec![]
315         },
316         lint_cap: Some(lint_cap.unwrap_or_else(|| lint::Forbid)),
317         cg: codegen_options,
318         externs,
319         target_triple: target.unwrap_or(host_triple),
320         // Ensure that rustdoc works even if rustc is feature-staged
321         unstable_features: UnstableFeatures::Allow,
322         actually_rustdoc: true,
323         debugging_opts: debugging_options.clone(),
324         error_format,
325         edition,
326         describe_lints,
327         ..Options::default()
328     };
329
330     let config = interface::Config {
331         opts: sessopts,
332         crate_cfg: config::parse_cfgspecs(cfgs),
333         input,
334         input_path: cpath,
335         output_file: None,
336         output_dir: None,
337         file_loader: None,
338         diagnostic_output: DiagnosticOutput::Default,
339         stderr: None,
340         crate_name: crate_name.clone(),
341         lint_caps,
342     };
343
344     interface::run_compiler_in_existing_thread_pool(config, |compiler| {
345         let sess = compiler.session();
346
347         // We need to hold on to the complete resolver, so we cause everything to be
348         // cloned for the analysis passes to use. Suboptimal, but necessary in the
349         // current architecture.
350         let resolver = abort_on_err(compiler.expansion(), sess).peek().1.clone();
351
352         if sess.err_count() > 0 {
353             sess.fatal("Compilation failed, aborting rustdoc");
354         }
355
356         let mut global_ctxt = abort_on_err(compiler.global_ctxt(), sess).take();
357
358         global_ctxt.enter(|tcx| {
359             tcx.analysis(LOCAL_CRATE).ok();
360
361             // Abort if there were any errors so far
362             sess.abort_if_errors();
363
364             let access_levels = tcx.privacy_access_levels(LOCAL_CRATE);
365             // Convert from a HirId set to a DefId set since we don't always have easy access
366             // to the map from defid -> hirid
367             let access_levels = AccessLevels {
368                 map: access_levels.map.iter()
369                                     .map(|(&k, &v)| (tcx.hir().local_def_id_from_hir_id(k), v))
370                                     .collect()
371             };
372
373             let send_trait = if crate_name == Some("core".to_string()) {
374                 clean::path_to_def_local(tcx, &["marker", "Send"])
375             } else {
376                 clean::path_to_def(tcx, &["core", "marker", "Send"])
377             };
378
379             let mut renderinfo = RenderInfo::default();
380             renderinfo.access_levels = access_levels;
381
382             let ctxt = DocContext {
383                 tcx,
384                 resolver,
385                 crate_name,
386                 cstore: compiler.cstore().clone(),
387                 external_traits: Default::default(),
388                 active_extern_traits: Default::default(),
389                 renderinfo: RefCell::new(renderinfo),
390                 ty_substs: Default::default(),
391                 lt_substs: Default::default(),
392                 ct_substs: Default::default(),
393                 impl_trait_bounds: Default::default(),
394                 send_trait: send_trait,
395                 fake_def_ids: Default::default(),
396                 all_fake_def_ids: Default::default(),
397                 generated_synthetics: Default::default(),
398                 all_traits: tcx.all_traits(LOCAL_CRATE).to_vec(),
399             };
400             debug!("crate: {:?}", tcx.hir().krate());
401
402             let mut krate = {
403                 let mut v = RustdocVisitor::new(&ctxt);
404                 v.visit(tcx.hir().krate());
405                 v.clean(&ctxt)
406             };
407
408             fn report_deprecated_attr(name: &str, diag: &errors::Handler) {
409                 let mut msg = diag.struct_warn(&format!("the `#![doc({})]` attribute is \
410                                                          considered deprecated", name));
411                 msg.warn("please see https://github.com/rust-lang/rust/issues/44136");
412
413                 if name == "no_default_passes" {
414                     msg.help("you may want to use `#![doc(document_private_items)]`");
415                 }
416
417                 msg.emit();
418             }
419
420             // Process all of the crate attributes, extracting plugin metadata along
421             // with the passes which we are supposed to run.
422             for attr in krate.module.as_ref().unwrap().attrs.lists("doc") {
423                 let diag = ctxt.sess().diagnostic();
424
425                 let name = attr.name_or_empty();
426                 if attr.is_word() {
427                     if name == "no_default_passes" {
428                         report_deprecated_attr("no_default_passes", diag);
429                         if default_passes == passes::DefaultPassOption::Default {
430                             default_passes = passes::DefaultPassOption::None;
431                         }
432                     }
433                 } else if let Some(value) = attr.value_str() {
434                     let sink = match name.get() {
435                         "passes" => {
436                             report_deprecated_attr("passes = \"...\"", diag);
437                             &mut manual_passes
438                         },
439                         "plugins" => {
440                             report_deprecated_attr("plugins = \"...\"", diag);
441                             eprintln!("WARNING: #![doc(plugins = \"...\")] no longer functions; \
442                                       see CVE-2018-1000622");
443                             continue
444                         },
445                         _ => continue,
446                     };
447                     for p in value.as_str().split_whitespace() {
448                         sink.push(p.to_string());
449                     }
450                 }
451
452                 if attr.is_word() && name == "document_private_items" {
453                     if default_passes == passes::DefaultPassOption::Default {
454                         default_passes = passes::DefaultPassOption::Private;
455                     }
456                 }
457             }
458
459             let mut passes: Vec<String> =
460                 passes::defaults(default_passes).iter().map(|p| p.to_string()).collect();
461             passes.extend(manual_passes);
462
463             info!("Executing passes");
464
465             for pass_name in &passes {
466                 match passes::find_pass(pass_name).map(|p| p.pass) {
467                     Some(pass) => {
468                         debug!("running pass {}", pass_name);
469                         krate = pass(krate, &ctxt);
470                     }
471                     None => error!("unknown pass {}, skipping", *pass_name),
472                 }
473             }
474
475             ctxt.sess().abort_if_errors();
476
477             (krate, ctxt.renderinfo.into_inner(), render_options, passes)
478         })
479     })
480 }