1use std::sync::{Arc, LazyLock};
2use std::{io, mem};
3
4use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
5use rustc_data_structures::unord::UnordSet;
6use rustc_driver::USING_INTERNAL_FEATURES;
7use rustc_errors::TerminalUrl;
8use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter;
9use rustc_errors::codes::*;
10use rustc_errors::emitter::{DynEmitter, HumanReadableErrorType, OutputTheme, stderr_destination};
11use rustc_errors::json::JsonEmitter;
12use rustc_feature::UnstableFeatures;
13use rustc_hir::def::Res;
14use rustc_hir::def_id::{DefId, DefIdMap, DefIdSet, LocalDefId};
15use rustc_hir::intravisit::{self, Visitor};
16use rustc_hir::{HirId, Path};
17use rustc_lint as lint;
18use rustc_lint::{MissingDoc, late_lint_mod};
19use rustc_middle::hir::nested_filter;
20use rustc_middle::ty::{self, ParamEnv, Ty, TyCtxt};
21use rustc_session::Session;
22use rustc_session::config::{self, Input};
23pub(crate) use rustc_session::config::{Options, UnstableOptions};
24use rustc_session::output::{ErrorOutputType, OutputType, OutputTypes, ResolveDocLinks};
25use rustc_span::source_map;
26use rustc_span::symbol::sym;
27use rustc_structures::CrateType;
28use tracing::debug;
29
30use crate::clean::inline::build_trait;
31use crate::clean::{self, ItemId};
32use crate::config::{Options as RustdocOptions, OutputFormat, RenderOptions};
33use crate::error::Error;
34use crate::formats::cache::Cache;
35use crate::html::macro_expansion::{ExpandedCode, source_macro_expansion};
36use crate::passes;
37
38pub(crate) struct DocContext<'tcx> {
39 pub(crate) tcx: TyCtxt<'tcx>,
40 pub(crate) param_env: ParamEnv<'tcx>,
44 pub(crate) external_traits: FxIndexMap<DefId, clean::Trait>,
46 pub(crate) active_extern_traits: DefIdSet,
49 pub(crate) args: DefIdMap<clean::GenericArg>,
56 pub(crate) current_type_aliases: DefIdMap<usize>,
57 pub(crate) impl_trait_bounds: FxHashMap<ImplTraitParam, Vec<clean::GenericBound>>,
59
60 pub(crate) synthetic_auto_trait_impls: FxHashSet<(Ty<'tcx>, DefId)>,
67 pub(crate) synthetic_blanket_impls: FxHashSet<(Ty<'tcx>, DefId)>,
69
70 pub(crate) auto_traits: Vec<DefId>,
72 pub(crate) cache: Cache,
74 pub(crate) inlined: FxHashSet<ItemId>,
76 pub(crate) output_format: OutputFormat,
78}
79
80impl<'tcx> DocContext<'tcx> {
81 pub(crate) fn sess(&self) -> &'tcx Session {
82 self.tcx.sess
83 }
84
85 pub(crate) fn with_param_env<T, F: FnOnce(&mut Self) -> T>(
86 &mut self,
87 def_id: DefId,
88 f: F,
89 ) -> T {
90 self.with_exact_param_env(self.tcx.param_env(def_id), f)
91 }
92
93 pub(crate) fn with_exact_param_env<T, F: FnOnce(&mut Self) -> T>(
94 &mut self,
95 param_env: ParamEnv<'tcx>,
96 f: F,
97 ) -> T {
98 let old_param_env = mem::replace(&mut self.param_env, param_env);
99 let ret = f(self);
100 self.param_env = old_param_env;
101 ret
102 }
103
104 pub(crate) fn typing_env(&self) -> ty::TypingEnv<'tcx> {
105 ty::TypingEnv::new(self.param_env, ty::TypingMode::non_body_analysis())
106 }
107
108 pub(crate) fn enter_alias<F, R>(
111 &mut self,
112 args: DefIdMap<clean::GenericArg>,
113 def_id: DefId,
114 f: F,
115 ) -> R
116 where
117 F: FnOnce(&mut Self) -> R,
118 {
119 let old_args = mem::replace(&mut self.args, args);
120 *self.current_type_aliases.entry(def_id).or_insert(0) += 1;
121 let r = f(self);
122 self.args = old_args;
123 if let Some(count) = self.current_type_aliases.get_mut(&def_id) {
124 *count -= 1;
125 if *count == 0 {
126 self.current_type_aliases.remove(&def_id);
127 }
128 }
129 r
130 }
131
132 pub(crate) fn as_local_hir_id(tcx: TyCtxt<'_>, item_id: ItemId) -> Option<HirId> {
135 match item_id {
136 ItemId::DefId(real_id) => {
137 real_id.as_local().map(|def_id| tcx.local_def_id_to_hir_id(def_id))
138 }
139 _ => None,
141 }
142 }
143
144 pub(crate) fn is_json_output(&self) -> bool {
148 self.output_format == OutputFormat::IrJson
149 }
150
151 pub(crate) fn document_private(&self) -> bool {
153 self.cache.document_private
154 }
155
156 pub(crate) fn document_hidden(&self) -> bool {
158 self.cache.document_hidden
159 }
160}
161
162pub(crate) fn new_dcx(
167 error_format: ErrorOutputType,
168 source_map: Option<Arc<source_map::SourceMap>>,
169 diagnostic_width: Option<usize>,
170 unstable_opts: &UnstableOptions,
171) -> rustc_errors::DiagCtxt {
172 let emitter: Box<DynEmitter> = match error_format {
173 ErrorOutputType::HumanReadable { kind, color_config } => match kind {
174 HumanReadableErrorType { no_graphics, short, unicode } => Box::new(
175 AnnotateSnippetEmitter::new(stderr_destination(color_config))
176 .sm(source_map.map(|sm| sm as _))
177 .short_message(short)
178 .diagnostic_width(diagnostic_width)
179 .track_diagnostics(unstable_opts.track_diagnostics)
180 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
181 .ui_testing(unstable_opts.ui_testing)
182 .no_graphics(no_graphics),
183 ),
184 },
185 ErrorOutputType::Json { pretty, json_rendered, color_config } => {
186 let source_map = source_map.unwrap_or_else(|| {
187 Arc::new(source_map::SourceMap::new(source_map::FilePathMapping::empty()))
188 });
189 Box::new(
190 JsonEmitter::new(
191 Box::new(io::BufWriter::new(io::stderr())),
192 Some(source_map),
193 pretty,
194 json_rendered,
195 color_config,
196 )
197 .ui_testing(unstable_opts.ui_testing)
198 .diagnostic_width(diagnostic_width)
199 .track_diagnostics(unstable_opts.track_diagnostics)
200 .terminal_url(TerminalUrl::No),
201 )
202 }
203 };
204
205 rustc_errors::DiagCtxt::new(emitter).with_flags(unstable_opts.dcx_flags(true))
206}
207
208pub(crate) fn create_config(
210 input: Input,
211 RustdocOptions {
212 crate_name,
213 proc_macro_crate,
214 error_format,
215 diagnostic_width,
216 libs,
217 externs,
218 mut cfgs,
219 check_cfgs,
220 codegen_options,
221 unstable_opts,
222 target,
223 edition,
224 sysroot,
225 lint_opts,
226 describe_lints,
227 lint_cap,
228 prints,
229 scrape_examples_options,
230 remap_path_prefix,
231 remap_path_scope,
232 target_modifiers,
233 ..
234 }: RustdocOptions,
235 render_options: &RenderOptions,
236) -> rustc_interface::Config {
237 cfgs.push("doc".to_string());
239
240 let mut lints_to_show = vec![
243 rustc_lint::builtin::MISSING_DOCS.name.to_string(),
245 rustc_lint::builtin::INVALID_DOC_ATTRIBUTES.name.to_string(),
246 rustc_lint::builtin::UNUSED_DOC_COMMENTS.name.to_string(),
247 rustc_lint::builtin::RENAMED_AND_REMOVED_LINTS.name.to_string(),
249 rustc_lint::builtin::UNKNOWN_LINTS.name.to_string(),
250 rustc_lint::builtin::UNEXPECTED_CFGS.name.to_string(),
251 rustc_lint::builtin::DUPLICATE_FEATURES.name.to_string(),
252 rustc_lint::builtin::UNUSED_FEATURES.name.to_string(),
253 rustc_lint::builtin::STABLE_FEATURES.name.to_string(),
254 rustc_lint::builtin::UNFULFILLED_LINT_EXPECTATIONS.name.to_string(),
256 ];
257 lints_to_show.extend(crate::lint::RUSTDOC_LINTS.iter().map(|lint| lint.name.to_string()));
258
259 let (lint_opts, lint_caps) = crate::lint::init_lints(lints_to_show, lint_opts, |lint| {
260 Some((lint.name_lower(), lint::Allow))
261 });
262
263 let crate_types =
264 if proc_macro_crate { vec![CrateType::ProcMacro] } else { vec![CrateType::Rlib] };
265 let resolve_doc_links = if render_options.document_private {
266 ResolveDocLinks::All
267 } else {
268 ResolveDocLinks::Exported
269 };
270 let test = scrape_examples_options.map(|opts| opts.scrape_tests).unwrap_or(false);
271 let sessopts = config::Options {
273 sysroot,
274 search_paths: libs,
275 crate_types,
276 lint_opts,
277 lint_cap,
278 cg: codegen_options,
279 externs,
280 target_triple: target,
281 unstable_features: UnstableFeatures::from_environment(crate_name.as_deref()),
282 actually_rustdoc: true,
283 resolve_doc_links,
284 unstable_opts,
285 error_format,
286 diagnostic_width,
287 edition,
288 describe_lints,
289 prints,
290 crate_name,
291 test,
292 remap_path_prefix,
293 remap_path_scope,
294 output_types: if let Some(file) = render_options.dep_info() {
295 OutputTypes::new(&[(OutputType::DepInfo, file.cloned())])
296 } else {
297 OutputTypes::new(&[])
298 },
299 target_modifiers,
300 ..Options::default()
301 };
302
303 rustc_interface::Config {
304 opts: sessopts,
305 crate_cfg: cfgs,
306 crate_check_cfg: check_cfgs,
307 input,
308 output_file: None,
309 output_dir: if render_options.output_to_stdout {
310 None
311 } else {
312 Some(render_options.output.clone())
313 },
314 file_loader: None,
315 lint_caps,
316 psess_created: None,
317 track_state: None,
318 register_lints: Some(Box::new(crate::lint::register_lints)),
319 override_queries: Some(|_sess, providers| {
320 providers.queries.lint_mod =
323 |tcx, module_def_id| late_lint_mod(tcx, module_def_id, MissingDoc);
324 providers.queries.used_trait_imports = |_, _| {
326 static EMPTY_SET: LazyLock<UnordSet<LocalDefId>> = LazyLock::new(UnordSet::default);
327 &EMPTY_SET
328 };
329 providers.queries.typeck_root = move |tcx, def_id| {
331 assert!(!tcx.is_typeck_child(def_id.to_def_id()));
333
334 let body = tcx.hir_body_owned_by(def_id);
335 debug!("visiting body for {def_id:?}");
336 EmitIgnoredResolutionErrors::new(tcx).visit_body(body);
337 (rustc_interface::DEFAULT_QUERY_PROVIDERS.queries.typeck_root)(tcx, def_id)
338 };
339 }),
340 extra_symbols: Vec::new(),
341 make_codegen_backend: None,
342 ice_file: None,
343 using_internal_features: &USING_INTERNAL_FEATURES,
344 }
345}
346
347pub(crate) fn run_global_ctxt(
348 tcx: TyCtxt<'_>,
349 show_coverage: bool,
350 render_options: RenderOptions,
351 output_format: OutputFormat,
352) -> Result<
353 (clean::Crate, RenderOptions, Cache, FxHashMap<rustc_span::BytePos, Vec<ExpandedCode>>),
354 Error,
355> {
356 let expanded_macros = {
361 let krate = &*tcx.resolver_for_lowering().1.borrow();
364
365 source_macro_expansion(&krate, &render_options, output_format, tcx.sess.source_map())
366 };
367
368 tcx.sess.time("wf_checking", || tcx.ensure_ok().check_type_wf(()));
374 tcx.sess.time("check_mod_attrs", || {
375 tcx.hir_for_each_module(|module| tcx.ensure_ok().check_mod_attrs(module))
376 });
377 rustc_interface::passes::emit_delayed_lints(tcx);
378
379 tcx.dcx().abort_if_errors();
380
381 tcx.sess.time("missing_docs", || rustc_lint::check_crate(tcx));
382 rustc_passes::stability::check_unused_or_stable_features(tcx);
383
384 let auto_traits =
385 tcx.visible_traits().filter(|&trait_def_id| tcx.trait_is_auto(trait_def_id)).collect();
386
387 let mut ctxt = DocContext {
388 tcx,
389 param_env: ParamEnv::empty(),
390 external_traits: Default::default(),
391 active_extern_traits: Default::default(),
392 args: Default::default(),
393 current_type_aliases: Default::default(),
394 impl_trait_bounds: Default::default(),
395 synthetic_auto_trait_impls: Default::default(),
396 synthetic_blanket_impls: Default::default(),
397 auto_traits,
398 cache: Cache::new(render_options.document_private, render_options.document_hidden),
399 inlined: FxHashSet::default(),
400 output_format,
401 };
402
403 for cnum in tcx.crates(()) {
404 crate::visit_lib::lib_embargo_visit_item(&mut ctxt, cnum.as_def_id());
405 }
406
407 if let Some(sized_trait_did) = ctxt.tcx.lang_items().sized_trait() {
411 let sized_trait = build_trait(&mut ctxt, sized_trait_did);
412 ctxt.external_traits.insert(sized_trait_did, sized_trait);
413 }
414
415 let mut krate = tcx.sess.time("clean_crate", || clean::krate(&mut ctxt));
416
417 if krate.module.doc_value().is_empty() {
418 let help = format!(
419 "The following guide may be of use:\n\
420 {}/rustdoc/how-to-write-documentation.html",
421 crate::DOC_RUST_LANG_ORG_VERSION
422 );
423 tcx.emit_node_lint(
424 crate::lint::MISSING_CRATE_LEVEL_DOCS,
425 DocContext::as_local_hir_id(tcx, krate.module.item_id).unwrap(),
426 rustc_errors::DiagDecorator(|lint| {
427 if let Some(local_def_id) = krate.module.item_id.as_local_def_id() {
428 lint.span(tcx.def_span(local_def_id));
429 }
430 lint.primary_message("no documentation found for this crate's top-level module");
431 lint.help(help);
432 }),
433 );
434 }
435
436 let store;
437 (krate, store) = passes::run(krate, &mut ctxt, show_coverage);
438
439 if show_coverage {
440 crate::calculate_doc_coverage::run(&krate, &mut ctxt, &render_options)?;
441 }
442
443 tcx.sess.time("check_lint_expectations", || tcx.check_expectations(Some(sym::rustdoc)));
444
445 krate =
446 tcx.sess.time("create_format_cache", || Cache::populate(&mut ctxt, krate, &render_options));
447
448 passes::finalize(&mut ctxt, store);
449
450 tcx.dcx().abort_if_errors();
451
452 Ok((krate, render_options, ctxt.cache, expanded_macros))
453}
454
455struct EmitIgnoredResolutionErrors<'tcx> {
460 tcx: TyCtxt<'tcx>,
461}
462
463impl<'tcx> EmitIgnoredResolutionErrors<'tcx> {
464 fn new(tcx: TyCtxt<'tcx>) -> Self {
465 Self { tcx }
466 }
467}
468
469impl<'tcx> Visitor<'tcx> for EmitIgnoredResolutionErrors<'tcx> {
470 type NestedFilter = nested_filter::OnlyBodies;
471
472 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
473 self.tcx
476 }
477
478 fn visit_path(&mut self, path: &Path<'tcx>, _id: HirId) {
479 debug!("visiting path {path:?}");
480 if path.res == Res::Err {
481 let label = format!(
485 "could not resolve path `{}`",
486 path.segments
487 .iter()
488 .map(|segment| segment.ident.as_str())
489 .intersperse("::")
490 .collect::<String>()
491 );
492 rustc_errors::struct_span_code_err!(
493 self.tcx.dcx(),
494 path.span,
495 E0433,
496 "failed to resolve: {label}",
497 )
498 .with_span_label(path.span, label)
499 .with_note("this error was originally ignored because you are running `rustdoc`")
500 .with_note("try running again with `rustc` or `cargo check` and you may get a more detailed error")
501 .emit();
502 }
503 intravisit::walk_path(self, path);
507 }
508}
509
510#[derive(Clone, Copy, PartialEq, Eq, Hash)]
513pub(crate) enum ImplTraitParam {
514 DefId(DefId),
515 ParamIndex(u32),
516}
517
518impl From<DefId> for ImplTraitParam {
519 fn from(did: DefId) -> Self {
520 ImplTraitParam::DefId(did)
521 }
522}
523
524impl From<u32> for ImplTraitParam {
525 fn from(idx: u32) -> Self {
526 ImplTraitParam::ParamIndex(idx)
527 }
528}