]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/core.rs
18bb5eef538badc620c8753ec0ec9ad6aedfc397
[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, colorful_rendered } => {
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                     colorful_rendered,
319                 ).ui_testing(ui_testing)
320             )
321         },
322         ErrorOutputType::Short(color_config) => Box::new(
323             EmitterWriter::stderr(
324                 color_config,
325                 source_map.map(|cm| cm as _),
326                 true,
327                 false)
328         ),
329     };
330
331     errors::Handler::with_emitter_and_flags(
332         emitter,
333         errors::HandlerFlags {
334             can_emit_warnings: true,
335             treat_err_as_bug,
336             report_delayed_bugs: false,
337             external_macro_backtrace: false,
338             ..Default::default()
339         },
340     )
341 }
342
343 pub fn run_core(options: RustdocOptions) -> (clean::Crate, RenderInfo, RenderOptions, Vec<String>) {
344     // Parse, resolve, and typecheck the given crate.
345
346     let RustdocOptions {
347         input,
348         crate_name,
349         error_format,
350         libs,
351         externs,
352         cfgs,
353         codegen_options,
354         debugging_options,
355         target,
356         edition,
357         maybe_sysroot,
358         lint_opts,
359         describe_lints,
360         lint_cap,
361         mut default_passes,
362         mut manual_passes,
363         display_warnings,
364         render_options,
365         ..
366     } = options;
367
368     let cpath = Some(input.clone());
369     let input = Input::File(input);
370
371     let intra_link_resolution_failure_name = lint::builtin::INTRA_DOC_LINK_RESOLUTION_FAILURE.name;
372     let warnings_lint_name = lint::builtin::WARNINGS.name;
373     let missing_docs = rustc_lint::builtin::MISSING_DOCS.name;
374     let missing_doc_example = rustc_lint::builtin::MISSING_DOC_CODE_EXAMPLES.name;
375     let private_doc_tests = rustc_lint::builtin::PRIVATE_DOC_TESTS.name;
376
377     // In addition to those specific lints, we also need to whitelist those given through
378     // command line, otherwise they'll get ignored and we don't want that.
379     let mut whitelisted_lints = vec![warnings_lint_name.to_owned(),
380                                      intra_link_resolution_failure_name.to_owned(),
381                                      missing_docs.to_owned(),
382                                      missing_doc_example.to_owned(),
383                                      private_doc_tests.to_owned()];
384
385     whitelisted_lints.extend(lint_opts.iter().map(|(lint, _)| lint).cloned());
386
387     let lints = || {
388         lint::builtin::HardwiredLints
389             .get_lints()
390             .into_iter()
391             .chain(rustc_lint::SoftLints.get_lints().into_iter())
392     };
393
394     let lint_opts = lints().filter_map(|lint| {
395         if lint.name == warnings_lint_name ||
396             lint.name == intra_link_resolution_failure_name {
397             None
398         } else {
399             Some((lint.name_lower(), lint::Allow))
400         }
401     }).chain(lint_opts.into_iter()).collect::<Vec<_>>();
402
403     let lint_caps = lints().filter_map(|lint| {
404         // We don't want to whitelist *all* lints so let's
405         // ignore those ones.
406         if whitelisted_lints.iter().any(|l| &lint.name == l) {
407             None
408         } else {
409             Some((lint::LintId::of(lint), lint::Allow))
410         }
411     }).collect();
412
413     let host_triple = TargetTriple::from_triple(config::host_triple());
414     // plays with error output here!
415     let sessopts = config::Options {
416         maybe_sysroot,
417         search_paths: libs,
418         crate_types: vec![config::CrateType::Rlib],
419         lint_opts: if !display_warnings {
420             lint_opts
421         } else {
422             vec![]
423         },
424         lint_cap: Some(lint_cap.unwrap_or_else(|| lint::Forbid)),
425         cg: codegen_options,
426         externs,
427         target_triple: target.unwrap_or(host_triple),
428         // Ensure that rustdoc works even if rustc is feature-staged
429         unstable_features: UnstableFeatures::Allow,
430         actually_rustdoc: true,
431         debugging_opts: debugging_options.clone(),
432         error_format,
433         edition,
434         describe_lints,
435         ..Options::default()
436     };
437
438     let config = interface::Config {
439         opts: sessopts,
440         crate_cfg: config::parse_cfgspecs(cfgs),
441         input,
442         input_path: cpath,
443         output_file: None,
444         output_dir: None,
445         file_loader: None,
446         diagnostic_output: DiagnosticOutput::Default,
447         stderr: None,
448         crate_name: crate_name.clone(),
449         lint_caps,
450     };
451
452     interface::run_compiler_in_existing_thread_pool(config, |compiler| {
453         let sess = compiler.session();
454
455         // We need to hold on to the complete resolver, so we cause everything to be
456         // cloned for the analysis passes to use. Suboptimal, but necessary in the
457         // current architecture.
458         let resolver = abort_on_err(compiler.expansion(), sess).peek().1.clone();
459
460         if sess.err_count() > 0 {
461             sess.fatal("Compilation failed, aborting rustdoc");
462         }
463
464         let mut global_ctxt = abort_on_err(compiler.global_ctxt(), sess).take();
465
466         global_ctxt.enter(|tcx| {
467             tcx.analysis(LOCAL_CRATE).ok();
468
469             // Abort if there were any errors so far
470             sess.abort_if_errors();
471
472             let access_levels = tcx.privacy_access_levels(LOCAL_CRATE);
473             // Convert from a HirId set to a DefId set since we don't always have easy access
474             // to the map from defid -> hirid
475             let access_levels = AccessLevels {
476                 map: access_levels.map.iter()
477                                     .map(|(&k, &v)| (tcx.hir().local_def_id_from_hir_id(k), v))
478                                     .collect()
479             };
480
481             let send_trait = if crate_name == Some("core".to_string()) {
482                 clean::path_to_def_local(&tcx, &["marker", "Send"])
483             } else {
484                 clean::path_to_def(&tcx, &["core", "marker", "Send"])
485             };
486
487             let mut renderinfo = RenderInfo::default();
488             renderinfo.access_levels = access_levels;
489
490             let ctxt = DocContext {
491                 tcx,
492                 resolver,
493                 crate_name,
494                 cstore: compiler.cstore().clone(),
495                 external_traits: Default::default(),
496                 active_extern_traits: Default::default(),
497                 renderinfo: RefCell::new(renderinfo),
498                 ty_substs: Default::default(),
499                 lt_substs: Default::default(),
500                 ct_substs: Default::default(),
501                 impl_trait_bounds: Default::default(),
502                 send_trait: send_trait,
503                 fake_def_ids: Default::default(),
504                 all_fake_def_ids: Default::default(),
505                 generated_synthetics: Default::default(),
506                 all_traits: tcx.all_traits(LOCAL_CRATE).to_vec(),
507             };
508             debug!("crate: {:?}", tcx.hir().krate());
509
510             let mut krate = {
511                 let mut v = RustdocVisitor::new(&ctxt);
512                 v.visit(tcx.hir().krate());
513                 v.clean(&ctxt)
514             };
515
516             fn report_deprecated_attr(name: &str, diag: &errors::Handler) {
517                 let mut msg = diag.struct_warn(&format!("the `#![doc({})]` attribute is \
518                                                          considered deprecated", name));
519                 msg.warn("please see https://github.com/rust-lang/rust/issues/44136");
520
521                 if name == "no_default_passes" {
522                     msg.help("you may want to use `#![doc(document_private_items)]`");
523                 }
524
525                 msg.emit();
526             }
527
528             // Process all of the crate attributes, extracting plugin metadata along
529             // with the passes which we are supposed to run.
530             for attr in krate.module.as_ref().unwrap().attrs.lists("doc") {
531                 let diag = ctxt.sess().diagnostic();
532
533                 let name = attr.name_or_empty();
534                 if attr.is_word() {
535                     if name == "no_default_passes" {
536                         report_deprecated_attr("no_default_passes", diag);
537                         if default_passes == passes::DefaultPassOption::Default {
538                             default_passes = passes::DefaultPassOption::None;
539                         }
540                     }
541                 } else if let Some(value) = attr.value_str() {
542                     let sink = match name.get() {
543                         "passes" => {
544                             report_deprecated_attr("passes = \"...\"", diag);
545                             &mut manual_passes
546                         },
547                         "plugins" => {
548                             report_deprecated_attr("plugins = \"...\"", diag);
549                             eprintln!("WARNING: #![doc(plugins = \"...\")] no longer functions; \
550                                       see CVE-2018-1000622");
551                             continue
552                         },
553                         _ => continue,
554                     };
555                     for p in value.as_str().split_whitespace() {
556                         sink.push(p.to_string());
557                     }
558                 }
559
560                 if attr.is_word() && name == "document_private_items" {
561                     if default_passes == passes::DefaultPassOption::Default {
562                         default_passes = passes::DefaultPassOption::Private;
563                     }
564                 }
565             }
566
567             let mut passes: Vec<String> =
568                 passes::defaults(default_passes).iter().map(|p| p.to_string()).collect();
569             passes.extend(manual_passes);
570
571             info!("Executing passes");
572
573             for pass_name in &passes {
574                 match passes::find_pass(pass_name).map(|p| p.pass) {
575                     Some(pass) => {
576                         debug!("running pass {}", pass_name);
577                         krate = pass(krate, &ctxt);
578                     }
579                     None => error!("unknown pass {}, skipping", *pass_name),
580                 }
581             }
582
583             ctxt.sess().abort_if_errors();
584
585             (krate, ctxt.renderinfo.into_inner(), render_options, passes)
586         })
587     })
588 }