]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes/mod.rs
Rollup merge of #69599 - Centril:typeck-tweak-wording, r=davidtwco
[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::lint;
5 use rustc::middle::privacy::AccessLevels;
6 use rustc_hir::def_id::{DefId, DefIdSet};
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>(
316     cx: &DocContext<'tcx>,
317     dox: &str,
318     item: &Item,
319     check_missing_code: bool,
320 ) {
321     let hir_id = match cx.as_local_hir_id(item.def_id) {
322         Some(hir_id) => hir_id,
323         None => {
324             // If non-local, no need to check anything.
325             return;
326         }
327     };
328
329     struct Tests {
330         found_tests: usize,
331     }
332
333     impl crate::test::Tester for Tests {
334         fn add_test(&mut self, _: String, _: LangString, _: usize) {
335             self.found_tests += 1;
336         }
337     }
338
339     let mut tests = Tests { found_tests: 0 };
340
341     find_testable_code(&dox, &mut tests, ErrorCodes::No, false);
342
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()
347         });
348     } else if !check_missing_code
349         && tests.found_tests > 0
350         && !cx.renderinfo.borrow().access_levels.is_public(item.def_id)
351     {
352         cx.tcx.struct_span_lint_hir(
353             lint::builtin::PRIVATE_DOC_TESTS,
354             hir_id,
355             span_of_attrs(&item.attrs).unwrap_or(item.source.span()),
356             |lint| lint.build("documentation test in private item").emit(),
357         );
358     }
359 }
360
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() {
364         return None;
365     }
366     let start = attrs.doc_strings[0].span();
367     if start == DUMMY_SP {
368         return None;
369     }
370     let end = attrs.doc_strings.last().expect("no doc strings provided").span();
371     Some(start.to(end))
372 }
373
374 /// Attempts to match a range of bytes from parsed markdown to a `Span` in the source code.
375 ///
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(
380     cx: &DocContext<'_>,
381     markdown: &str,
382     md_range: &Range<usize>,
383     attrs: &clean::Attributes,
384 ) -> Option<Span> {
385     let is_all_sugared_doc = attrs.doc_strings.iter().all(|frag| match frag {
386         clean::DocFragment::SugaredDoc(..) => true,
387         _ => false,
388     });
389
390     if !is_all_sugared_doc {
391         return None;
392     }
393
394     let snippet = cx.sess().source_map().span_to_snippet(span_of_attrs(attrs)?).ok()?;
395
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();
398
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');
403
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;
408
409     'outer: for (line_no, md_line) in md_lines.enumerate() {
410         loop {
411             let source_line = src_lines.next().expect("could not find markdown in source");
412             match source_line.find(md_line) {
413                 Some(offset) => {
414                     if line_no == starting_line {
415                         start_bytes += offset;
416
417                         if starting_line == ending_line {
418                             break 'outer;
419                         }
420                     } else if line_no == ending_line {
421                         end_bytes += offset;
422                         break 'outer;
423                     } else if line_no < starting_line {
424                         start_bytes += source_line.len() - md_line.len();
425                     } else {
426                         end_bytes += source_line.len() - md_line.len();
427                     }
428                     break;
429                 }
430                 None => {
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;
435                     } else {
436                         end_bytes += source_line.len() + 1;
437                     }
438                 }
439             }
440         }
441     }
442
443     Some(span_of_attrs(attrs)?.from_inner(InnerSpan::new(
444         md_range.start + start_bytes,
445         md_range.end + start_bytes + end_bytes,
446     )))
447 }