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