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
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 pub(crate) show_coverage: bool,
80}
81
82impl<'tcx> DocContext<'tcx> {
83 pub(crate) fn sess(&self) -> &'tcx Session {
84 self.tcx.sess
85 }
86
87 pub(crate) fn with_param_env<T, F: FnOnce(&mut Self) -> T>(
88 &mut self,
89 def_id: DefId,
90 f: F,
91 ) -> 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 pub(crate) fn typing_env(&self) -> ty::TypingEnv<'tcx> {
99 ty::TypingEnv::new(self.param_env, ty::TypingMode::non_body_analysis())
100 }
101
102 pub(crate) fn enter_alias<F, R>(
105 &mut self,
106 args: DefIdMap<clean::GenericArg>,
107 def_id: DefId,
108 f: F,
109 ) -> R
110 where
111 F: FnOnce(&mut Self) -> R,
112 {
113 let old_args = mem::replace(&mut self.args, args);
114 *self.current_type_aliases.entry(def_id).or_insert(0) += 1;
115 let r = f(self);
116 self.args = old_args;
117 if let Some(count) = self.current_type_aliases.get_mut(&def_id) {
118 *count -= 1;
119 if *count == 0 {
120 self.current_type_aliases.remove(&def_id);
121 }
122 }
123 r
124 }
125
126 pub(crate) fn as_local_hir_id(tcx: TyCtxt<'_>, item_id: ItemId) -> Option<HirId> {
129 match item_id {
130 ItemId::DefId(real_id) => {
131 real_id.as_local().map(|def_id| tcx.local_def_id_to_hir_id(def_id))
132 }
133 _ => None,
135 }
136 }
137
138 pub(crate) fn is_json_output(&self) -> bool {
142 self.output_format.is_json() && !self.show_coverage
143 }
144
145 pub(crate) fn document_private(&self) -> bool {
147 self.cache.document_private
148 }
149
150 pub(crate) fn document_hidden(&self) -> bool {
152 self.cache.document_hidden
153 }
154}
155
156pub(crate) fn new_dcx(
161 error_format: ErrorOutputType,
162 source_map: Option<Arc<source_map::SourceMap>>,
163 diagnostic_width: Option<usize>,
164 unstable_opts: &UnstableOptions,
165) -> rustc_errors::DiagCtxt {
166 let emitter: Box<DynEmitter> = match error_format {
167 ErrorOutputType::HumanReadable { kind, color_config } => match kind {
168 HumanReadableErrorType { short, unicode } => Box::new(
169 AnnotateSnippetEmitter::new(stderr_destination(color_config))
170 .sm(source_map.map(|sm| sm as _))
171 .short_message(short)
172 .diagnostic_width(diagnostic_width)
173 .track_diagnostics(unstable_opts.track_diagnostics)
174 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
175 .ui_testing(unstable_opts.ui_testing),
176 ),
177 },
178 ErrorOutputType::Json { pretty, json_rendered, color_config } => {
179 let source_map = source_map.unwrap_or_else(|| {
180 Arc::new(source_map::SourceMap::new(source_map::FilePathMapping::empty()))
181 });
182 Box::new(
183 JsonEmitter::new(
184 Box::new(io::BufWriter::new(io::stderr())),
185 Some(source_map),
186 pretty,
187 json_rendered,
188 color_config,
189 )
190 .ui_testing(unstable_opts.ui_testing)
191 .diagnostic_width(diagnostic_width)
192 .track_diagnostics(unstable_opts.track_diagnostics)
193 .terminal_url(TerminalUrl::No),
194 )
195 }
196 };
197
198 rustc_errors::DiagCtxt::new(emitter).with_flags(unstable_opts.dcx_flags(true))
199}
200
201pub(crate) fn create_config(
203 input: Input,
204 RustdocOptions {
205 crate_name,
206 proc_macro_crate,
207 error_format,
208 diagnostic_width,
209 libs,
210 externs,
211 mut cfgs,
212 check_cfgs,
213 codegen_options,
214 unstable_opts,
215 target,
216 edition,
217 sysroot,
218 lint_opts,
219 describe_lints,
220 lint_cap,
221 scrape_examples_options,
222 remap_path_prefix,
223 remap_path_scope,
224 target_modifiers,
225 ..
226 }: RustdocOptions,
227 render_options: &RenderOptions,
228) -> rustc_interface::Config {
229 cfgs.push("doc".to_string());
231
232 let mut lints_to_show = vec![
235 rustc_lint::builtin::MISSING_DOCS.name.to_string(),
237 rustc_lint::builtin::INVALID_DOC_ATTRIBUTES.name.to_string(),
238 rustc_lint::builtin::RENAMED_AND_REMOVED_LINTS.name.to_string(),
240 rustc_lint::builtin::UNKNOWN_LINTS.name.to_string(),
241 rustc_lint::builtin::UNEXPECTED_CFGS.name.to_string(),
242 rustc_lint::builtin::DUPLICATE_FEATURES.name.to_string(),
243 rustc_lint::builtin::UNUSED_FEATURES.name.to_string(),
244 rustc_lint::builtin::STABLE_FEATURES.name.to_string(),
245 rustc_lint::builtin::UNFULFILLED_LINT_EXPECTATIONS.name.to_string(),
247 ];
248 lints_to_show.extend(crate::lint::RUSTDOC_LINTS.iter().map(|lint| lint.name.to_string()));
249
250 let (lint_opts, lint_caps) = crate::lint::init_lints(lints_to_show, lint_opts, |lint| {
251 Some((lint.name_lower(), lint::Allow))
252 });
253
254 let crate_types =
255 if proc_macro_crate { vec![CrateType::ProcMacro] } else { vec![CrateType::Rlib] };
256 let resolve_doc_links = if render_options.document_private {
257 ResolveDocLinks::All
258 } else {
259 ResolveDocLinks::Exported
260 };
261 let test = scrape_examples_options.map(|opts| opts.scrape_tests).unwrap_or(false);
262 let sessopts = config::Options {
264 sysroot,
265 search_paths: libs,
266 crate_types,
267 lint_opts,
268 lint_cap,
269 cg: codegen_options,
270 externs,
271 target_triple: target,
272 unstable_features: UnstableFeatures::from_environment(crate_name.as_deref()),
273 actually_rustdoc: true,
274 resolve_doc_links,
275 unstable_opts,
276 error_format,
277 diagnostic_width,
278 edition,
279 describe_lints,
280 crate_name,
281 test,
282 remap_path_prefix,
283 remap_path_scope,
284 output_types: if let Some(file) = render_options.dep_info() {
285 OutputTypes::new(&[(OutputType::DepInfo, file.cloned())])
286 } else {
287 OutputTypes::new(&[])
288 },
289 target_modifiers,
290 ..Options::default()
291 };
292
293 rustc_interface::Config {
294 opts: sessopts,
295 crate_cfg: cfgs,
296 crate_check_cfg: check_cfgs,
297 input,
298 output_file: None,
299 output_dir: if render_options.output_to_stdout {
300 None
301 } else {
302 Some(render_options.output.clone())
303 },
304 file_loader: None,
305 lint_caps,
306 psess_created: None,
307 track_state: None,
308 register_lints: Some(Box::new(crate::lint::register_lints)),
309 override_queries: Some(|_sess, providers| {
310 providers.queries.lint_mod =
313 |tcx, module_def_id| late_lint_mod(tcx, module_def_id, MissingDoc);
314 providers.queries.used_trait_imports = |_, _| {
316 static EMPTY_SET: LazyLock<UnordSet<LocalDefId>> = LazyLock::new(UnordSet::default);
317 &EMPTY_SET
318 };
319 providers.queries.typeck_root = move |tcx, def_id| {
321 assert!(!tcx.is_typeck_child(def_id.to_def_id()));
323
324 let body = tcx.hir_body_owned_by(def_id);
325 debug!("visiting body for {def_id:?}");
326 EmitIgnoredResolutionErrors::new(tcx).visit_body(body);
327 (rustc_interface::DEFAULT_QUERY_PROVIDERS.queries.typeck_root)(tcx, def_id)
328 };
329 }),
330 extra_symbols: Vec::new(),
331 make_codegen_backend: None,
332 ice_file: None,
333 using_internal_features: &USING_INTERNAL_FEATURES,
334 }
335}
336
337pub(crate) fn run_global_ctxt(
338 tcx: TyCtxt<'_>,
339 show_coverage: bool,
340 render_options: RenderOptions,
341 output_format: OutputFormat,
342) -> (clean::Crate, RenderOptions, Cache, FxHashMap<rustc_span::BytePos, Vec<ExpandedCode>>) {
343 let expanded_macros = {
348 let (_resolver, krate) = &*tcx.resolver_for_lowering().borrow();
351
352 source_macro_expansion(&krate, &render_options, output_format, tcx.sess.source_map())
353 };
354
355 tcx.sess.time("wf_checking", || tcx.ensure_ok().check_type_wf(()));
361
362 tcx.dcx().abort_if_errors();
363
364 tcx.sess.time("missing_docs", || rustc_lint::check_crate(tcx));
365 tcx.sess.time("check_mod_attrs", || {
366 tcx.hir_for_each_module(|module| tcx.ensure_ok().check_mod_attrs(module))
367 });
368 rustc_passes::stability::check_unused_or_stable_features(tcx);
369
370 let auto_traits =
371 tcx.visible_traits().filter(|&trait_def_id| tcx.trait_is_auto(trait_def_id)).collect();
372
373 let mut ctxt = DocContext {
374 tcx,
375 param_env: ParamEnv::empty(),
376 external_traits: Default::default(),
377 active_extern_traits: Default::default(),
378 args: Default::default(),
379 current_type_aliases: Default::default(),
380 impl_trait_bounds: Default::default(),
381 synthetic_auto_trait_impls: Default::default(),
382 synthetic_blanket_impls: Default::default(),
383 auto_traits,
384 cache: Cache::new(render_options.document_private, render_options.document_hidden),
385 inlined: FxHashSet::default(),
386 output_format,
387 show_coverage,
388 };
389
390 for cnum in tcx.crates(()) {
391 crate::visit_lib::lib_embargo_visit_item(&mut ctxt, cnum.as_def_id());
392 }
393
394 if let Some(sized_trait_did) = ctxt.tcx.lang_items().sized_trait() {
398 let sized_trait = build_trait(&mut ctxt, sized_trait_did);
399 ctxt.external_traits.insert(sized_trait_did, sized_trait);
400 }
401
402 let mut krate = tcx.sess.time("clean_crate", || clean::krate(&mut ctxt));
403
404 if krate.module.doc_value().is_empty() {
405 let help = format!(
406 "The following guide may be of use:\n\
407 {}/rustdoc/how-to-write-documentation.html",
408 crate::DOC_RUST_LANG_ORG_VERSION
409 );
410 tcx.emit_node_lint(
411 crate::lint::MISSING_CRATE_LEVEL_DOCS,
412 DocContext::as_local_hir_id(tcx, krate.module.item_id).unwrap(),
413 rustc_errors::DiagDecorator(|lint| {
414 if let Some(local_def_id) = krate.module.item_id.as_local_def_id() {
415 lint.span(tcx.def_span(local_def_id));
416 }
417 lint.primary_message("no documentation found for this crate's top-level module");
418 lint.help(help);
419 }),
420 );
421 }
422
423 info!("Executing passes");
424
425 let mut visited = FxHashMap::default();
426 let mut ambiguous = FxIndexMap::default();
427
428 for p in passes::defaults(show_coverage) {
429 let run = match p.condition {
430 Always => true,
431 WhenDocumentPrivate => ctxt.document_private(),
432 WhenNotDocumentPrivate => !ctxt.document_private(),
433 WhenNotDocumentHidden => !ctxt.document_hidden(),
434 };
435 if run {
436 debug!("running pass {}", p.pass.name);
437 if let Some(run_fn) = p.pass.run {
438 krate = tcx.sess.time(p.pass.name, || run_fn(krate, &mut ctxt));
439 } else {
440 let (k, LinkCollector { visited_links, ambiguous_links, .. }) =
441 passes::collect_intra_doc_links::collect_intra_doc_links(krate, &mut ctxt);
442 krate = k;
443 visited = visited_links;
444 ambiguous = ambiguous_links;
445 }
446 }
447 }
448
449 tcx.sess.time("check_lint_expectations", || tcx.check_expectations(Some(sym::rustdoc)));
450
451 krate =
452 tcx.sess.time("create_format_cache", || Cache::populate(&mut ctxt, krate, &render_options));
453
454 let mut collector =
455 LinkCollector { cx: &mut ctxt, visited_links: visited, ambiguous_links: ambiguous };
456 collector.resolve_ambiguities();
457
458 tcx.dcx().abort_if_errors();
459
460 (krate, render_options, ctxt.cache, expanded_macros)
461}
462
463struct EmitIgnoredResolutionErrors<'tcx> {
468 tcx: TyCtxt<'tcx>,
469}
470
471impl<'tcx> EmitIgnoredResolutionErrors<'tcx> {
472 fn new(tcx: TyCtxt<'tcx>) -> Self {
473 Self { tcx }
474 }
475}
476
477impl<'tcx> Visitor<'tcx> for EmitIgnoredResolutionErrors<'tcx> {
478 type NestedFilter = nested_filter::OnlyBodies;
479
480 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
481 self.tcx
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 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 rustc_errors::struct_span_code_err!(
501 self.tcx.dcx(),
502 path.span,
503 E0433,
504 "failed to resolve: {label}",
505 )
506 .with_span_label(path.span, label)
507 .with_note("this error was originally ignored because you are running `rustdoc`")
508 .with_note("try running again with `rustc` or `cargo check` and you may get a more detailed error")
509 .emit();
510 }
511 intravisit::walk_path(self, path);
515 }
516}
517
518#[derive(Clone, Copy, PartialEq, Eq, Hash)]
521pub(crate) enum ImplTraitParam {
522 DefId(DefId),
523 ParamIndex(u32),
524}
525
526impl From<DefId> for ImplTraitParam {
527 fn from(did: DefId) -> Self {
528 ImplTraitParam::DefId(did)
529 }
530}
531
532impl From<u32> for ImplTraitParam {
533 fn from(idx: u32) -> Self {
534 ImplTraitParam::ParamIndex(idx)
535 }
536}