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