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::{MissingDoc, late_lint_mod};
18use rustc_middle::hir::nested_filter;
19use rustc_middle::ty::{self, ParamEnv, Ty, TyCtxt};
20use rustc_session::config::{
21 self, CrateType, ErrorOutputType, Input, OutputType, OutputTypes, ResolveDocLinks,
22};
23pub(crate) use rustc_session::config::{Options, UnstableOptions};
24use rustc_session::{Session, lint};
25use rustc_span::source_map;
26use rustc_span::symbol::sym;
27use tracing::{debug, info};
28
29use crate::clean::inline::build_trait;
30use crate::clean::{self, ItemId};
31use crate::config::{Options as RustdocOptions, OutputFormat, RenderOptions};
32use crate::formats::cache::Cache;
33use crate::html::macro_expansion::{ExpandedCode, source_macro_expansion};
34use crate::passes;
35use crate::passes::Condition::*;
36use crate::passes::collect_intra_doc_links::LinkCollector;
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 pub(crate) generated_synthetics: FxHashSet<(Ty<'tcx>, DefId)>,
62 pub(crate) auto_traits: Vec<DefId>,
63 pub(crate) cache: Cache,
65 pub(crate) inlined: FxHashSet<ItemId>,
67 pub(crate) output_format: OutputFormat,
69 pub(crate) show_coverage: bool,
71}
72
73impl<'tcx> DocContext<'tcx> {
74 pub(crate) fn sess(&self) -> &'tcx Session {
75 self.tcx.sess
76 }
77
78 pub(crate) fn with_param_env<T, F: FnOnce(&mut Self) -> T>(
79 &mut self,
80 def_id: DefId,
81 f: F,
82 ) -> T {
83 let old_param_env = mem::replace(&mut self.param_env, self.tcx.param_env(def_id));
84 let ret = f(self);
85 self.param_env = old_param_env;
86 ret
87 }
88
89 pub(crate) fn typing_env(&self) -> ty::TypingEnv<'tcx> {
90 ty::TypingEnv {
91 typing_mode: ty::TypingMode::non_body_analysis(),
92 param_env: self.param_env,
93 }
94 }
95
96 pub(crate) fn enter_alias<F, R>(
99 &mut self,
100 args: DefIdMap<clean::GenericArg>,
101 def_id: DefId,
102 f: F,
103 ) -> R
104 where
105 F: FnOnce(&mut Self) -> R,
106 {
107 let old_args = mem::replace(&mut self.args, args);
108 *self.current_type_aliases.entry(def_id).or_insert(0) += 1;
109 let r = f(self);
110 self.args = old_args;
111 if let Some(count) = self.current_type_aliases.get_mut(&def_id) {
112 *count -= 1;
113 if *count == 0 {
114 self.current_type_aliases.remove(&def_id);
115 }
116 }
117 r
118 }
119
120 pub(crate) fn as_local_hir_id(tcx: TyCtxt<'_>, item_id: ItemId) -> Option<HirId> {
123 match item_id {
124 ItemId::DefId(real_id) => {
125 real_id.as_local().map(|def_id| tcx.local_def_id_to_hir_id(def_id))
126 }
127 _ => None,
129 }
130 }
131
132 pub(crate) fn is_json_output(&self) -> bool {
136 self.output_format.is_json() && !self.show_coverage
137 }
138
139 pub(crate) fn document_private(&self) -> bool {
141 self.cache.document_private
142 }
143
144 pub(crate) fn document_hidden(&self) -> bool {
146 self.cache.document_hidden
147 }
148}
149
150pub(crate) fn new_dcx(
155 error_format: ErrorOutputType,
156 source_map: Option<Arc<source_map::SourceMap>>,
157 diagnostic_width: Option<usize>,
158 unstable_opts: &UnstableOptions,
159) -> rustc_errors::DiagCtxt {
160 let translator = rustc_driver::default_translator();
161 let emitter: Box<DynEmitter> = match error_format {
162 ErrorOutputType::HumanReadable { kind, color_config } => match kind {
163 HumanReadableErrorType { short, unicode } => Box::new(
164 AnnotateSnippetEmitter::new(stderr_destination(color_config), translator)
165 .sm(source_map.map(|sm| sm as _))
166 .short_message(short)
167 .diagnostic_width(diagnostic_width)
168 .track_diagnostics(unstable_opts.track_diagnostics)
169 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
170 .ui_testing(unstable_opts.ui_testing),
171 ),
172 },
173 ErrorOutputType::Json { pretty, json_rendered, color_config } => {
174 let source_map = source_map.unwrap_or_else(|| {
175 Arc::new(source_map::SourceMap::new(source_map::FilePathMapping::empty()))
176 });
177 Box::new(
178 JsonEmitter::new(
179 Box::new(io::BufWriter::new(io::stderr())),
180 Some(source_map),
181 translator,
182 pretty,
183 json_rendered,
184 color_config,
185 )
186 .ui_testing(unstable_opts.ui_testing)
187 .diagnostic_width(diagnostic_width)
188 .track_diagnostics(unstable_opts.track_diagnostics)
189 .terminal_url(TerminalUrl::No),
190 )
191 }
192 };
193
194 rustc_errors::DiagCtxt::new(emitter).with_flags(unstable_opts.dcx_flags(true))
195}
196
197pub(crate) fn create_config(
199 input: Input,
200 RustdocOptions {
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 sysroot,
214 lint_opts,
215 describe_lints,
216 lint_cap,
217 scrape_examples_options,
218 remap_path_prefix,
219 target_modifiers,
220 ..
221 }: RustdocOptions,
222 render_options: &RenderOptions,
223) -> rustc_interface::Config {
224 cfgs.push("doc".to_string());
226
227 let mut lints_to_show = vec![
230 rustc_lint::builtin::MISSING_DOCS.name.to_string(),
232 rustc_lint::builtin::INVALID_DOC_ATTRIBUTES.name.to_string(),
233 rustc_lint::builtin::RENAMED_AND_REMOVED_LINTS.name.to_string(),
235 rustc_lint::builtin::UNKNOWN_LINTS.name.to_string(),
236 rustc_lint::builtin::UNEXPECTED_CFGS.name.to_string(),
237 rustc_lint::builtin::UNFULFILLED_LINT_EXPECTATIONS.name.to_string(),
239 ];
240 lints_to_show.extend(crate::lint::RUSTDOC_LINTS.iter().map(|lint| lint.name.to_string()));
241
242 let (lint_opts, lint_caps) = crate::lint::init_lints(lints_to_show, lint_opts, |lint| {
243 Some((lint.name_lower(), lint::Allow))
244 });
245
246 let crate_types =
247 if proc_macro_crate { vec![CrateType::ProcMacro] } else { vec![CrateType::Rlib] };
248 let resolve_doc_links = if render_options.document_private {
249 ResolveDocLinks::All
250 } else {
251 ResolveDocLinks::Exported
252 };
253 let test = scrape_examples_options.map(|opts| opts.scrape_tests).unwrap_or(false);
254 let sessopts = config::Options {
256 sysroot,
257 search_paths: libs,
258 crate_types,
259 lint_opts,
260 lint_cap,
261 cg: codegen_options,
262 externs,
263 target_triple: target,
264 unstable_features: UnstableFeatures::from_environment(crate_name.as_deref()),
265 actually_rustdoc: true,
266 resolve_doc_links,
267 unstable_opts,
268 error_format,
269 diagnostic_width,
270 edition,
271 describe_lints,
272 crate_name,
273 test,
274 remap_path_prefix,
275 output_types: if let Some(file) = render_options.dep_info() {
276 OutputTypes::new(&[(OutputType::DepInfo, file.cloned())])
277 } else {
278 OutputTypes::new(&[])
279 },
280 target_modifiers,
281 ..Options::default()
282 };
283
284 rustc_interface::Config {
285 opts: sessopts,
286 crate_cfg: cfgs,
287 crate_check_cfg: check_cfgs,
288 input,
289 output_file: None,
290 output_dir: None,
291 file_loader: None,
292 locale_resources: rustc_driver::DEFAULT_LOCALE_RESOURCES.to_vec(),
293 lint_caps,
294 psess_created: None,
295 hash_untracked_state: None,
296 register_lints: Some(Box::new(crate::lint::register_lints)),
297 override_queries: Some(|_sess, providers| {
298 providers.queries.lint_mod =
301 |tcx, module_def_id| late_lint_mod(tcx, module_def_id, MissingDoc);
302 providers.queries.used_trait_imports = |_, _| {
304 static EMPTY_SET: LazyLock<UnordSet<LocalDefId>> = LazyLock::new(UnordSet::default);
305 &EMPTY_SET
306 };
307 providers.queries.typeck = move |tcx, def_id| {
309 let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id()).expect_local();
313 if typeck_root_def_id != def_id {
314 return tcx.typeck(typeck_root_def_id);
315 }
316
317 let body = tcx.hir_body_owned_by(def_id);
318 debug!("visiting body for {def_id:?}");
319 EmitIgnoredResolutionErrors::new(tcx).visit_body(body);
320 (rustc_interface::DEFAULT_QUERY_PROVIDERS.queries.typeck)(tcx, def_id)
321 };
322 }),
323 extra_symbols: Vec::new(),
324 make_codegen_backend: None,
325 registry: rustc_driver::diagnostics_registry(),
326 ice_file: None,
327 using_internal_features: &USING_INTERNAL_FEATURES,
328 }
329}
330
331pub(crate) fn run_global_ctxt(
332 tcx: TyCtxt<'_>,
333 show_coverage: bool,
334 render_options: RenderOptions,
335 output_format: OutputFormat,
336) -> (clean::Crate, RenderOptions, Cache, FxHashMap<rustc_span::BytePos, Vec<ExpandedCode>>) {
337 let expanded_macros = {
342 let (_resolver, krate) = &*tcx.resolver_for_lowering().borrow();
345
346 source_macro_expansion(&krate, &render_options, output_format, tcx.sess.source_map())
347 };
348
349 let _ = tcx.sess.time("wf_checking", || tcx.ensure_ok().check_type_wf(()));
355
356 tcx.dcx().abort_if_errors();
357
358 tcx.sess.time("missing_docs", || rustc_lint::check_crate(tcx));
359 tcx.sess.time("check_mod_attrs", || {
360 tcx.hir_for_each_module(|module| tcx.ensure_ok().check_mod_attrs(module))
361 });
362 rustc_passes::stability::check_unused_or_stable_features(tcx);
363
364 let auto_traits =
365 tcx.visible_traits().filter(|&trait_def_id| tcx.trait_is_auto(trait_def_id)).collect();
366
367 let mut ctxt = DocContext {
368 tcx,
369 param_env: ParamEnv::empty(),
370 external_traits: Default::default(),
371 active_extern_traits: Default::default(),
372 args: Default::default(),
373 current_type_aliases: Default::default(),
374 impl_trait_bounds: Default::default(),
375 generated_synthetics: Default::default(),
376 auto_traits,
377 cache: Cache::new(render_options.document_private, render_options.document_hidden),
378 inlined: FxHashSet::default(),
379 output_format,
380 show_coverage,
381 };
382
383 for cnum in tcx.crates(()) {
384 crate::visit_lib::lib_embargo_visit_item(&mut ctxt, cnum.as_def_id());
385 }
386
387 if let Some(sized_trait_did) = ctxt.tcx.lang_items().sized_trait() {
391 let sized_trait = build_trait(&mut ctxt, sized_trait_did);
392 ctxt.external_traits.insert(sized_trait_did, sized_trait);
393 }
394
395 let mut krate = tcx.sess.time("clean_crate", || clean::krate(&mut ctxt));
396
397 if krate.module.doc_value().is_empty() {
398 let help = format!(
399 "The following guide may be of use:\n\
400 {}/rustdoc/how-to-write-documentation.html",
401 crate::DOC_RUST_LANG_ORG_VERSION
402 );
403 tcx.node_lint(
404 crate::lint::MISSING_CRATE_LEVEL_DOCS,
405 DocContext::as_local_hir_id(tcx, krate.module.item_id).unwrap(),
406 |lint| {
407 if let Some(local_def_id) = krate.module.item_id.as_local_def_id() {
408 lint.span(tcx.def_span(local_def_id));
409 }
410 lint.primary_message("no documentation found for this crate's top-level module");
411 lint.help(help);
412 },
413 );
414 }
415
416 info!("Executing passes");
417
418 let mut visited = FxHashMap::default();
419 let mut ambiguous = FxIndexMap::default();
420
421 for p in passes::defaults(show_coverage) {
422 let run = match p.condition {
423 Always => true,
424 WhenDocumentPrivate => ctxt.document_private(),
425 WhenNotDocumentPrivate => !ctxt.document_private(),
426 WhenNotDocumentHidden => !ctxt.document_hidden(),
427 };
428 if run {
429 debug!("running pass {}", p.pass.name);
430 if let Some(run_fn) = p.pass.run {
431 krate = tcx.sess.time(p.pass.name, || run_fn(krate, &mut ctxt));
432 } else {
433 let (k, LinkCollector { visited_links, ambiguous_links, .. }) =
434 passes::collect_intra_doc_links::collect_intra_doc_links(krate, &mut ctxt);
435 krate = k;
436 visited = visited_links;
437 ambiguous = ambiguous_links;
438 }
439 }
440 }
441
442 tcx.sess.time("check_lint_expectations", || tcx.check_expectations(Some(sym::rustdoc)));
443
444 krate =
445 tcx.sess.time("create_format_cache", || Cache::populate(&mut ctxt, krate, &render_options));
446
447 let mut collector =
448 LinkCollector { cx: &mut ctxt, visited_links: visited, ambiguous_links: ambiguous };
449 collector.resolve_ambiguities();
450
451 tcx.dcx().abort_if_errors();
452
453 (krate, render_options, ctxt.cache, expanded_macros)
454}
455
456struct EmitIgnoredResolutionErrors<'tcx> {
461 tcx: TyCtxt<'tcx>,
462}
463
464impl<'tcx> EmitIgnoredResolutionErrors<'tcx> {
465 fn new(tcx: TyCtxt<'tcx>) -> Self {
466 Self { tcx }
467 }
468}
469
470impl<'tcx> Visitor<'tcx> for EmitIgnoredResolutionErrors<'tcx> {
471 type NestedFilter = nested_filter::OnlyBodies;
472
473 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
474 self.tcx
477 }
478
479 fn visit_path(&mut self, path: &Path<'tcx>, _id: HirId) {
480 debug!("visiting path {path:?}");
481 if path.res == Res::Err {
482 let label = format!(
486 "could not resolve path `{}`",
487 path.segments
488 .iter()
489 .map(|segment| segment.ident.as_str())
490 .intersperse("::")
491 .collect::<String>()
492 );
493 rustc_errors::struct_span_code_err!(
494 self.tcx.dcx(),
495 path.span,
496 E0433,
497 "failed to resolve: {label}",
498 )
499 .with_span_label(path.span, label)
500 .with_note("this error was originally ignored because you are running `rustdoc`")
501 .with_note("try running again with `rustc` or `cargo check` and you may get a more detailed error")
502 .emit();
503 }
504 intravisit::walk_path(self, path);
508 }
509}
510
511#[derive(Clone, Copy, PartialEq, Eq, Hash)]
514pub(crate) enum ImplTraitParam {
515 DefId(DefId),
516 ParamIndex(u32),
517}
518
519impl From<DefId> for ImplTraitParam {
520 fn from(did: DefId) -> Self {
521 ImplTraitParam::DefId(did)
522 }
523}
524
525impl From<u32> for ImplTraitParam {
526 fn from(idx: u32) -> Self {
527 ImplTraitParam::ParamIndex(idx)
528 }
529}