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