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