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