1 //! Contains information about "passes", used to modify crate information during the documentation
4 use rustc_hir::def_id::{DefId, DefIdSet};
5 use rustc_middle::middle::privacy::AccessLevels;
6 use rustc_session::lint;
7 use rustc_span::{InnerSpan, Span, DUMMY_SP};
11 use self::Condition::*;
12 use crate::clean::{self, GetDefId, Item};
13 use crate::core::DocContext;
14 use crate::fold::{DocFolder, StripItem};
15 use crate::html::markdown::{find_testable_code, ErrorCodes, LangString};
18 pub use self::collapse_docs::COLLAPSE_DOCS;
21 pub use self::strip_hidden::STRIP_HIDDEN;
24 pub use self::strip_private::STRIP_PRIVATE;
26 mod strip_priv_imports;
27 pub use self::strip_priv_imports::STRIP_PRIV_IMPORTS;
29 mod unindent_comments;
30 pub use self::unindent_comments::UNINDENT_COMMENTS;
32 mod propagate_doc_cfg;
33 pub use self::propagate_doc_cfg::PROPAGATE_DOC_CFG;
35 mod collect_intra_doc_links;
36 pub use self::collect_intra_doc_links::COLLECT_INTRA_DOC_LINKS;
38 mod private_items_doc_tests;
39 pub use self::private_items_doc_tests::CHECK_PRIVATE_ITEMS_DOC_TESTS;
41 mod collect_trait_impls;
42 pub use self::collect_trait_impls::COLLECT_TRAIT_IMPLS;
44 mod check_code_block_syntax;
45 pub use self::check_code_block_syntax::CHECK_CODE_BLOCK_SYNTAX;
47 mod calculate_doc_coverage;
48 pub use self::calculate_doc_coverage::CALCULATE_DOC_COVERAGE;
50 /// A single pass over the cleaned documentation.
52 /// Runs in the compiler context, so it has access to types and traits and the like.
53 #[derive(Copy, Clone)]
55 pub name: &'static str,
56 pub run: fn(clean::Crate, &DocContext<'_>) -> clean::Crate,
57 pub description: &'static str,
60 /// In a list of passes, a pass that may or may not need to be run depending on options.
61 #[derive(Copy, Clone)]
62 pub struct ConditionalPass {
64 pub condition: Condition,
67 /// How to decide whether to run a conditional pass.
68 #[derive(Copy, Clone)]
71 /// When `--document-private-items` is passed.
73 /// When `--document-private-items` is not passed.
74 WhenNotDocumentPrivate,
75 /// When `--document-hidden-items` is not passed.
76 WhenNotDocumentHidden,
79 /// The full list of passes.
80 pub const PASSES: &[Pass] = &[
81 CHECK_PRIVATE_ITEMS_DOC_TESTS,
88 COLLECT_INTRA_DOC_LINKS,
89 CHECK_CODE_BLOCK_SYNTAX,
91 CALCULATE_DOC_COVERAGE,
94 /// The list of passes run by default.
95 pub const DEFAULT_PASSES: &[ConditionalPass] = &[
96 ConditionalPass::always(COLLECT_TRAIT_IMPLS),
97 ConditionalPass::always(COLLAPSE_DOCS),
98 ConditionalPass::always(UNINDENT_COMMENTS),
99 ConditionalPass::always(CHECK_PRIVATE_ITEMS_DOC_TESTS),
100 ConditionalPass::new(STRIP_HIDDEN, WhenNotDocumentHidden),
101 ConditionalPass::new(STRIP_PRIVATE, WhenNotDocumentPrivate),
102 ConditionalPass::new(STRIP_PRIV_IMPORTS, WhenDocumentPrivate),
103 ConditionalPass::always(COLLECT_INTRA_DOC_LINKS),
104 ConditionalPass::always(CHECK_CODE_BLOCK_SYNTAX),
105 ConditionalPass::always(PROPAGATE_DOC_CFG),
108 /// The list of default passes run when `--doc-coverage` is passed to rustdoc.
109 pub const COVERAGE_PASSES: &[ConditionalPass] = &[
110 ConditionalPass::always(COLLECT_TRAIT_IMPLS),
111 ConditionalPass::new(STRIP_HIDDEN, WhenNotDocumentHidden),
112 ConditionalPass::new(STRIP_PRIVATE, WhenNotDocumentPrivate),
113 ConditionalPass::always(CALCULATE_DOC_COVERAGE),
116 impl ConditionalPass {
117 pub const fn always(pass: Pass) -> Self {
118 Self::new(pass, Always)
121 pub const fn new(pass: Pass, condition: Condition) -> Self {
122 ConditionalPass { pass, condition }
126 /// A shorthand way to refer to which set of passes to use, based on the presence of
127 /// `--no-defaults` and `--show-coverage`.
128 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
129 pub enum DefaultPassOption {
135 /// Returns the given default set of passes.
136 pub fn defaults(default_set: DefaultPassOption) -> &'static [ConditionalPass] {
138 DefaultPassOption::Default => DEFAULT_PASSES,
139 DefaultPassOption::Coverage => COVERAGE_PASSES,
140 DefaultPassOption::None => &[],
144 /// If the given name matches a known pass, returns its information.
145 pub fn find_pass(pass_name: &str) -> Option<Pass> {
146 PASSES.iter().find(|p| p.name == pass_name).copied()
149 struct Stripper<'a> {
150 retained: &'a mut DefIdSet,
151 access_levels: &'a AccessLevels<DefId>,
152 update_retained: bool,
155 impl<'a> DocFolder for Stripper<'a> {
156 fn fold_item(&mut self, i: Item) -> Option<Item> {
158 clean::StrippedItem(..) => {
159 // We need to recurse into stripped modules to strip things
160 // like impl methods but when doing so we must not add any
161 // items to the `retained` set.
162 debug!("Stripper: recursing into stripped {:?} {:?}", i.type_(), i.name);
163 let old = mem::replace(&mut self.update_retained, false);
164 let ret = self.fold_item_recur(i);
165 self.update_retained = old;
168 // These items can all get re-exported
169 clean::OpaqueTyItem(..)
170 | clean::TypedefItem(..)
171 | clean::StaticItem(..)
172 | clean::StructItem(..)
173 | clean::EnumItem(..)
174 | clean::TraitItem(..)
175 | clean::FunctionItem(..)
176 | clean::VariantItem(..)
177 | clean::MethodItem(..)
178 | clean::ForeignFunctionItem(..)
179 | clean::ForeignStaticItem(..)
180 | clean::ConstantItem(..)
181 | clean::UnionItem(..)
182 | clean::AssocConstItem(..)
183 | clean::TraitAliasItem(..)
184 | clean::ForeignTypeItem => {
185 if i.def_id.is_local() {
186 if !self.access_levels.is_exported(i.def_id) {
187 debug!("Stripper: stripping {:?} {:?}", i.type_(), i.name);
193 clean::StructFieldItem(..) => {
194 if i.visibility != clean::Public {
195 return StripItem(i).strip();
199 clean::ModuleItem(..) => {
200 if i.def_id.is_local() && i.visibility != clean::Public {
201 debug!("Stripper: stripping module {:?}", i.name);
202 let old = mem::replace(&mut self.update_retained, false);
203 let ret = StripItem(self.fold_item_recur(i).unwrap()).strip();
204 self.update_retained = old;
209 // handled in the `strip-priv-imports` pass
210 clean::ExternCrateItem(..) | clean::ImportItem(..) => {}
212 clean::ImplItem(..) => {}
214 // tymethods/macros have no control over privacy
215 clean::MacroItem(..) | clean::TyMethodItem(..) => {}
217 // Proc-macros are always public
218 clean::ProcMacroItem(..) => {}
220 // Primitives are never stripped
221 clean::PrimitiveItem(..) => {}
223 // Associated types are never stripped
224 clean::AssocTypeItem(..) => {}
226 // Keywords are never stripped
227 clean::KeywordItem(..) => {}
230 let fastreturn = match i.inner {
231 // nothing left to do for traits (don't want to filter their
232 // methods out, visibility controlled by the trait)
233 clean::TraitItem(..) => true,
235 // implementations of traits are always public.
236 clean::ImplItem(ref imp) if imp.trait_.is_some() => true,
237 // Struct variant fields have inherited visibility
238 clean::VariantItem(clean::Variant { kind: clean::VariantKind::Struct(..) }) => true,
242 let i = if fastreturn {
243 if self.update_retained {
244 self.retained.insert(i.def_id);
248 self.fold_item_recur(i)
251 if let Some(ref i) = i {
252 if self.update_retained {
253 self.retained.insert(i.def_id);
260 // This stripper discards all impls which reference stripped items
261 struct ImplStripper<'a> {
262 retained: &'a DefIdSet,
265 impl<'a> DocFolder for ImplStripper<'a> {
266 fn fold_item(&mut self, i: Item) -> Option<Item> {
267 if let clean::ImplItem(ref imp) = i.inner {
268 // emptied none trait impls can be stripped
269 if imp.trait_.is_none() && imp.items.is_empty() {
272 if let Some(did) = imp.for_.def_id() {
273 if did.is_local() && !imp.for_.is_generic() && !self.retained.contains(&did) {
274 debug!("ImplStripper: impl item for stripped type; removing");
278 if let Some(did) = imp.trait_.def_id() {
279 if did.is_local() && !self.retained.contains(&did) {
280 debug!("ImplStripper: impl item for stripped trait; removing");
284 if let Some(generics) = imp.trait_.as_ref().and_then(|t| t.generics()) {
285 for typaram in generics {
286 if let Some(did) = typaram.def_id() {
287 if did.is_local() && !self.retained.contains(&did) {
289 "ImplStripper: stripped item in trait's generics; \
298 self.fold_item_recur(i)
302 // This stripper discards all private import statements (`use`, `extern crate`)
303 struct ImportStripper;
304 impl DocFolder for ImportStripper {
305 fn fold_item(&mut self, i: Item) -> Option<Item> {
307 clean::ExternCrateItem(..) | clean::ImportItem(..) if i.visibility != clean::Public => {
310 _ => self.fold_item_recur(i),
315 pub fn look_for_tests<'tcx>(
316 cx: &DocContext<'tcx>,
319 check_missing_code: bool,
321 let hir_id = match cx.as_local_hir_id(item.def_id) {
322 Some(hir_id) => hir_id,
324 // If non-local, no need to check anything.
333 impl crate::test::Tester for Tests {
334 fn add_test(&mut self, _: String, _: LangString, _: usize) {
335 self.found_tests += 1;
339 let mut tests = Tests { found_tests: 0 };
341 find_testable_code(&dox, &mut tests, ErrorCodes::No, false);
343 if check_missing_code && tests.found_tests == 0 {
344 let sp = span_of_attrs(&item.attrs).unwrap_or(item.source.span());
345 cx.tcx.struct_span_lint_hir(lint::builtin::MISSING_DOC_CODE_EXAMPLES, hir_id, sp, |lint| {
346 lint.build("missing code example in this documentation").emit()
348 } else if !check_missing_code
349 && tests.found_tests > 0
350 && !cx.renderinfo.borrow().access_levels.is_public(item.def_id)
352 cx.tcx.struct_span_lint_hir(
353 lint::builtin::PRIVATE_DOC_TESTS,
355 span_of_attrs(&item.attrs).unwrap_or(item.source.span()),
356 |lint| lint.build("documentation test in private item").emit(),
361 /// Returns a span encompassing all the given attributes.
362 crate fn span_of_attrs(attrs: &clean::Attributes) -> Option<Span> {
363 if attrs.doc_strings.is_empty() {
366 let start = attrs.doc_strings[0].span();
367 if start == DUMMY_SP {
370 let end = attrs.doc_strings.last().expect("no doc strings provided").span();
374 /// Attempts to match a range of bytes from parsed markdown to a `Span` in the source code.
376 /// This method will return `None` if we cannot construct a span from the source map or if the
377 /// attributes are not all sugared doc comments. It's difficult to calculate the correct span in
378 /// that case due to escaping and other source features.
379 crate fn source_span_for_markdown_range(
382 md_range: &Range<usize>,
383 attrs: &clean::Attributes,
385 let is_all_sugared_doc = attrs.doc_strings.iter().all(|frag| match frag {
386 clean::DocFragment::SugaredDoc(..) => true,
390 if !is_all_sugared_doc {
394 let snippet = cx.sess().source_map().span_to_snippet(span_of_attrs(attrs)?).ok()?;
396 let starting_line = markdown[..md_range.start].matches('\n').count();
397 let ending_line = starting_line + markdown[md_range.start..md_range.end].matches('\n').count();
399 // We use `split_terminator('\n')` instead of `lines()` when counting bytes so that we treat
400 // CRLF and LF line endings the same way.
401 let mut src_lines = snippet.split_terminator('\n');
402 let md_lines = markdown.split_terminator('\n');
404 // The number of bytes from the source span to the markdown span that are not part
405 // of the markdown, like comment markers.
406 let mut start_bytes = 0;
407 let mut end_bytes = 0;
409 'outer: for (line_no, md_line) in md_lines.enumerate() {
411 let source_line = src_lines.next().expect("could not find markdown in source");
412 match source_line.find(md_line) {
414 if line_no == starting_line {
415 start_bytes += offset;
417 if starting_line == ending_line {
420 } else if line_no == ending_line {
423 } else if line_no < starting_line {
424 start_bytes += source_line.len() - md_line.len();
426 end_bytes += source_line.len() - md_line.len();
431 // Since this is a source line that doesn't include a markdown line,
432 // we have to count the newline that we split from earlier.
433 if line_no <= starting_line {
434 start_bytes += source_line.len() + 1;
436 end_bytes += source_line.len() + 1;
443 Some(span_of_attrs(attrs)?.from_inner(InnerSpan::new(
444 md_range.start + start_bytes,
445 md_range.end + start_bytes + end_bytes,