]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes/mod.rs
Separate `missing_doc_code_examples` from intra-doc links
[rust.git] / src / librustdoc / passes / mod.rs
1 //! Contains information about "passes", used to modify crate information during the documentation
2 //! process.
3
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};
8 use std::mem;
9 use std::ops::Range;
10
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};
16
17 mod collapse_docs;
18 pub use self::collapse_docs::COLLAPSE_DOCS;
19
20 mod strip_hidden;
21 pub use self::strip_hidden::STRIP_HIDDEN;
22
23 mod strip_private;
24 pub use self::strip_private::STRIP_PRIVATE;
25
26 mod strip_priv_imports;
27 pub use self::strip_priv_imports::STRIP_PRIV_IMPORTS;
28
29 mod unindent_comments;
30 pub use self::unindent_comments::UNINDENT_COMMENTS;
31
32 mod propagate_doc_cfg;
33 pub use self::propagate_doc_cfg::PROPAGATE_DOC_CFG;
34
35 mod collect_intra_doc_links;
36 pub use self::collect_intra_doc_links::COLLECT_INTRA_DOC_LINKS;
37
38 mod private_items_doc_tests;
39 pub use self::private_items_doc_tests::CHECK_PRIVATE_ITEMS_DOC_TESTS;
40
41 mod collect_trait_impls;
42 pub use self::collect_trait_impls::COLLECT_TRAIT_IMPLS;
43
44 mod check_code_block_syntax;
45 pub use self::check_code_block_syntax::CHECK_CODE_BLOCK_SYNTAX;
46
47 mod calculate_doc_coverage;
48 pub use self::calculate_doc_coverage::CALCULATE_DOC_COVERAGE;
49
50 /// A single pass over the cleaned documentation.
51 ///
52 /// Runs in the compiler context, so it has access to types and traits and the like.
53 #[derive(Copy, Clone)]
54 pub struct Pass {
55     pub name: &'static str,
56     pub run: fn(clean::Crate, &DocContext<'_>) -> clean::Crate,
57     pub description: &'static str,
58 }
59
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 {
63     pub pass: Pass,
64     pub condition: Condition,
65 }
66
67 /// How to decide whether to run a conditional pass.
68 #[derive(Copy, Clone)]
69 pub enum Condition {
70     Always,
71     /// When `--document-private-items` is passed.
72     WhenDocumentPrivate,
73     /// When `--document-private-items` is not passed.
74     WhenNotDocumentPrivate,
75     /// When `--document-hidden-items` is not passed.
76     WhenNotDocumentHidden,
77 }
78
79 /// The full list of passes.
80 pub const PASSES: &[Pass] = &[
81     CHECK_PRIVATE_ITEMS_DOC_TESTS,
82     STRIP_HIDDEN,
83     UNINDENT_COMMENTS,
84     COLLAPSE_DOCS,
85     STRIP_PRIVATE,
86     STRIP_PRIV_IMPORTS,
87     PROPAGATE_DOC_CFG,
88     COLLECT_INTRA_DOC_LINKS,
89     CHECK_CODE_BLOCK_SYNTAX,
90     COLLECT_TRAIT_IMPLS,
91     CALCULATE_DOC_COVERAGE,
92 ];
93
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),
106 ];
107
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),
114 ];
115
116 impl ConditionalPass {
117     pub const fn always(pass: Pass) -> Self {
118         Self::new(pass, Always)
119     }
120
121     pub const fn new(pass: Pass, condition: Condition) -> Self {
122         ConditionalPass { pass, condition }
123     }
124 }
125
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 {
130     Default,
131     Coverage,
132     None,
133 }
134
135 /// Returns the given default set of passes.
136 pub fn defaults(default_set: DefaultPassOption) -> &'static [ConditionalPass] {
137     match default_set {
138         DefaultPassOption::Default => DEFAULT_PASSES,
139         DefaultPassOption::Coverage => COVERAGE_PASSES,
140         DefaultPassOption::None => &[],
141     }
142 }
143
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()
147 }
148
149 struct Stripper<'a> {
150     retained: &'a mut DefIdSet,
151     access_levels: &'a AccessLevels<DefId>,
152     update_retained: bool,
153 }
154
155 impl<'a> DocFolder for Stripper<'a> {
156     fn fold_item(&mut self, i: Item) -> Option<Item> {
157         match i.inner {
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;
166                 return ret;
167             }
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);
188                         return None;
189                     }
190                 }
191             }
192
193             clean::StructFieldItem(..) => {
194                 if i.visibility != clean::Public {
195                     return StripItem(i).strip();
196                 }
197             }
198
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;
205                     return ret;
206                 }
207             }
208
209             // handled in the `strip-priv-imports` pass
210             clean::ExternCrateItem(..) | clean::ImportItem(..) => {}
211
212             clean::ImplItem(..) => {}
213
214             // tymethods/macros have no control over privacy
215             clean::MacroItem(..) | clean::TyMethodItem(..) => {}
216
217             // Proc-macros are always public
218             clean::ProcMacroItem(..) => {}
219
220             // Primitives are never stripped
221             clean::PrimitiveItem(..) => {}
222
223             // Associated types are never stripped
224             clean::AssocTypeItem(..) => {}
225
226             // Keywords are never stripped
227             clean::KeywordItem(..) => {}
228         }
229
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,
234
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,
239             _ => false,
240         };
241
242         let i = if fastreturn {
243             if self.update_retained {
244                 self.retained.insert(i.def_id);
245             }
246             return Some(i);
247         } else {
248             self.fold_item_recur(i)
249         };
250
251         if let Some(ref i) = i {
252             if self.update_retained {
253                 self.retained.insert(i.def_id);
254             }
255         }
256         i
257     }
258 }
259
260 // This stripper discards all impls which reference stripped items
261 struct ImplStripper<'a> {
262     retained: &'a DefIdSet,
263 }
264
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() {
270                 return None;
271             }
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");
275                     return None;
276                 }
277             }
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");
281                     return None;
282                 }
283             }
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) {
288                             debug!(
289                                 "ImplStripper: stripped item in trait's generics; \
290                                     removing impl"
291                             );
292                             return None;
293                         }
294                     }
295                 }
296             }
297         }
298         self.fold_item_recur(i)
299     }
300 }
301
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> {
306         match i.inner {
307             clean::ExternCrateItem(..) | clean::ImportItem(..) if i.visibility != clean::Public => {
308                 None
309             }
310             _ => self.fold_item_recur(i),
311         }
312     }
313 }
314
315 pub fn look_for_tests<'tcx>(cx: &DocContext<'tcx>, dox: &str, item: &Item) {
316     let hir_id = match cx.as_local_hir_id(item.def_id) {
317         Some(hir_id) => hir_id,
318         None => {
319             // If non-local, no need to check anything.
320             return;
321         }
322     };
323
324     struct Tests {
325         found_tests: usize,
326     }
327
328     impl crate::test::Tester for Tests {
329         fn add_test(&mut self, _: String, _: LangString, _: usize) {
330             self.found_tests += 1;
331         }
332     }
333
334     let mut tests = Tests { found_tests: 0 };
335
336     find_testable_code(&dox, &mut tests, ErrorCodes::No, false, None);
337
338     if tests.found_tests == 0 {
339         use clean::ItemEnum::*;
340
341         let should_report = match item.inner {
342             ExternCrateItem(_, _) | ImportItem(_) | PrimitiveItem(_) | KeywordItem(_) => false,
343             _ => true,
344         };
345         if should_report {
346             debug!("reporting error for {:?} (hir_id={:?})", item, hir_id);
347             let sp = span_of_attrs(&item.attrs).unwrap_or(item.source.span());
348             cx.tcx.struct_span_lint_hir(
349                 lint::builtin::MISSING_DOC_CODE_EXAMPLES,
350                 hir_id,
351                 sp,
352                 |lint| lint.build("missing code example in this documentation").emit(),
353             );
354         }
355     } else if rustc_feature::UnstableFeatures::from_environment().is_nightly_build()
356         && tests.found_tests > 0
357         && !cx.renderinfo.borrow().access_levels.is_public(item.def_id)
358     {
359         cx.tcx.struct_span_lint_hir(
360             lint::builtin::PRIVATE_DOC_TESTS,
361             hir_id,
362             span_of_attrs(&item.attrs).unwrap_or(item.source.span()),
363             |lint| lint.build("documentation test in private item").emit(),
364         );
365     }
366 }
367
368 /// Returns a span encompassing all the given attributes.
369 crate fn span_of_attrs(attrs: &clean::Attributes) -> Option<Span> {
370     if attrs.doc_strings.is_empty() {
371         return None;
372     }
373     let start = attrs.doc_strings[0].span();
374     if start == DUMMY_SP {
375         return None;
376     }
377     let end = attrs.doc_strings.last().expect("no doc strings provided").span();
378     Some(start.to(end))
379 }
380
381 /// Attempts to match a range of bytes from parsed markdown to a `Span` in the source code.
382 ///
383 /// This method will return `None` if we cannot construct a span from the source map or if the
384 /// attributes are not all sugared doc comments. It's difficult to calculate the correct span in
385 /// that case due to escaping and other source features.
386 crate fn source_span_for_markdown_range(
387     cx: &DocContext<'_>,
388     markdown: &str,
389     md_range: &Range<usize>,
390     attrs: &clean::Attributes,
391 ) -> Option<Span> {
392     let is_all_sugared_doc = attrs.doc_strings.iter().all(|frag| match frag {
393         clean::DocFragment::SugaredDoc(..) => true,
394         _ => false,
395     });
396
397     if !is_all_sugared_doc {
398         return None;
399     }
400
401     let snippet = cx.sess().source_map().span_to_snippet(span_of_attrs(attrs)?).ok()?;
402
403     let starting_line = markdown[..md_range.start].matches('\n').count();
404     let ending_line = starting_line + markdown[md_range.start..md_range.end].matches('\n').count();
405
406     // We use `split_terminator('\n')` instead of `lines()` when counting bytes so that we treat
407     // CRLF and LF line endings the same way.
408     let mut src_lines = snippet.split_terminator('\n');
409     let md_lines = markdown.split_terminator('\n');
410
411     // The number of bytes from the source span to the markdown span that are not part
412     // of the markdown, like comment markers.
413     let mut start_bytes = 0;
414     let mut end_bytes = 0;
415
416     'outer: for (line_no, md_line) in md_lines.enumerate() {
417         loop {
418             let source_line = src_lines.next().expect("could not find markdown in source");
419             match source_line.find(md_line) {
420                 Some(offset) => {
421                     if line_no == starting_line {
422                         start_bytes += offset;
423
424                         if starting_line == ending_line {
425                             break 'outer;
426                         }
427                     } else if line_no == ending_line {
428                         end_bytes += offset;
429                         break 'outer;
430                     } else if line_no < starting_line {
431                         start_bytes += source_line.len() - md_line.len();
432                     } else {
433                         end_bytes += source_line.len() - md_line.len();
434                     }
435                     break;
436                 }
437                 None => {
438                     // Since this is a source line that doesn't include a markdown line,
439                     // we have to count the newline that we split from earlier.
440                     if line_no <= starting_line {
441                         start_bytes += source_line.len() + 1;
442                     } else {
443                         end_bytes += source_line.len() + 1;
444                     }
445                 }
446             }
447         }
448     }
449
450     Some(span_of_attrs(attrs)?.from_inner(InnerSpan::new(
451         md_range.start + start_bytes,
452         md_range.end + start_bytes + end_bytes,
453     )))
454 }