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