"Fossies" - the Fresh Open Source Software Archive 
Member "rustc-1.72.1-src/src/librustdoc/core.rs" (13 Sep 2023, 20274 Bytes) of package /linux/misc/rustc-1.72.1-src.tar.xz:
As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Rust source code syntax highlighting (style:
standard) with prefixed line numbers and
code folding option.
Alternatively you can here
view or
download the uninterpreted source code file.
See also the last
Fossies "Diffs" side-by-side code changes report for "core.rs":
1.71.1_vs_1.72.0.
1 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
2 use rustc_data_structures::sync::{self, Lrc};
3 use rustc_data_structures::unord::UnordSet;
4 use rustc_errors::emitter::{Emitter, EmitterWriter};
5 use rustc_errors::json::JsonEmitter;
6 use rustc_errors::TerminalUrl;
7 use rustc_feature::UnstableFeatures;
8 use rustc_hir::def::Res;
9 use rustc_hir::def_id::{DefId, DefIdMap, DefIdSet, LocalDefId};
10 use rustc_hir::intravisit::{self, Visitor};
11 use rustc_hir::{HirId, Path};
12 use rustc_interface::interface;
13 use rustc_middle::hir::nested_filter;
14 use rustc_middle::ty::{ParamEnv, Ty, TyCtxt};
15 use rustc_session::config::{self, CrateType, ErrorOutputType, ResolveDocLinks};
16 use rustc_session::Session;
17 use rustc_session::{lint, EarlyErrorHandler};
18 use rustc_span::symbol::sym;
19 use rustc_span::{source_map, Span};
20
21 use std::cell::RefCell;
22 use std::mem;
23 use std::rc::Rc;
24 use std::sync::LazyLock;
25
26 use crate::clean::inline::build_external_trait;
27 use crate::clean::{self, ItemId};
28 use crate::config::{Options as RustdocOptions, OutputFormat, RenderOptions};
29 use crate::formats::cache::Cache;
30 use crate::passes::{self, Condition::*};
31
32 pub(crate) use rustc_session::config::{Input, Options, UnstableOptions};
33
34 pub(crate) struct DocContext<'tcx> {
35 pub(crate) tcx: TyCtxt<'tcx>,
36 /// Used for normalization.
37 ///
38 /// Most of this logic is copied from rustc_lint::late.
39 pub(crate) param_env: ParamEnv<'tcx>,
40 /// Later on moved through `clean::Crate` into `cache`
41 pub(crate) external_traits: Rc<RefCell<FxHashMap<DefId, clean::Trait>>>,
42 /// Used while populating `external_traits` to ensure we don't process the same trait twice at
43 /// the same time.
44 pub(crate) active_extern_traits: DefIdSet,
45 // The current set of parameter substitutions,
46 // for expanding type aliases at the HIR level:
47 /// Table `DefId` of type, lifetime, or const parameter -> substituted type, lifetime, or const
48 pub(crate) substs: DefIdMap<clean::SubstParam>,
49 pub(crate) current_type_aliases: DefIdMap<usize>,
50 /// Table synthetic type parameter for `impl Trait` in argument position -> bounds
51 pub(crate) impl_trait_bounds: FxHashMap<ImplTraitParam, Vec<clean::GenericBound>>,
52 /// Auto-trait or blanket impls processed so far, as `(self_ty, trait_def_id)`.
53 // FIXME(eddyb) make this a `ty::TraitRef<'tcx>` set.
54 pub(crate) generated_synthetics: FxHashSet<(Ty<'tcx>, DefId)>,
55 pub(crate) auto_traits: Vec<DefId>,
56 /// The options given to rustdoc that could be relevant to a pass.
57 pub(crate) render_options: RenderOptions,
58 /// This same cache is used throughout rustdoc, including in [`crate::html::render`].
59 pub(crate) cache: Cache,
60 /// Used by [`clean::inline`] to tell if an item has already been inlined.
61 pub(crate) inlined: FxHashSet<ItemId>,
62 /// Used by `calculate_doc_coverage`.
63 pub(crate) output_format: OutputFormat,
64 /// Used by `strip_private`.
65 pub(crate) show_coverage: bool,
66 }
67
68 impl<'tcx> DocContext<'tcx> {
69 pub(crate) fn sess(&self) -> &'tcx Session {
70 self.tcx.sess
71 }
72
73 pub(crate) fn with_param_env<T, F: FnOnce(&mut Self) -> T>(
74 &mut self,
75 def_id: DefId,
76 f: F,
77 ) -> T {
78 let old_param_env = mem::replace(&mut self.param_env, self.tcx.param_env(def_id));
79 let ret = f(self);
80 self.param_env = old_param_env;
81 ret
82 }
83
84 /// Call the closure with the given parameters set as
85 /// the substitutions for a type alias' RHS.
86 pub(crate) fn enter_alias<F, R>(
87 &mut self,
88 substs: DefIdMap<clean::SubstParam>,
89 def_id: DefId,
90 f: F,
91 ) -> R
92 where
93 F: FnOnce(&mut Self) -> R,
94 {
95 let old_substs = mem::replace(&mut self.substs, substs);
96 *self.current_type_aliases.entry(def_id).or_insert(0) += 1;
97 let r = f(self);
98 self.substs = old_substs;
99 if let Some(count) = self.current_type_aliases.get_mut(&def_id) {
100 *count -= 1;
101 if *count == 0 {
102 self.current_type_aliases.remove(&def_id);
103 }
104 }
105 r
106 }
107
108 /// Like `hir().local_def_id_to_hir_id()`, but skips calling it on fake DefIds.
109 /// (This avoids a slice-index-out-of-bounds panic.)
110 pub(crate) fn as_local_hir_id(tcx: TyCtxt<'_>, item_id: ItemId) -> Option<HirId> {
111 match item_id {
112 ItemId::DefId(real_id) => {
113 real_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
114 }
115 // FIXME: Can this be `Some` for `Auto` or `Blanket`?
116 _ => None,
117 }
118 }
119 }
120
121 /// Creates a new diagnostic `Handler` that can be used to emit warnings and errors.
122 ///
123 /// If the given `error_format` is `ErrorOutputType::Json` and no `SourceMap` is given, a new one
124 /// will be created for the handler.
125 pub(crate) fn new_handler(
126 error_format: ErrorOutputType,
127 source_map: Option<Lrc<source_map::SourceMap>>,
128 diagnostic_width: Option<usize>,
129 unstable_opts: &UnstableOptions,
130 ) -> rustc_errors::Handler {
131 let fallback_bundle = rustc_errors::fallback_fluent_bundle(
132 rustc_driver::DEFAULT_LOCALE_RESOURCES.to_vec(),
133 false,
134 );
135 let emitter: Box<dyn Emitter + sync::Send> = match error_format {
136 ErrorOutputType::HumanReadable(kind) => {
137 let (short, color_config) = kind.unzip();
138 Box::new(
139 EmitterWriter::stderr(
140 color_config,
141 source_map.map(|sm| sm as _),
142 None,
143 fallback_bundle,
144 short,
145 unstable_opts.teach,
146 diagnostic_width,
147 false,
148 unstable_opts.track_diagnostics,
149 TerminalUrl::No,
150 )
151 .ui_testing(unstable_opts.ui_testing),
152 )
153 }
154 ErrorOutputType::Json { pretty, json_rendered } => {
155 let source_map = source_map.unwrap_or_else(|| {
156 Lrc::new(source_map::SourceMap::new(source_map::FilePathMapping::empty()))
157 });
158 Box::new(
159 JsonEmitter::stderr(
160 None,
161 source_map,
162 None,
163 fallback_bundle,
164 pretty,
165 json_rendered,
166 diagnostic_width,
167 false,
168 unstable_opts.track_diagnostics,
169 TerminalUrl::No,
170 )
171 .ui_testing(unstable_opts.ui_testing),
172 )
173 }
174 };
175
176 rustc_errors::Handler::with_emitter_and_flags(
177 emitter,
178 unstable_opts.diagnostic_handler_flags(true),
179 )
180 }
181
182 /// Parse, resolve, and typecheck the given crate.
183 pub(crate) fn create_config(
184 handler: &EarlyErrorHandler,
185 RustdocOptions {
186 input,
187 crate_name,
188 proc_macro_crate,
189 error_format,
190 diagnostic_width,
191 libs,
192 externs,
193 mut cfgs,
194 check_cfgs,
195 codegen_options,
196 unstable_opts,
197 target,
198 edition,
199 maybe_sysroot,
200 lint_opts,
201 describe_lints,
202 lint_cap,
203 scrape_examples_options,
204 ..
205 }: RustdocOptions,
206 RenderOptions { document_private, .. }: &RenderOptions,
207 ) -> rustc_interface::Config {
208 // Add the doc cfg into the doc build.
209 cfgs.push("doc".to_string());
210
211 let input = Input::File(input);
212
213 // By default, rustdoc ignores all lints.
214 // Specifically unblock lints relevant to documentation or the lint machinery itself.
215 let mut lints_to_show = vec![
216 // it's unclear whether these should be part of rustdoc directly (#77364)
217 rustc_lint::builtin::MISSING_DOCS.name.to_string(),
218 rustc_lint::builtin::INVALID_DOC_ATTRIBUTES.name.to_string(),
219 // these are definitely not part of rustdoc, but we want to warn on them anyway.
220 rustc_lint::builtin::RENAMED_AND_REMOVED_LINTS.name.to_string(),
221 rustc_lint::builtin::UNKNOWN_LINTS.name.to_string(),
222 rustc_lint::builtin::UNEXPECTED_CFGS.name.to_string(),
223 // this lint is needed to support `#[expect]` attributes
224 rustc_lint::builtin::UNFULFILLED_LINT_EXPECTATIONS.name.to_string(),
225 ];
226 lints_to_show.extend(crate::lint::RUSTDOC_LINTS.iter().map(|lint| lint.name.to_string()));
227
228 let (lint_opts, lint_caps) = crate::lint::init_lints(lints_to_show, lint_opts, |lint| {
229 Some((lint.name_lower(), lint::Allow))
230 });
231
232 let crate_types =
233 if proc_macro_crate { vec![CrateType::ProcMacro] } else { vec![CrateType::Rlib] };
234 let resolve_doc_links =
235 if *document_private { ResolveDocLinks::All } else { ResolveDocLinks::Exported };
236 let test = scrape_examples_options.map(|opts| opts.scrape_tests).unwrap_or(false);
237 // plays with error output here!
238 let sessopts = config::Options {
239 maybe_sysroot,
240 search_paths: libs,
241 crate_types,
242 lint_opts,
243 lint_cap,
244 cg: codegen_options,
245 externs,
246 target_triple: target,
247 unstable_features: UnstableFeatures::from_environment(crate_name.as_deref()),
248 actually_rustdoc: true,
249 resolve_doc_links,
250 unstable_opts,
251 error_format,
252 diagnostic_width,
253 edition,
254 describe_lints,
255 crate_name,
256 test,
257 ..Options::default()
258 };
259
260 interface::Config {
261 opts: sessopts,
262 crate_cfg: interface::parse_cfgspecs(handler, cfgs),
263 crate_check_cfg: interface::parse_check_cfg(handler, check_cfgs),
264 input,
265 output_file: None,
266 output_dir: None,
267 file_loader: None,
268 locale_resources: rustc_driver::DEFAULT_LOCALE_RESOURCES,
269 lint_caps,
270 parse_sess_created: None,
271 register_lints: Some(Box::new(crate::lint::register_lints)),
272 override_queries: Some(|_sess, providers, _external_providers| {
273 // Most lints will require typechecking, so just don't run them.
274 providers.lint_mod = |_, _| {};
275 // hack so that `used_trait_imports` won't try to call typeck
276 providers.used_trait_imports = |_, _| {
277 static EMPTY_SET: LazyLock<UnordSet<LocalDefId>> = LazyLock::new(UnordSet::default);
278 &EMPTY_SET
279 };
280 // In case typeck does end up being called, don't ICE in case there were name resolution errors
281 providers.typeck = move |tcx, def_id| {
282 // Closures' tables come from their outermost function,
283 // as they are part of the same "inference environment".
284 // This avoids emitting errors for the parent twice (see similar code in `typeck_with_fallback`)
285 let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id()).expect_local();
286 if typeck_root_def_id != def_id {
287 return tcx.typeck(typeck_root_def_id);
288 }
289
290 let hir = tcx.hir();
291 let body = hir.body(hir.body_owned_by(def_id));
292 debug!("visiting body for {:?}", def_id);
293 EmitIgnoredResolutionErrors::new(tcx).visit_body(body);
294 (rustc_interface::DEFAULT_QUERY_PROVIDERS.typeck)(tcx, def_id)
295 };
296 }),
297 make_codegen_backend: None,
298 registry: rustc_driver::diagnostics_registry(),
299 }
300 }
301
302 pub(crate) fn run_global_ctxt(
303 tcx: TyCtxt<'_>,
304 show_coverage: bool,
305 render_options: RenderOptions,
306 output_format: OutputFormat,
307 ) -> (clean::Crate, RenderOptions, Cache) {
308 // Certain queries assume that some checks were run elsewhere
309 // (see https://github.com/rust-lang/rust/pull/73566#issuecomment-656954425),
310 // so type-check everything other than function bodies in this crate before running lints.
311
312 // NOTE: this does not call `tcx.analysis()` so that we won't
313 // typeck function bodies or run the default rustc lints.
314 // (see `override_queries` in the `config`)
315
316 // HACK(jynelson) this calls an _extremely_ limited subset of `typeck`
317 // and might break if queries change their assumptions in the future.
318 tcx.sess.time("type_collecting", || {
319 tcx.hir().for_each_module(|module| tcx.ensure().collect_mod_item_types(module))
320 });
321
322 // NOTE: This is copy/pasted from typeck/lib.rs and should be kept in sync with those changes.
323 tcx.sess.time("item_types_checking", || {
324 tcx.hir().for_each_module(|module| tcx.ensure().check_mod_item_types(module))
325 });
326 tcx.sess.abort_if_errors();
327 tcx.sess.time("missing_docs", || {
328 rustc_lint::check_crate(tcx, rustc_lint::builtin::MissingDoc::new);
329 });
330 tcx.sess.time("check_mod_attrs", || {
331 tcx.hir().for_each_module(|module| tcx.ensure().check_mod_attrs(module))
332 });
333 rustc_passes::stability::check_unused_or_stable_features(tcx);
334
335 let auto_traits =
336 tcx.all_traits().filter(|&trait_def_id| tcx.trait_is_auto(trait_def_id)).collect();
337
338 let mut ctxt = DocContext {
339 tcx,
340 param_env: ParamEnv::empty(),
341 external_traits: Default::default(),
342 active_extern_traits: Default::default(),
343 substs: Default::default(),
344 current_type_aliases: Default::default(),
345 impl_trait_bounds: Default::default(),
346 generated_synthetics: Default::default(),
347 auto_traits,
348 cache: Cache::new(render_options.document_private),
349 inlined: FxHashSet::default(),
350 output_format,
351 render_options,
352 show_coverage,
353 };
354
355 for cnum in tcx.crates(()) {
356 crate::visit_lib::lib_embargo_visit_item(&mut ctxt, cnum.as_def_id());
357 }
358
359 // Small hack to force the Sized trait to be present.
360 //
361 // Note that in case of `#![no_core]`, the trait is not available.
362 if let Some(sized_trait_did) = ctxt.tcx.lang_items().sized_trait() {
363 let sized_trait = build_external_trait(&mut ctxt, sized_trait_did);
364 ctxt.external_traits.borrow_mut().insert(sized_trait_did, sized_trait);
365 }
366
367 debug!("crate: {:?}", tcx.hir().krate());
368
369 let mut krate = tcx.sess.time("clean_crate", || clean::krate(&mut ctxt));
370
371 if krate.module.doc_value().is_empty() {
372 let help = format!(
373 "The following guide may be of use:\n\
374 {}/rustdoc/how-to-write-documentation.html",
375 crate::DOC_RUST_LANG_ORG_CHANNEL
376 );
377 tcx.struct_lint_node(
378 crate::lint::MISSING_CRATE_LEVEL_DOCS,
379 DocContext::as_local_hir_id(tcx, krate.module.item_id).unwrap(),
380 "no documentation found for this crate's top-level module",
381 |lint| lint.help(help),
382 );
383 }
384
385 fn report_deprecated_attr(name: &str, diag: &rustc_errors::Handler, sp: Span) {
386 let mut msg =
387 diag.struct_span_warn(sp, format!("the `#![doc({})]` attribute is deprecated", name));
388 msg.note(
389 "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
390 for more information",
391 );
392
393 if name == "no_default_passes" {
394 msg.help("`#![doc(no_default_passes)]` no longer functions; you may want to use `#![doc(document_private_items)]`");
395 } else if name.starts_with("passes") {
396 msg.help("`#![doc(passes = \"...\")]` no longer functions; you may want to use `#![doc(document_private_items)]`");
397 } else if name.starts_with("plugins") {
398 msg.warn("`#![doc(plugins = \"...\")]` no longer functions; see CVE-2018-1000622 <https://nvd.nist.gov/vuln/detail/CVE-2018-1000622>");
399 }
400
401 msg.emit();
402 }
403
404 // Process all of the crate attributes, extracting plugin metadata along
405 // with the passes which we are supposed to run.
406 for attr in krate.module.attrs.lists(sym::doc) {
407 let diag = ctxt.sess().diagnostic();
408
409 let name = attr.name_or_empty();
410 // `plugins = "..."`, `no_default_passes`, and `passes = "..."` have no effect
411 if attr.is_word() && name == sym::no_default_passes {
412 report_deprecated_attr("no_default_passes", diag, attr.span());
413 } else if attr.value_str().is_some() {
414 match name {
415 sym::passes => {
416 report_deprecated_attr("passes = \"...\"", diag, attr.span());
417 }
418 sym::plugins => {
419 report_deprecated_attr("plugins = \"...\"", diag, attr.span());
420 }
421 _ => (),
422 }
423 }
424
425 if attr.is_word() && name == sym::document_private_items {
426 ctxt.render_options.document_private = true;
427 }
428 }
429
430 info!("Executing passes");
431
432 for p in passes::defaults(show_coverage) {
433 let run = match p.condition {
434 Always => true,
435 WhenDocumentPrivate => ctxt.render_options.document_private,
436 WhenNotDocumentPrivate => !ctxt.render_options.document_private,
437 WhenNotDocumentHidden => !ctxt.render_options.document_hidden,
438 };
439 if run {
440 debug!("running pass {}", p.pass.name);
441 krate = tcx.sess.time(p.pass.name, || (p.pass.run)(krate, &mut ctxt));
442 }
443 }
444
445 tcx.sess.time("check_lint_expectations", || tcx.check_expectations(Some(sym::rustdoc)));
446
447 if tcx.sess.diagnostic().has_errors_or_lint_errors().is_some() {
448 rustc_errors::FatalError.raise();
449 }
450
451 krate = tcx.sess.time("create_format_cache", || Cache::populate(&mut ctxt, krate));
452
453 (krate, ctxt.render_options, ctxt.cache)
454 }
455
456 /// Due to <https://github.com/rust-lang/rust/pull/73566>,
457 /// the name resolution pass may find errors that are never emitted.
458 /// If typeck is called after this happens, then we'll get an ICE:
459 /// 'Res::Error found but not reported'. To avoid this, emit the errors now.
460 struct EmitIgnoredResolutionErrors<'tcx> {
461 tcx: TyCtxt<'tcx>,
462 }
463
464 impl<'tcx> EmitIgnoredResolutionErrors<'tcx> {
465 fn new(tcx: TyCtxt<'tcx>) -> Self {
466 Self { tcx }
467 }
468 }
469
470 impl<'tcx> Visitor<'tcx> for EmitIgnoredResolutionErrors<'tcx> {
471 type NestedFilter = nested_filter::OnlyBodies;
472
473 fn nested_visit_map(&mut self) -> Self::Map {
474 // We need to recurse into nested closures,
475 // since those will fallback to the parent for type checking.
476 self.tcx.hir()
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 // We have less context here than in rustc_resolve,
483 // so we can only emit the name and span.
484 // However we can give a hint that rustc_resolve will have more info.
485 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 let mut err = rustc_errors::struct_span_err!(
494 self.tcx.sess,
495 path.span,
496 E0433,
497 "failed to resolve: {}",
498 label
499 );
500 err.span_label(path.span, label);
501 err.note("this error was originally ignored because you are running `rustdoc`");
502 err.note("try running again with `rustc` or `cargo check` and you may get a more detailed error");
503 err.emit();
504 }
505 // We could have an outer resolution that succeeded,
506 // but with generic parameters that failed.
507 // Recurse into the segments so we catch those too.
508 intravisit::walk_path(self, path);
509 }
510 }
511
512 /// `DefId` or parameter index (`ty::ParamTy.index`) of a synthetic type parameter
513 /// for `impl Trait` in argument position.
514 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
515 pub(crate) enum ImplTraitParam {
516 DefId(DefId),
517 ParamIndex(u32),
518 }
519
520 impl From<DefId> for ImplTraitParam {
521 fn from(did: DefId) -> Self {
522 ImplTraitParam::DefId(did)
523 }
524 }
525
526 impl From<u32> for ImplTraitParam {
527 fn from(idx: u32) -> Self {
528 ImplTraitParam::ParamIndex(idx)
529 }
530 }