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