blob: 3e6066c78fba2ba0832c2e8c7e36477f5272397e [file] [log] [blame]
Matthew Maurer859223d2020-03-27 12:47:38 -07001use rustc_data_structures::fx::{FxHashMap, FxHashSet};
Chris Wailes951ae7a2023-12-07 10:11:13 -08002use rustc_data_structures::sync::Lrc;
Chariseef7ad1c42023-01-30 22:46:42 +00003use rustc_data_structures::unord::UnordSet;
Chris Wailes951ae7a2023-12-07 10:11:13 -08004use rustc_errors::emitter::{DynEmitter, EmitterWriter};
Jeff Vander Stoepad6790c2020-06-24 15:34:31 +02005use rustc_errors::json::JsonEmitter;
Chris Wailes5c0824a2023-04-24 16:30:59 -07006use rustc_errors::TerminalUrl;
Matthew Maurerf4d8f812020-03-27 13:14:30 -07007use rustc_feature::UnstableFeatures;
Chris Wailes5c0824a2023-04-24 16:30:59 -07008use rustc_hir::def::Res;
9use rustc_hir::def_id::{DefId, DefIdMap, DefIdSet, LocalDefId};
Chris Wailes2805eef2022-04-07 11:22:56 -070010use rustc_hir::intravisit::{self, Visitor};
Chris Wailes5c0824a2023-04-24 16:30:59 -070011use rustc_hir::{HirId, Path};
Chris Wailes2805eef2022-04-07 11:22:56 -070012use rustc_interface::interface;
Charisee87880442023-11-01 01:09:07 +000013use rustc_lint::{late_lint_mod, MissingDoc};
Chris Wailes2805eef2022-04-07 11:22:56 -070014use rustc_middle::hir::nested_filter;
Jeff Vander Stoepd59a2872021-02-15 10:22:21 +010015use rustc_middle::ty::{ParamEnv, Ty, TyCtxt};
Chris Wailes5c0824a2023-04-24 16:30:59 -070016use rustc_session::config::{self, CrateType, ErrorOutputType, ResolveDocLinks};
Jeff Vander Stoep247d86b2020-08-11 14:27:44 +020017use rustc_session::Session;
James Farrell91b821d2023-08-24 14:18:40 +000018use rustc_session::{lint, EarlyErrorHandler};
Matthew Maurer859223d2020-03-27 12:47:38 -070019use rustc_span::symbol::sym;
Chris Wailes5c0824a2023-04-24 16:30:59 -070020use rustc_span::{source_map, Span};
Inna Palantff3f07a2019-07-11 16:15:26 -070021
Chris Wailese3116c42021-07-13 14:40:48 -070022use std::cell::RefCell;
Inna Palantff3f07a2019-07-11 16:15:26 -070023use std::mem;
Inna Palantff3f07a2019-07-11 16:15:26 -070024use std::rc::Rc;
Chris Wailes65720582022-08-11 09:53:28 -070025use std::sync::LazyLock;
Inna Palantff3f07a2019-07-11 16:15:26 -070026
Chris Wailese3116c42021-07-13 14:40:48 -070027use crate::clean::inline::build_external_trait;
Chariseef7ad1c42023-01-30 22:46:42 +000028use crate::clean::{self, ItemId};
Chris Wailese3116c42021-07-13 14:40:48 -070029use crate::config::{Options as RustdocOptions, OutputFormat, RenderOptions};
Jeff Vander Stoep59fbe182021-03-29 10:17:52 +020030use crate::formats::cache::Cache;
Charisee7878d542022-02-24 18:21:36 +000031use crate::passes::{self, Condition::*};
Inna Palantff3f07a2019-07-11 16:15:26 -070032
Chariseeb1d32802022-09-22 15:38:41 +000033pub(crate) use rustc_session::config::{Input, Options, UnstableOptions};
Inna Palantff3f07a2019-07-11 16:15:26 -070034
Chris Wailes65720582022-08-11 09:53:28 -070035pub(crate) struct DocContext<'tcx> {
36 pub(crate) tcx: TyCtxt<'tcx>,
Jeff Vander Stoepd59a2872021-02-15 10:22:21 +010037 /// Used for normalization.
38 ///
39 /// Most of this logic is copied from rustc_lint::late.
Chris Wailes65720582022-08-11 09:53:28 -070040 pub(crate) param_env: ParamEnv<'tcx>,
Jeff Vander Stoep59fbe182021-03-29 10:17:52 +020041 /// Later on moved through `clean::Crate` into `cache`
Chariseef7ad1c42023-01-30 22:46:42 +000042 pub(crate) external_traits: Rc<RefCell<FxHashMap<DefId, clean::Trait>>>,
Inna Palantff3f07a2019-07-11 16:15:26 -070043 /// Used while populating `external_traits` to ensure we don't process the same trait twice at
44 /// the same time.
Chris Wailes5c0824a2023-04-24 16:30:59 -070045 pub(crate) active_extern_traits: DefIdSet,
Chris Wailes356b57e2022-01-13 10:08:24 -080046 // The current set of parameter substitutions,
Inna Palantff3f07a2019-07-11 16:15:26 -070047 // for expanding type aliases at the HIR level:
Chris Wailes356b57e2022-01-13 10:08:24 -080048 /// Table `DefId` of type, lifetime, or const parameter -> substituted type, lifetime, or const
Charisee87880442023-11-01 01:09:07 +000049 pub(crate) args: DefIdMap<clean::SubstParam>,
Chris Wailescd1aefd2023-07-13 13:36:21 -070050 pub(crate) current_type_aliases: DefIdMap<usize>,
Chih-Hung Hsieh8cd2c992019-12-19 15:08:11 -080051 /// Table synthetic type parameter for `impl Trait` in argument position -> bounds
Chris Wailes65720582022-08-11 09:53:28 -070052 pub(crate) impl_trait_bounds: FxHashMap<ImplTraitParam, Vec<clean::GenericBound>>,
Chih-Hung Hsiehfd666f22019-12-19 14:34:18 -080053 /// Auto-trait or blanket impls processed so far, as `(self_ty, trait_def_id)`.
54 // FIXME(eddyb) make this a `ty::TraitRef<'tcx>` set.
Chris Wailes65720582022-08-11 09:53:28 -070055 pub(crate) generated_synthetics: FxHashSet<(Ty<'tcx>, DefId)>,
56 pub(crate) auto_traits: Vec<DefId>,
Jeff Vander Stoep983137f2020-09-16 14:50:30 +020057 /// The options given to rustdoc that could be relevant to a pass.
Chris Wailes65720582022-08-11 09:53:28 -070058 pub(crate) render_options: RenderOptions,
Chris Wailese3116c42021-07-13 14:40:48 -070059 /// This same cache is used throughout rustdoc, including in [`crate::html::render`].
Chris Wailes65720582022-08-11 09:53:28 -070060 pub(crate) cache: Cache,
Chris Wailese3116c42021-07-13 14:40:48 -070061 /// Used by [`clean::inline`] to tell if an item has already been inlined.
Chris Wailes65720582022-08-11 09:53:28 -070062 pub(crate) inlined: FxHashSet<ItemId>,
Chris Wailese3116c42021-07-13 14:40:48 -070063 /// Used by `calculate_doc_coverage`.
Chris Wailes65720582022-08-11 09:53:28 -070064 pub(crate) output_format: OutputFormat,
Chariseeb1d32802022-09-22 15:38:41 +000065 /// Used by `strip_private`.
66 pub(crate) show_coverage: bool,
Inna Palantff3f07a2019-07-11 16:15:26 -070067}
68
69impl<'tcx> DocContext<'tcx> {
Chris Wailes65720582022-08-11 09:53:28 -070070 pub(crate) fn sess(&self) -> &'tcx Session {
Chris Wailes356b57e2022-01-13 10:08:24 -080071 self.tcx.sess
Inna Palantff3f07a2019-07-11 16:15:26 -070072 }
73
Chris Wailes65720582022-08-11 09:53:28 -070074 pub(crate) fn with_param_env<T, F: FnOnce(&mut Self) -> T>(
75 &mut self,
76 def_id: DefId,
77 f: F,
78 ) -> T {
Chris Wailese3116c42021-07-13 14:40:48 -070079 let old_param_env = mem::replace(&mut self.param_env, self.tcx.param_env(def_id));
80 let ret = f(self);
81 self.param_env = old_param_env;
Jeff Vander Stoepd59a2872021-02-15 10:22:21 +010082 ret
83 }
84
Inna Palantff3f07a2019-07-11 16:15:26 -070085 /// Call the closure with the given parameters set as
86 /// the substitutions for a type alias' RHS.
Chris Wailescd1aefd2023-07-13 13:36:21 -070087 pub(crate) fn enter_alias<F, R>(
88 &mut self,
Charisee87880442023-11-01 01:09:07 +000089 args: DefIdMap<clean::SubstParam>,
Chris Wailescd1aefd2023-07-13 13:36:21 -070090 def_id: DefId,
91 f: F,
92 ) -> R
Matthew Maurerf4d8f812020-03-27 13:14:30 -070093 where
Chris Wailese3116c42021-07-13 14:40:48 -070094 F: FnOnce(&mut Self) -> R,
Matthew Maurerf4d8f812020-03-27 13:14:30 -070095 {
Charisee87880442023-11-01 01:09:07 +000096 let old_args = mem::replace(&mut self.args, args);
Chris Wailescd1aefd2023-07-13 13:36:21 -070097 *self.current_type_aliases.entry(def_id).or_insert(0) += 1;
Chris Wailese3116c42021-07-13 14:40:48 -070098 let r = f(self);
Charisee87880442023-11-01 01:09:07 +000099 self.args = old_args;
Chris Wailescd1aefd2023-07-13 13:36:21 -0700100 if let Some(count) = self.current_type_aliases.get_mut(&def_id) {
101 *count -= 1;
102 if *count == 0 {
103 self.current_type_aliases.remove(&def_id);
104 }
105 }
Inna Palantff3f07a2019-07-11 16:15:26 -0700106 r
107 }
108
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100109 /// Like `hir().local_def_id_to_hir_id()`, but skips calling it on fake DefIds.
Inna Palantff3f07a2019-07-11 16:15:26 -0700110 /// (This avoids a slice-index-out-of-bounds panic.)
Chris Wailes65720582022-08-11 09:53:28 -0700111 pub(crate) fn as_local_hir_id(tcx: TyCtxt<'_>, item_id: ItemId) -> Option<HirId> {
Charisee9cf67802022-06-30 20:04:09 +0000112 match item_id {
Chris Wailes54272ac2021-09-09 16:08:13 -0700113 ItemId::DefId(real_id) => {
Chris Wailes2f3fdfe2021-07-29 10:56:18 -0700114 real_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
115 }
Chris Wailes54272ac2021-09-09 16:08:13 -0700116 // FIXME: Can this be `Some` for `Auto` or `Blanket`?
117 _ => None,
Inna Palantff3f07a2019-07-11 16:15:26 -0700118 }
119 }
Inna Palantff3f07a2019-07-11 16:15:26 -0700120}
121
122/// Creates a new diagnostic `Handler` that can be used to emit warnings and errors.
123///
124/// If the given `error_format` is `ErrorOutputType::Json` and no `SourceMap` is given, a new one
125/// will be created for the handler.
Chris Wailes65720582022-08-11 09:53:28 -0700126pub(crate) fn new_handler(
Matthew Maurerf4d8f812020-03-27 13:14:30 -0700127 error_format: ErrorOutputType,
128 source_map: Option<Lrc<source_map::SourceMap>>,
Chariseeb1d32802022-09-22 15:38:41 +0000129 diagnostic_width: Option<usize>,
130 unstable_opts: &UnstableOptions,
Matthew Maurer859223d2020-03-27 12:47:38 -0700131) -> rustc_errors::Handler {
Chris Wailes5c0824a2023-04-24 16:30:59 -0700132 let fallback_bundle = rustc_errors::fallback_fluent_bundle(
133 rustc_driver::DEFAULT_LOCALE_RESOURCES.to_vec(),
134 false,
135 );
Chris Wailes951ae7a2023-12-07 10:11:13 -0800136 let emitter: Box<DynEmitter> = match error_format {
Chih-Hung Hsiehfd666f22019-12-19 14:34:18 -0800137 ErrorOutputType::HumanReadable(kind) => {
138 let (short, color_config) = kind.unzip();
139 Box::new(
Charisee87880442023-11-01 01:09:07 +0000140 EmitterWriter::stderr(color_config, fallback_bundle)
141 .sm(source_map.map(|sm| sm as _))
142 .short_message(short)
143 .teach(unstable_opts.teach)
144 .diagnostic_width(diagnostic_width)
145 .track_diagnostics(unstable_opts.track_diagnostics)
146 .ui_testing(unstable_opts.ui_testing),
Chih-Hung Hsiehfd666f22019-12-19 14:34:18 -0800147 )
Matthew Maurerf4d8f812020-03-27 13:14:30 -0700148 }
Chih-Hung Hsiehfd666f22019-12-19 14:34:18 -0800149 ErrorOutputType::Json { pretty, json_rendered } => {
Matthew Maurerf4d8f812020-03-27 13:14:30 -0700150 let source_map = source_map.unwrap_or_else(|| {
Matthew Maurer859223d2020-03-27 12:47:38 -0700151 Lrc::new(source_map::SourceMap::new(source_map::FilePathMapping::empty()))
Matthew Maurerf4d8f812020-03-27 13:14:30 -0700152 });
Inna Palantff3f07a2019-07-11 16:15:26 -0700153 Box::new(
Jeff Vander Stoep983137f2020-09-16 14:50:30 +0200154 JsonEmitter::stderr(
155 None,
156 source_map,
Charisee9cf67802022-06-30 20:04:09 +0000157 None,
158 fallback_bundle,
Jeff Vander Stoep983137f2020-09-16 14:50:30 +0200159 pretty,
160 json_rendered,
Chariseeb1d32802022-09-22 15:38:41 +0000161 diagnostic_width,
Jeff Vander Stoep983137f2020-09-16 14:50:30 +0200162 false,
Chris Wailes977026a2023-02-13 09:13:10 -0800163 unstable_opts.track_diagnostics,
Chris Wailes5c0824a2023-04-24 16:30:59 -0700164 TerminalUrl::No,
Jeff Vander Stoep983137f2020-09-16 14:50:30 +0200165 )
Chariseeb1d32802022-09-22 15:38:41 +0000166 .ui_testing(unstable_opts.ui_testing),
Inna Palantff3f07a2019-07-11 16:15:26 -0700167 )
Matthew Maurerf4d8f812020-03-27 13:14:30 -0700168 }
Inna Palantff3f07a2019-07-11 16:15:26 -0700169 };
170
Charisee87880442023-11-01 01:09:07 +0000171 rustc_errors::Handler::with_emitter(emitter)
172 .with_flags(unstable_opts.diagnostic_handler_flags(true))
Inna Palantff3f07a2019-07-11 16:15:26 -0700173}
174
Jeff Vander Stoepd59a2872021-02-15 10:22:21 +0100175/// Parse, resolve, and typecheck the given crate.
Chris Wailes65720582022-08-11 09:53:28 -0700176pub(crate) fn create_config(
James Farrell91b821d2023-08-24 14:18:40 +0000177 handler: &EarlyErrorHandler,
Jeff Vander Stoepd59a2872021-02-15 10:22:21 +0100178 RustdocOptions {
Inna Palantff3f07a2019-07-11 16:15:26 -0700179 input,
180 crate_name,
Chih-Hung Hsieh8cd2c992019-12-19 15:08:11 -0800181 proc_macro_crate,
Inna Palantff3f07a2019-07-11 16:15:26 -0700182 error_format,
Chariseeb1d32802022-09-22 15:38:41 +0000183 diagnostic_width,
Inna Palantff3f07a2019-07-11 16:15:26 -0700184 libs,
185 externs,
Chih-Hung Hsieh2ccedcd2019-12-19 15:10:50 -0800186 mut cfgs,
Charisee341341c2022-05-20 05:14:50 +0000187 check_cfgs,
Inna Palantff3f07a2019-07-11 16:15:26 -0700188 codegen_options,
Chariseeb1d32802022-09-22 15:38:41 +0000189 unstable_opts,
Inna Palantff3f07a2019-07-11 16:15:26 -0700190 target,
191 edition,
192 maybe_sysroot,
193 lint_opts,
194 describe_lints,
195 lint_cap,
Chris Wailes2805eef2022-04-07 11:22:56 -0700196 scrape_examples_options,
Chris Wailes951ae7a2023-12-07 10:11:13 -0800197 expanded_args,
Inna Palantff3f07a2019-07-11 16:15:26 -0700198 ..
Jeff Vander Stoepd59a2872021-02-15 10:22:21 +0100199 }: RustdocOptions,
Chris Wailes5c0824a2023-04-24 16:30:59 -0700200 RenderOptions { document_private, .. }: &RenderOptions,
Jeff Vander Stoepd59a2872021-02-15 10:22:21 +0100201) -> rustc_interface::Config {
Matthew Maurerf4d8f812020-03-27 13:14:30 -0700202 // Add the doc cfg into the doc build.
203 cfgs.push("doc".to_string());
Chih-Hung Hsieh2ccedcd2019-12-19 15:10:50 -0800204
Inna Palantff3f07a2019-07-11 16:15:26 -0700205 let input = Input::File(input);
206
Chris Wailese3116c42021-07-13 14:40:48 -0700207 // By default, rustdoc ignores all lints.
208 // Specifically unblock lints relevant to documentation or the lint machinery itself.
209 let mut lints_to_show = vec![
Chris Wailes2f3fdfe2021-07-29 10:56:18 -0700210 // it's unclear whether these should be part of rustdoc directly (#77364)
Chris Wailese3116c42021-07-13 14:40:48 -0700211 rustc_lint::builtin::MISSING_DOCS.name.to_string(),
Chris Wailes2f3fdfe2021-07-29 10:56:18 -0700212 rustc_lint::builtin::INVALID_DOC_ATTRIBUTES.name.to_string(),
Chris Wailese3116c42021-07-13 14:40:48 -0700213 // these are definitely not part of rustdoc, but we want to warn on them anyway.
214 rustc_lint::builtin::RENAMED_AND_REMOVED_LINTS.name.to_string(),
215 rustc_lint::builtin::UNKNOWN_LINTS.name.to_string(),
Charisee341341c2022-05-20 05:14:50 +0000216 rustc_lint::builtin::UNEXPECTED_CFGS.name.to_string(),
Charisee9cf67802022-06-30 20:04:09 +0000217 // this lint is needed to support `#[expect]` attributes
218 rustc_lint::builtin::UNFULFILLED_LINT_EXPECTATIONS.name.to_string(),
Matthew Maurerf4d8f812020-03-27 13:14:30 -0700219 ];
Chris Wailese3116c42021-07-13 14:40:48 -0700220 lints_to_show.extend(crate::lint::RUSTDOC_LINTS.iter().map(|lint| lint.name.to_string()));
Inna Palantff3f07a2019-07-11 16:15:26 -0700221
Chris Wailese3116c42021-07-13 14:40:48 -0700222 let (lint_opts, lint_caps) = crate::lint::init_lints(lints_to_show, lint_opts, |lint| {
Chris Wailes2f3fdfe2021-07-29 10:56:18 -0700223 Some((lint.name_lower(), lint::Allow))
Jeff Vander Stoep247d86b2020-08-11 14:27:44 +0200224 });
Inna Palantff3f07a2019-07-11 16:15:26 -0700225
Jeff Vander Stoep247d86b2020-08-11 14:27:44 +0200226 let crate_types =
227 if proc_macro_crate { vec![CrateType::ProcMacro] } else { vec![CrateType::Rlib] };
Charisee635618d2023-06-01 20:46:00 +0000228 let resolve_doc_links =
229 if *document_private { ResolveDocLinks::All } else { ResolveDocLinks::Exported };
Chris Wailes2805eef2022-04-07 11:22:56 -0700230 let test = scrape_examples_options.map(|opts| opts.scrape_tests).unwrap_or(false);
Inna Palantff3f07a2019-07-11 16:15:26 -0700231 // plays with error output here!
232 let sessopts = config::Options {
233 maybe_sysroot,
234 search_paths: libs,
Chih-Hung Hsieh8cd2c992019-12-19 15:08:11 -0800235 crate_types,
Chris Wailesa1538422021-12-02 10:37:12 -0800236 lint_opts,
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100237 lint_cap,
Inna Palantff3f07a2019-07-11 16:15:26 -0700238 cg: codegen_options,
239 externs,
Chih-Hung Hsieh8cd2c992019-12-19 15:08:11 -0800240 target_triple: target,
Jeff Vander Stoepd59a2872021-02-15 10:22:21 +0100241 unstable_features: UnstableFeatures::from_environment(crate_name.as_deref()),
Inna Palantff3f07a2019-07-11 16:15:26 -0700242 actually_rustdoc: true,
Chris Wailes5c0824a2023-04-24 16:30:59 -0700243 resolve_doc_links,
Chariseeb1d32802022-09-22 15:38:41 +0000244 unstable_opts,
Inna Palantff3f07a2019-07-11 16:15:26 -0700245 error_format,
Chariseeb1d32802022-09-22 15:38:41 +0000246 diagnostic_width,
Inna Palantff3f07a2019-07-11 16:15:26 -0700247 edition,
248 describe_lints,
Jeff Vander Stoepd59a2872021-02-15 10:22:21 +0100249 crate_name,
Chris Wailes2805eef2022-04-07 11:22:56 -0700250 test,
Inna Palantff3f07a2019-07-11 16:15:26 -0700251 ..Options::default()
252 };
253
Jeff Vander Stoepd59a2872021-02-15 10:22:21 +0100254 interface::Config {
Inna Palantff3f07a2019-07-11 16:15:26 -0700255 opts: sessopts,
James Farrell91b821d2023-08-24 14:18:40 +0000256 crate_cfg: interface::parse_cfgspecs(handler, cfgs),
257 crate_check_cfg: interface::parse_check_cfg(handler, check_cfgs),
Inna Palantff3f07a2019-07-11 16:15:26 -0700258 input,
Inna Palantff3f07a2019-07-11 16:15:26 -0700259 output_file: None,
260 output_dir: None,
261 file_loader: None,
Chris Wailes5c0824a2023-04-24 16:30:59 -0700262 locale_resources: rustc_driver::DEFAULT_LOCALE_RESOURCES,
Inna Palantff3f07a2019-07-11 16:15:26 -0700263 lint_caps,
Chris Wailese3116c42021-07-13 14:40:48 -0700264 parse_sess_created: None,
Chariseeb1d32802022-09-22 15:38:41 +0000265 register_lints: Some(Box::new(crate::lint::register_lints)),
Chris Wailes951ae7a2023-12-07 10:11:13 -0800266 override_queries: Some(|_sess, providers| {
Charisee87880442023-11-01 01:09:07 +0000267 // We do not register late module lints, so this only runs `MissingDoc`.
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100268 // Most lints will require typechecking, so just don't run them.
Charisee87880442023-11-01 01:09:07 +0000269 providers.lint_mod = |tcx, module_def_id| late_lint_mod(tcx, module_def_id, MissingDoc);
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100270 // hack so that `used_trait_imports` won't try to call typeck
271 providers.used_trait_imports = |_, _| {
Chariseef7ad1c42023-01-30 22:46:42 +0000272 static EMPTY_SET: LazyLock<UnordSet<LocalDefId>> = LazyLock::new(UnordSet::default);
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100273 &EMPTY_SET
274 };
275 // In case typeck does end up being called, don't ICE in case there were name resolution errors
276 providers.typeck = move |tcx, def_id| {
277 // Closures' tables come from their outermost function,
278 // as they are part of the same "inference environment".
279 // This avoids emitting errors for the parent twice (see similar code in `typeck_with_fallback`)
Chris Wailes356b57e2022-01-13 10:08:24 -0800280 let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id()).expect_local();
281 if typeck_root_def_id != def_id {
282 return tcx.typeck(typeck_root_def_id);
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100283 }
284
285 let hir = tcx.hir();
Chariseeb1d32802022-09-22 15:38:41 +0000286 let body = hir.body(hir.body_owned_by(def_id));
Charisee87880442023-11-01 01:09:07 +0000287 debug!("visiting body for {def_id:?}");
Jeff Vander Stoepd59a2872021-02-15 10:22:21 +0100288 EmitIgnoredResolutionErrors::new(tcx).visit_body(body);
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100289 (rustc_interface::DEFAULT_QUERY_PROVIDERS.typeck)(tcx, def_id)
290 };
291 }),
Thiébaud Weksteen3b664ca2020-11-26 14:41:59 +0100292 make_codegen_backend: None,
Matthew Maurerf4d8f812020-03-27 13:14:30 -0700293 registry: rustc_driver::diagnostics_registry(),
Charisee87880442023-11-01 01:09:07 +0000294 ice_file: None,
Chris Wailes951ae7a2023-12-07 10:11:13 -0800295 expanded_args,
Jeff Vander Stoepd59a2872021-02-15 10:22:21 +0100296 }
Inna Palantff3f07a2019-07-11 16:15:26 -0700297}
Chih-Hung Hsieh8cd2c992019-12-19 15:08:11 -0800298
Chris Wailes65720582022-08-11 09:53:28 -0700299pub(crate) fn run_global_ctxt(
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100300 tcx: TyCtxt<'_>,
Charisee7878d542022-02-24 18:21:36 +0000301 show_coverage: bool,
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100302 render_options: RenderOptions,
Jeff Vander Stoep59fbe182021-03-29 10:17:52 +0200303 output_format: OutputFormat,
Chris Wailese3116c42021-07-13 14:40:48 -0700304) -> (clean::Crate, RenderOptions, Cache) {
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100305 // Certain queries assume that some checks were run elsewhere
306 // (see https://github.com/rust-lang/rust/pull/73566#issuecomment-656954425),
307 // so type-check everything other than function bodies in this crate before running lints.
308
309 // NOTE: this does not call `tcx.analysis()` so that we won't
310 // typeck function bodies or run the default rustc lints.
311 // (see `override_queries` in the `config`)
312
313 // HACK(jynelson) this calls an _extremely_ limited subset of `typeck`
314 // and might break if queries change their assumptions in the future.
Charisee635618d2023-06-01 20:46:00 +0000315 tcx.sess.time("type_collecting", || {
316 tcx.hir().for_each_module(|module| tcx.ensure().collect_mod_item_types(module))
317 });
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100318
319 // NOTE: This is copy/pasted from typeck/lib.rs and should be kept in sync with those changes.
320 tcx.sess.time("item_types_checking", || {
Chris Wailesa1538422021-12-02 10:37:12 -0800321 tcx.hir().for_each_module(|module| tcx.ensure().check_mod_item_types(module))
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100322 });
323 tcx.sess.abort_if_errors();
Charisee87880442023-11-01 01:09:07 +0000324 tcx.sess.time("missing_docs", || rustc_lint::check_crate(tcx));
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100325 tcx.sess.time("check_mod_attrs", || {
Chris Wailesa1538422021-12-02 10:37:12 -0800326 tcx.hir().for_each_module(|module| tcx.ensure().check_mod_attrs(module))
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100327 });
Chris Wailese3116c42021-07-13 14:40:48 -0700328 rustc_passes::stability::check_unused_or_stable_features(tcx);
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100329
Chariseef7ad1c42023-01-30 22:46:42 +0000330 let auto_traits =
331 tcx.all_traits().filter(|&trait_def_id| tcx.trait_is_auto(trait_def_id)).collect();
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100332
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100333 let mut ctxt = DocContext {
334 tcx,
Chris Wailese3116c42021-07-13 14:40:48 -0700335 param_env: ParamEnv::empty(),
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100336 external_traits: Default::default(),
337 active_extern_traits: Default::default(),
Charisee87880442023-11-01 01:09:07 +0000338 args: Default::default(),
Chris Wailescd1aefd2023-07-13 13:36:21 -0700339 current_type_aliases: Default::default(),
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100340 impl_trait_bounds: Default::default(),
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100341 generated_synthetics: Default::default(),
Chris Wailes2805eef2022-04-07 11:22:56 -0700342 auto_traits,
Charisee87880442023-11-01 01:09:07 +0000343 cache: Cache::new(render_options.document_private, render_options.document_hidden),
Chris Wailese3116c42021-07-13 14:40:48 -0700344 inlined: FxHashSet::default(),
345 output_format,
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100346 render_options,
Chariseeb1d32802022-09-22 15:38:41 +0000347 show_coverage,
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100348 };
Chris Wailese3116c42021-07-13 14:40:48 -0700349
Chris Wailes5c0824a2023-04-24 16:30:59 -0700350 for cnum in tcx.crates(()) {
351 crate::visit_lib::lib_embargo_visit_item(&mut ctxt, cnum.as_def_id());
352 }
353
Chris Wailese3116c42021-07-13 14:40:48 -0700354 // Small hack to force the Sized trait to be present.
355 //
356 // Note that in case of `#![no_core]`, the trait is not available.
357 if let Some(sized_trait_did) = ctxt.tcx.lang_items().sized_trait() {
Chariseeb1d32802022-09-22 15:38:41 +0000358 let sized_trait = build_external_trait(&mut ctxt, sized_trait_did);
Chariseef7ad1c42023-01-30 22:46:42 +0000359 ctxt.external_traits.borrow_mut().insert(sized_trait_did, sized_trait);
Chris Wailese3116c42021-07-13 14:40:48 -0700360 }
361
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100362 debug!("crate: {:?}", tcx.hir().krate());
363
364 let mut krate = tcx.sess.time("clean_crate", || clean::krate(&mut ctxt));
365
Chris Wailescd1aefd2023-07-13 13:36:21 -0700366 if krate.module.doc_value().is_empty() {
Chris Wailes2f3fdfe2021-07-29 10:56:18 -0700367 let help = format!(
368 "The following guide may be of use:\n\
369 {}/rustdoc/how-to-write-documentation.html",
370 crate::DOC_RUST_LANG_ORG_CHANNEL
371 );
Chris Wailes32f78352021-07-20 14:04:55 -0700372 tcx.struct_lint_node(
373 crate::lint::MISSING_CRATE_LEVEL_DOCS,
Charisee9cf67802022-06-30 20:04:09 +0000374 DocContext::as_local_hir_id(tcx, krate.module.item_id).unwrap(),
Chariseef7ad1c42023-01-30 22:46:42 +0000375 "no documentation found for this crate's top-level module",
376 |lint| lint.help(help),
Chris Wailes32f78352021-07-20 14:04:55 -0700377 );
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100378 }
379
Chris Wailese3116c42021-07-13 14:40:48 -0700380 fn report_deprecated_attr(name: &str, diag: &rustc_errors::Handler, sp: Span) {
381 let mut msg =
Charisee87880442023-11-01 01:09:07 +0000382 diag.struct_span_warn(sp, format!("the `#![doc({name})]` attribute is deprecated"));
Chris Wailese3116c42021-07-13 14:40:48 -0700383 msg.note(
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100384 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
Charisee7878d542022-02-24 18:21:36 +0000385 for more information",
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100386 );
387
388 if name == "no_default_passes" {
Charisee7878d542022-02-24 18:21:36 +0000389 msg.help("`#![doc(no_default_passes)]` no longer functions; you may want to use `#![doc(document_private_items)]`");
390 } else if name.starts_with("passes") {
391 msg.help("`#![doc(passes = \"...\")]` no longer functions; you may want to use `#![doc(document_private_items)]`");
Chris Wailese3116c42021-07-13 14:40:48 -0700392 } else if name.starts_with("plugins") {
393 msg.warn("`#![doc(plugins = \"...\")]` no longer functions; see CVE-2018-1000622 <https://nvd.nist.gov/vuln/detail/CVE-2018-1000622>");
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100394 }
395
396 msg.emit();
397 }
398
399 // Process all of the crate attributes, extracting plugin metadata along
400 // with the passes which we are supposed to run.
Chris Wailes32f78352021-07-20 14:04:55 -0700401 for attr in krate.module.attrs.lists(sym::doc) {
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100402 let diag = ctxt.sess().diagnostic();
403
404 let name = attr.name_or_empty();
Charisee7878d542022-02-24 18:21:36 +0000405 // `plugins = "..."`, `no_default_passes`, and `passes = "..."` have no effect
406 if attr.is_word() && name == sym::no_default_passes {
407 report_deprecated_attr("no_default_passes", diag, attr.span());
408 } else if attr.value_str().is_some() {
Chris Wailese3116c42021-07-13 14:40:48 -0700409 match name {
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100410 sym::passes => {
Chris Wailese3116c42021-07-13 14:40:48 -0700411 report_deprecated_attr("passes = \"...\"", diag, attr.span());
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100412 }
413 sym::plugins => {
Chris Wailese3116c42021-07-13 14:40:48 -0700414 report_deprecated_attr("plugins = \"...\"", diag, attr.span());
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100415 }
Charisee7878d542022-02-24 18:21:36 +0000416 _ => (),
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100417 }
418 }
419
420 if attr.is_word() && name == sym::document_private_items {
421 ctxt.render_options.document_private = true;
422 }
423 }
424
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100425 info!("Executing passes");
426
Charisee7878d542022-02-24 18:21:36 +0000427 for p in passes::defaults(show_coverage) {
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100428 let run = match p.condition {
429 Always => true,
430 WhenDocumentPrivate => ctxt.render_options.document_private,
431 WhenNotDocumentPrivate => !ctxt.render_options.document_private,
432 WhenNotDocumentHidden => !ctxt.render_options.document_hidden,
433 };
434 if run {
435 debug!("running pass {}", p.pass.name);
Chris Wailes356b57e2022-01-13 10:08:24 -0800436 krate = tcx.sess.time(p.pass.name, || (p.pass.run)(krate, &mut ctxt));
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100437 }
438 }
439
Charisee9cf67802022-06-30 20:04:09 +0000440 tcx.sess.time("check_lint_expectations", || tcx.check_expectations(Some(sym::rustdoc)));
441
Charisee341341c2022-05-20 05:14:50 +0000442 if tcx.sess.diagnostic().has_errors_or_lint_errors().is_some() {
Chris Wailes356b57e2022-01-13 10:08:24 -0800443 rustc_errors::FatalError.raise();
444 }
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100445
Chris Wailes356b57e2022-01-13 10:08:24 -0800446 krate = tcx.sess.time("create_format_cache", || Cache::populate(&mut ctxt, krate));
Chris Wailese3116c42021-07-13 14:40:48 -0700447
Chris Wailes356b57e2022-01-13 10:08:24 -0800448 (krate, ctxt.render_options, ctxt.cache)
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100449}
450
Thiébaud Weksteen5bd94c12021-01-06 15:18:42 +0100451/// Due to <https://github.com/rust-lang/rust/pull/73566>,
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100452/// the name resolution pass may find errors that are never emitted.
453/// If typeck is called after this happens, then we'll get an ICE:
454/// 'Res::Error found but not reported'. To avoid this, emit the errors now.
455struct EmitIgnoredResolutionErrors<'tcx> {
456 tcx: TyCtxt<'tcx>,
457}
458
459impl<'tcx> EmitIgnoredResolutionErrors<'tcx> {
460 fn new(tcx: TyCtxt<'tcx>) -> Self {
461 Self { tcx }
462 }
463}
464
465impl<'tcx> Visitor<'tcx> for EmitIgnoredResolutionErrors<'tcx> {
Chris Wailes2805eef2022-04-07 11:22:56 -0700466 type NestedFilter = nested_filter::OnlyBodies;
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100467
Chris Wailes2805eef2022-04-07 11:22:56 -0700468 fn nested_visit_map(&mut self) -> Self::Map {
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100469 // We need to recurse into nested closures,
470 // since those will fallback to the parent for type checking.
Chris Wailes2805eef2022-04-07 11:22:56 -0700471 self.tcx.hir()
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100472 }
473
Chris Wailes977026a2023-02-13 09:13:10 -0800474 fn visit_path(&mut self, path: &Path<'tcx>, _id: HirId) {
Charisee87880442023-11-01 01:09:07 +0000475 debug!("visiting path {path:?}");
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100476 if path.res == Res::Err {
477 // We have less context here than in rustc_resolve,
478 // so we can only emit the name and span.
479 // However we can give a hint that rustc_resolve will have more info.
480 let label = format!(
481 "could not resolve path `{}`",
482 path.segments
483 .iter()
Chris Wailes2805eef2022-04-07 11:22:56 -0700484 .map(|segment| segment.ident.as_str())
485 .intersperse("::")
486 .collect::<String>()
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100487 );
488 let mut err = rustc_errors::struct_span_err!(
489 self.tcx.sess,
490 path.span,
491 E0433,
Charisee87880442023-11-01 01:09:07 +0000492 "failed to resolve: {label}",
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100493 );
494 err.span_label(path.span, label);
495 err.note("this error was originally ignored because you are running `rustdoc`");
496 err.note("try running again with `rustc` or `cargo check` and you may get a more detailed error");
497 err.emit();
498 }
499 // We could have an outer resolution that succeeded,
500 // but with generic parameters that failed.
501 // Recurse into the segments so we catch those too.
502 intravisit::walk_path(self, path);
503 }
504}
505
Chih-Hung Hsieh8cd2c992019-12-19 15:08:11 -0800506/// `DefId` or parameter index (`ty::ParamTy.index`) of a synthetic type parameter
507/// for `impl Trait` in argument position.
508#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
Chris Wailes65720582022-08-11 09:53:28 -0700509pub(crate) enum ImplTraitParam {
Chih-Hung Hsieh8cd2c992019-12-19 15:08:11 -0800510 DefId(DefId),
511 ParamIndex(u32),
512}
513
514impl From<DefId> for ImplTraitParam {
515 fn from(did: DefId) -> Self {
516 ImplTraitParam::DefId(did)
517 }
518}
519
520impl From<u32> for ImplTraitParam {
521 fn from(idx: u32) -> Self {
522 ImplTraitParam::ParamIndex(idx)
523 }
524}