]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/core.rs
Rollup merge of #90723 - asquared31415:box_docs, r=jyn514
[rust.git] / src / librustdoc / core.rs
1 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
2 use rustc_data_structures::sync::{self, Lrc};
3 use rustc_driver::abort_on_err;
4 use rustc_errors::emitter::{Emitter, EmitterWriter};
5 use rustc_errors::json::JsonEmitter;
6 use rustc_feature::UnstableFeatures;
7 use rustc_hir::def::Res;
8 use rustc_hir::def_id::{DefId, LocalDefId};
9 use rustc_hir::HirId;
10 use rustc_hir::{
11     intravisit::{self, NestedVisitorMap, Visitor},
12     Path,
13 };
14 use rustc_interface::{interface, Queries};
15 use rustc_middle::hir::map::Map;
16 use rustc_middle::middle::privacy::AccessLevels;
17 use rustc_middle::ty::{ParamEnv, Ty, TyCtxt};
18 use rustc_resolve as resolve;
19 use rustc_session::config::{self, CrateType, ErrorOutputType};
20 use rustc_session::lint;
21 use rustc_session::DiagnosticOutput;
22 use rustc_session::Session;
23 use rustc_span::source_map;
24 use rustc_span::symbol::sym;
25 use rustc_span::Span;
26
27 use std::cell::RefCell;
28 use std::lazy::SyncLazy;
29 use std::mem;
30 use std::rc::Rc;
31
32 use crate::clean::inline::build_external_trait;
33 use crate::clean::{self, ItemId, TraitWithExtraInfo};
34 use crate::config::{Options as RustdocOptions, OutputFormat, RenderOptions};
35 use crate::formats::cache::Cache;
36 use crate::passes::{self, Condition::*, ConditionalPass};
37
38 crate use rustc_session::config::{DebuggingOptions, Input, Options};
39
40 crate struct DocContext<'tcx> {
41     crate tcx: TyCtxt<'tcx>,
42     /// Name resolver. Used for intra-doc links.
43     ///
44     /// The `Rc<RefCell<...>>` wrapping is needed because that is what's returned by
45     /// [`Queries::expansion()`].
46     // FIXME: see if we can get rid of this RefCell somehow
47     crate resolver: Rc<RefCell<interface::BoxedResolver>>,
48     /// Used for normalization.
49     ///
50     /// Most of this logic is copied from rustc_lint::late.
51     crate param_env: ParamEnv<'tcx>,
52     /// Later on moved through `clean::Crate` into `cache`
53     crate external_traits: Rc<RefCell<FxHashMap<DefId, clean::TraitWithExtraInfo>>>,
54     /// Used while populating `external_traits` to ensure we don't process the same trait twice at
55     /// the same time.
56     crate active_extern_traits: FxHashSet<DefId>,
57     // The current set of parameter substitutions,
58     // for expanding type aliases at the HIR level:
59     /// Table `DefId` of type, lifetime, or const parameter -> substituted type, lifetime, or const
60     crate substs: FxHashMap<DefId, clean::SubstParam>,
61     /// Table synthetic type parameter for `impl Trait` in argument position -> bounds
62     crate impl_trait_bounds: FxHashMap<ImplTraitParam, Vec<clean::GenericBound>>,
63     /// Auto-trait or blanket impls processed so far, as `(self_ty, trait_def_id)`.
64     // FIXME(eddyb) make this a `ty::TraitRef<'tcx>` set.
65     crate generated_synthetics: FxHashSet<(Ty<'tcx>, DefId)>,
66     crate auto_traits: Vec<DefId>,
67     /// The options given to rustdoc that could be relevant to a pass.
68     crate render_options: RenderOptions,
69     /// The traits in scope for a given module.
70     ///
71     /// See `collect_intra_doc_links::traits_implemented_by` for more details.
72     /// `map<module, set<trait>>`
73     crate module_trait_cache: FxHashMap<DefId, FxHashSet<DefId>>,
74     /// This same cache is used throughout rustdoc, including in [`crate::html::render`].
75     crate cache: Cache,
76     /// Used by [`clean::inline`] to tell if an item has already been inlined.
77     crate inlined: FxHashSet<ItemId>,
78     /// Used by `calculate_doc_coverage`.
79     crate output_format: OutputFormat,
80 }
81
82 impl<'tcx> DocContext<'tcx> {
83     crate fn sess(&self) -> &'tcx Session {
84         self.tcx.sess
85     }
86
87     crate fn with_param_env<T, F: FnOnce(&mut Self) -> T>(&mut self, def_id: DefId, f: F) -> T {
88         let old_param_env = mem::replace(&mut self.param_env, self.tcx.param_env(def_id));
89         let ret = f(self);
90         self.param_env = old_param_env;
91         ret
92     }
93
94     crate fn enter_resolver<F, R>(&self, f: F) -> R
95     where
96         F: FnOnce(&mut resolve::Resolver<'_>) -> R,
97     {
98         self.resolver.borrow_mut().access(f)
99     }
100
101     /// Call the closure with the given parameters set as
102     /// the substitutions for a type alias' RHS.
103     crate fn enter_alias<F, R>(&mut self, substs: FxHashMap<DefId, clean::SubstParam>, f: F) -> R
104     where
105         F: FnOnce(&mut Self) -> R,
106     {
107         let old_substs = mem::replace(&mut self.substs, substs);
108         let r = f(self);
109         self.substs = old_substs;
110         r
111     }
112
113     /// Like `hir().local_def_id_to_hir_id()`, but skips calling it on fake DefIds.
114     /// (This avoids a slice-index-out-of-bounds panic.)
115     crate fn as_local_hir_id(tcx: TyCtxt<'_>, def_id: ItemId) -> Option<HirId> {
116         match def_id {
117             ItemId::DefId(real_id) => {
118                 real_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
119             }
120             // FIXME: Can this be `Some` for `Auto` or `Blanket`?
121             _ => None,
122         }
123     }
124 }
125
126 /// Creates a new diagnostic `Handler` that can be used to emit warnings and errors.
127 ///
128 /// If the given `error_format` is `ErrorOutputType::Json` and no `SourceMap` is given, a new one
129 /// will be created for the handler.
130 crate fn new_handler(
131     error_format: ErrorOutputType,
132     source_map: Option<Lrc<source_map::SourceMap>>,
133     debugging_opts: &DebuggingOptions,
134 ) -> rustc_errors::Handler {
135     let emitter: Box<dyn Emitter + sync::Send> = match error_format {
136         ErrorOutputType::HumanReadable(kind) => {
137             let (short, color_config) = kind.unzip();
138             Box::new(
139                 EmitterWriter::stderr(
140                     color_config,
141                     source_map.map(|sm| sm as _),
142                     short,
143                     debugging_opts.teach,
144                     debugging_opts.terminal_width,
145                     false,
146                 )
147                 .ui_testing(debugging_opts.ui_testing),
148             )
149         }
150         ErrorOutputType::Json { pretty, json_rendered } => {
151             let source_map = source_map.unwrap_or_else(|| {
152                 Lrc::new(source_map::SourceMap::new(source_map::FilePathMapping::empty()))
153             });
154             Box::new(
155                 JsonEmitter::stderr(
156                     None,
157                     source_map,
158                     pretty,
159                     json_rendered,
160                     debugging_opts.terminal_width,
161                     false,
162                 )
163                 .ui_testing(debugging_opts.ui_testing),
164             )
165         }
166     };
167
168     rustc_errors::Handler::with_emitter_and_flags(
169         emitter,
170         debugging_opts.diagnostic_handler_flags(true),
171     )
172 }
173
174 /// Parse, resolve, and typecheck the given crate.
175 crate fn create_config(
176     RustdocOptions {
177         input,
178         crate_name,
179         proc_macro_crate,
180         error_format,
181         libs,
182         externs,
183         mut cfgs,
184         codegen_options,
185         debugging_opts,
186         target,
187         edition,
188         maybe_sysroot,
189         lint_opts,
190         describe_lints,
191         lint_cap,
192         ..
193     }: RustdocOptions,
194 ) -> rustc_interface::Config {
195     // Add the doc cfg into the doc build.
196     cfgs.push("doc".to_string());
197
198     let cpath = Some(input.clone());
199     let input = Input::File(input);
200
201     // By default, rustdoc ignores all lints.
202     // Specifically unblock lints relevant to documentation or the lint machinery itself.
203     let mut lints_to_show = vec![
204         // it's unclear whether these should be part of rustdoc directly (#77364)
205         rustc_lint::builtin::MISSING_DOCS.name.to_string(),
206         rustc_lint::builtin::INVALID_DOC_ATTRIBUTES.name.to_string(),
207         // these are definitely not part of rustdoc, but we want to warn on them anyway.
208         rustc_lint::builtin::RENAMED_AND_REMOVED_LINTS.name.to_string(),
209         rustc_lint::builtin::UNKNOWN_LINTS.name.to_string(),
210     ];
211     lints_to_show.extend(crate::lint::RUSTDOC_LINTS.iter().map(|lint| lint.name.to_string()));
212
213     let (lint_opts, lint_caps) = crate::lint::init_lints(lints_to_show, lint_opts, |lint| {
214         Some((lint.name_lower(), lint::Allow))
215     });
216
217     let crate_types =
218         if proc_macro_crate { vec![CrateType::ProcMacro] } else { vec![CrateType::Rlib] };
219     // plays with error output here!
220     let sessopts = config::Options {
221         maybe_sysroot,
222         search_paths: libs,
223         crate_types,
224         lint_opts,
225         lint_cap,
226         cg: codegen_options,
227         externs,
228         target_triple: target,
229         unstable_features: UnstableFeatures::from_environment(crate_name.as_deref()),
230         actually_rustdoc: true,
231         debugging_opts,
232         error_format,
233         edition,
234         describe_lints,
235         crate_name,
236         ..Options::default()
237     };
238
239     interface::Config {
240         opts: sessopts,
241         crate_cfg: interface::parse_cfgspecs(cfgs),
242         input,
243         input_path: cpath,
244         output_file: None,
245         output_dir: None,
246         file_loader: None,
247         diagnostic_output: DiagnosticOutput::Default,
248         stderr: None,
249         lint_caps,
250         parse_sess_created: None,
251         register_lints: Some(box crate::lint::register_lints),
252         override_queries: Some(|_sess, providers, _external_providers| {
253             // Most lints will require typechecking, so just don't run them.
254             providers.lint_mod = |_, _| {};
255             // Prevent `rustc_typeck::check_crate` from calling `typeck` on all bodies.
256             providers.typeck_item_bodies = |_, _| {};
257             // hack so that `used_trait_imports` won't try to call typeck
258             providers.used_trait_imports = |_, _| {
259                 static EMPTY_SET: SyncLazy<FxHashSet<LocalDefId>> =
260                     SyncLazy::new(FxHashSet::default);
261                 &EMPTY_SET
262             };
263             // In case typeck does end up being called, don't ICE in case there were name resolution errors
264             providers.typeck = move |tcx, def_id| {
265                 // Closures' tables come from their outermost function,
266                 // as they are part of the same "inference environment".
267                 // This avoids emitting errors for the parent twice (see similar code in `typeck_with_fallback`)
268                 let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id()).expect_local();
269                 if typeck_root_def_id != def_id {
270                     return tcx.typeck(typeck_root_def_id);
271                 }
272
273                 let hir = tcx.hir();
274                 let body = hir.body(hir.body_owned_by(hir.local_def_id_to_hir_id(def_id)));
275                 debug!("visiting body for {:?}", def_id);
276                 EmitIgnoredResolutionErrors::new(tcx).visit_body(body);
277                 (rustc_interface::DEFAULT_QUERY_PROVIDERS.typeck)(tcx, def_id)
278             };
279         }),
280         make_codegen_backend: None,
281         registry: rustc_driver::diagnostics_registry(),
282     }
283 }
284
285 crate fn create_resolver<'a>(
286     queries: &Queries<'a>,
287     sess: &Session,
288 ) -> Rc<RefCell<interface::BoxedResolver>> {
289     let (krate, resolver, _) = &*abort_on_err(queries.expansion(), sess).peek();
290     let resolver = resolver.clone();
291
292     crate::passes::collect_intra_doc_links::load_intra_link_crates(resolver, krate)
293 }
294
295 crate fn run_global_ctxt(
296     tcx: TyCtxt<'_>,
297     resolver: Rc<RefCell<interface::BoxedResolver>>,
298     mut default_passes: passes::DefaultPassOption,
299     manual_passes: Vec<String>,
300     render_options: RenderOptions,
301     output_format: OutputFormat,
302 ) -> (clean::Crate, RenderOptions, Cache) {
303     // Certain queries assume that some checks were run elsewhere
304     // (see https://github.com/rust-lang/rust/pull/73566#issuecomment-656954425),
305     // so type-check everything other than function bodies in this crate before running lints.
306
307     // NOTE: this does not call `tcx.analysis()` so that we won't
308     // typeck function bodies or run the default rustc lints.
309     // (see `override_queries` in the `config`)
310
311     // HACK(jynelson) this calls an _extremely_ limited subset of `typeck`
312     // and might break if queries change their assumptions in the future.
313
314     // NOTE: This is copy/pasted from typeck/lib.rs and should be kept in sync with those changes.
315     tcx.sess.time("item_types_checking", || {
316         tcx.hir().for_each_module(|module| tcx.ensure().check_mod_item_types(module))
317     });
318     tcx.sess.abort_if_errors();
319     tcx.sess.time("missing_docs", || {
320         rustc_lint::check_crate(tcx, rustc_lint::builtin::MissingDoc::new);
321     });
322     tcx.sess.time("check_mod_attrs", || {
323         tcx.hir().for_each_module(|module| tcx.ensure().check_mod_attrs(module))
324     });
325     rustc_passes::stability::check_unused_or_stable_features(tcx);
326
327     let access_levels = AccessLevels {
328         map: tcx.privacy_access_levels(()).map.iter().map(|(k, v)| (k.to_def_id(), *v)).collect(),
329     };
330
331     let mut ctxt = DocContext {
332         tcx,
333         resolver,
334         param_env: ParamEnv::empty(),
335         external_traits: Default::default(),
336         active_extern_traits: Default::default(),
337         substs: Default::default(),
338         impl_trait_bounds: Default::default(),
339         generated_synthetics: Default::default(),
340         auto_traits: tcx
341             .all_traits(())
342             .iter()
343             .cloned()
344             .filter(|trait_def_id| tcx.trait_is_auto(*trait_def_id))
345             .collect(),
346         module_trait_cache: FxHashMap::default(),
347         cache: Cache::new(access_levels, render_options.document_private),
348         inlined: FxHashSet::default(),
349         output_format,
350         render_options,
351     };
352
353     // Small hack to force the Sized trait to be present.
354     //
355     // Note that in case of `#![no_core]`, the trait is not available.
356     if let Some(sized_trait_did) = ctxt.tcx.lang_items().sized_trait() {
357         let mut sized_trait = build_external_trait(&mut ctxt, sized_trait_did);
358         sized_trait.is_auto = true;
359         ctxt.external_traits
360             .borrow_mut()
361             .insert(sized_trait_did, TraitWithExtraInfo { trait_: sized_trait, is_notable: false });
362     }
363
364     debug!("crate: {:?}", tcx.hir().krate());
365
366     let mut krate = tcx.sess.time("clean_crate", || clean::krate(&mut ctxt));
367
368     if krate.module.doc_value().map(|d| d.is_empty()).unwrap_or(true) {
369         let help = format!(
370             "The following guide may be of use:\n\
371             {}/rustdoc/how-to-write-documentation.html",
372             crate::DOC_RUST_LANG_ORG_CHANNEL
373         );
374         tcx.struct_lint_node(
375             crate::lint::MISSING_CRATE_LEVEL_DOCS,
376             DocContext::as_local_hir_id(tcx, krate.module.def_id).unwrap(),
377             |lint| {
378                 let mut diag =
379                     lint.build("no documentation found for this crate's top-level module");
380                 diag.help(&help);
381                 diag.emit();
382             },
383         );
384     }
385
386     fn report_deprecated_attr(name: &str, diag: &rustc_errors::Handler, sp: Span) {
387         let mut msg =
388             diag.struct_span_warn(sp, &format!("the `#![doc({})]` attribute is deprecated", name));
389         msg.note(
390             "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
391              for more information",
392         );
393
394         if name == "no_default_passes" {
395             msg.help("you may want to use `#![doc(document_private_items)]`");
396         } else if name.starts_with("plugins") {
397             msg.warn("`#![doc(plugins = \"...\")]` no longer functions; see CVE-2018-1000622 <https://nvd.nist.gov/vuln/detail/CVE-2018-1000622>");
398         }
399
400         msg.emit();
401     }
402
403     let parse_pass = |name: &str, sp: Option<Span>| {
404         if let Some(pass) = passes::find_pass(name) {
405             Some(ConditionalPass::always(pass))
406         } else {
407             let msg = &format!("ignoring unknown pass `{}`", name);
408             let mut warning = if let Some(sp) = sp {
409                 tcx.sess.struct_span_warn(sp, msg)
410             } else {
411                 tcx.sess.struct_warn(msg)
412             };
413             if name == "collapse-docs" {
414                 warning.note("the `collapse-docs` pass was removed in #80261 <https://github.com/rust-lang/rust/pull/80261>");
415             }
416             warning.emit();
417             None
418         }
419     };
420
421     let mut manual_passes: Vec<_> =
422         manual_passes.into_iter().flat_map(|name| parse_pass(&name, None)).collect();
423
424     // Process all of the crate attributes, extracting plugin metadata along
425     // with the passes which we are supposed to run.
426     for attr in krate.module.attrs.lists(sym::doc) {
427         let diag = ctxt.sess().diagnostic();
428
429         let name = attr.name_or_empty();
430         if attr.is_word() {
431             if name == sym::no_default_passes {
432                 report_deprecated_attr("no_default_passes", diag, attr.span());
433                 if default_passes == passes::DefaultPassOption::Default {
434                     default_passes = passes::DefaultPassOption::None;
435                 }
436             }
437         } else if let Some(value) = attr.value_str() {
438             match name {
439                 sym::passes => {
440                     report_deprecated_attr("passes = \"...\"", diag, attr.span());
441                 }
442                 sym::plugins => {
443                     report_deprecated_attr("plugins = \"...\"", diag, attr.span());
444                     continue;
445                 }
446                 _ => continue,
447             };
448             for name in value.as_str().split_whitespace() {
449                 let span = attr.name_value_literal_span().unwrap_or_else(|| attr.span());
450                 manual_passes.extend(parse_pass(name, Some(span)));
451             }
452         }
453
454         if attr.is_word() && name == sym::document_private_items {
455             ctxt.render_options.document_private = true;
456         }
457     }
458
459     let passes = passes::defaults(default_passes).iter().copied().chain(manual_passes);
460     info!("Executing passes");
461
462     for p in passes {
463         let run = match p.condition {
464             Always => true,
465             WhenDocumentPrivate => ctxt.render_options.document_private,
466             WhenNotDocumentPrivate => !ctxt.render_options.document_private,
467             WhenNotDocumentHidden => !ctxt.render_options.document_hidden,
468         };
469         if run {
470             debug!("running pass {}", p.pass.name);
471             krate = tcx.sess.time(p.pass.name, || (p.pass.run)(krate, &mut ctxt));
472         }
473     }
474
475     if tcx.sess.diagnostic().has_errors_or_lint_errors() {
476         rustc_errors::FatalError.raise();
477     }
478
479     let render_options = ctxt.render_options;
480     let mut cache = ctxt.cache;
481     krate = tcx.sess.time("create_format_cache", || cache.populate(krate, tcx, &render_options));
482
483     // The main crate doc comments are always collapsed.
484     krate.collapsed = true;
485
486     (krate, render_options, cache)
487 }
488
489 /// Due to <https://github.com/rust-lang/rust/pull/73566>,
490 /// the name resolution pass may find errors that are never emitted.
491 /// If typeck is called after this happens, then we'll get an ICE:
492 /// 'Res::Error found but not reported'. To avoid this, emit the errors now.
493 struct EmitIgnoredResolutionErrors<'tcx> {
494     tcx: TyCtxt<'tcx>,
495 }
496
497 impl<'tcx> EmitIgnoredResolutionErrors<'tcx> {
498     fn new(tcx: TyCtxt<'tcx>) -> Self {
499         Self { tcx }
500     }
501 }
502
503 impl<'tcx> Visitor<'tcx> for EmitIgnoredResolutionErrors<'tcx> {
504     type Map = Map<'tcx>;
505
506     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
507         // We need to recurse into nested closures,
508         // since those will fallback to the parent for type checking.
509         NestedVisitorMap::OnlyBodies(self.tcx.hir())
510     }
511
512     fn visit_path(&mut self, path: &'tcx Path<'_>, _id: HirId) {
513         debug!("visiting path {:?}", path);
514         if path.res == Res::Err {
515             // We have less context here than in rustc_resolve,
516             // so we can only emit the name and span.
517             // However we can give a hint that rustc_resolve will have more info.
518             let label = format!(
519                 "could not resolve path `{}`",
520                 path.segments
521                     .iter()
522                     .map(|segment| segment.ident.as_str().to_string())
523                     .collect::<Vec<_>>()
524                     .join("::")
525             );
526             let mut err = rustc_errors::struct_span_err!(
527                 self.tcx.sess,
528                 path.span,
529                 E0433,
530                 "failed to resolve: {}",
531                 label
532             );
533             err.span_label(path.span, label);
534             err.note("this error was originally ignored because you are running `rustdoc`");
535             err.note("try running again with `rustc` or `cargo check` and you may get a more detailed error");
536             err.emit();
537         }
538         // We could have an outer resolution that succeeded,
539         // but with generic parameters that failed.
540         // Recurse into the segments so we catch those too.
541         intravisit::walk_path(self, path);
542     }
543 }
544
545 /// `DefId` or parameter index (`ty::ParamTy.index`) of a synthetic type parameter
546 /// for `impl Trait` in argument position.
547 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
548 crate enum ImplTraitParam {
549     DefId(DefId),
550     ParamIndex(u32),
551 }
552
553 impl From<DefId> for ImplTraitParam {
554     fn from(did: DefId) -> Self {
555         ImplTraitParam::DefId(did)
556     }
557 }
558
559 impl From<u32> for ImplTraitParam {
560     fn from(idx: u32) -> Self {
561         ImplTraitParam::ParamIndex(idx)
562     }
563 }