]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes/mod.rs
Improve type size assertions
[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;
5 use rustc::hir::def_id::DefId;
6 use rustc::lint as lint;
7 use rustc::middle::privacy::AccessLevels;
8 use rustc::util::nodemap::DefIdSet;
9 use std::mem;
10 use syntax_pos::{DUMMY_SP, Span};
11 use std::ops::Range;
12
13 use crate::clean::{self, GetDefId, Item};
14 use crate::core::{DocContext, DocAccessLevels};
15 use crate::fold::{DocFolder, StripItem};
16 use crate::html::markdown::{find_testable_code, ErrorCodes, LangString};
17
18 mod collapse_docs;
19 pub use self::collapse_docs::COLLAPSE_DOCS;
20
21 mod strip_hidden;
22 pub use self::strip_hidden::STRIP_HIDDEN;
23
24 mod strip_private;
25 pub use self::strip_private::STRIP_PRIVATE;
26
27 mod strip_priv_imports;
28 pub use self::strip_priv_imports::STRIP_PRIV_IMPORTS;
29
30 mod unindent_comments;
31 pub use self::unindent_comments::UNINDENT_COMMENTS;
32
33 mod propagate_doc_cfg;
34 pub use self::propagate_doc_cfg::PROPAGATE_DOC_CFG;
35
36 mod collect_intra_doc_links;
37 pub use self::collect_intra_doc_links::COLLECT_INTRA_DOC_LINKS;
38
39 mod private_items_doc_tests;
40 pub use self::private_items_doc_tests::CHECK_PRIVATE_ITEMS_DOC_TESTS;
41
42 mod collect_trait_impls;
43 pub use self::collect_trait_impls::COLLECT_TRAIT_IMPLS;
44
45 mod check_code_block_syntax;
46 pub use self::check_code_block_syntax::CHECK_CODE_BLOCK_SYNTAX;
47
48 mod calculate_doc_coverage;
49 pub use self::calculate_doc_coverage::CALCULATE_DOC_COVERAGE;
50
51 /// A single pass over the cleaned documentation.
52 ///
53 /// Runs in the compiler context, so it has access to types and traits and the like.
54 #[derive(Copy, Clone)]
55 pub struct Pass {
56     pub name: &'static str,
57     pub pass: fn(clean::Crate, &DocContext<'_>) -> clean::Crate,
58     pub description: &'static str,
59 }
60
61 /// The full list of passes.
62 pub const PASSES: &'static [Pass] = &[
63     CHECK_PRIVATE_ITEMS_DOC_TESTS,
64     STRIP_HIDDEN,
65     UNINDENT_COMMENTS,
66     COLLAPSE_DOCS,
67     STRIP_PRIVATE,
68     STRIP_PRIV_IMPORTS,
69     PROPAGATE_DOC_CFG,
70     COLLECT_INTRA_DOC_LINKS,
71     CHECK_CODE_BLOCK_SYNTAX,
72     COLLECT_TRAIT_IMPLS,
73     CALCULATE_DOC_COVERAGE,
74 ];
75
76 /// The list of passes run by default.
77 pub const DEFAULT_PASSES: &[&str] = &[
78     "collect-trait-impls",
79     "collapse-docs",
80     "unindent-comments",
81     "check-private-items-doc-tests",
82     "strip-hidden",
83     "strip-private",
84     "collect-intra-doc-links",
85     "check-code-block-syntax",
86     "propagate-doc-cfg",
87 ];
88
89 /// The list of default passes run with `--document-private-items` is passed to rustdoc.
90 pub const DEFAULT_PRIVATE_PASSES: &[&str] = &[
91     "collect-trait-impls",
92     "collapse-docs",
93     "unindent-comments",
94     "check-private-items-doc-tests",
95     "strip-priv-imports",
96     "collect-intra-doc-links",
97     "check-code-block-syntax",
98     "propagate-doc-cfg",
99 ];
100
101 /// The list of default passes run when `--doc-coverage` is passed to rustdoc.
102 pub const DEFAULT_COVERAGE_PASSES: &'static [&'static str] = &[
103     "collect-trait-impls",
104     "strip-hidden",
105     "strip-private",
106     "calculate-doc-coverage",
107 ];
108
109 /// The list of default passes run when `--doc-coverage --document-private-items` is passed to
110 /// rustdoc.
111 pub const PRIVATE_COVERAGE_PASSES: &'static [&'static str] = &[
112     "collect-trait-impls",
113     "calculate-doc-coverage",
114 ];
115
116 /// A shorthand way to refer to which set of passes to use, based on the presence of
117 /// `--no-defaults` or `--document-private-items`.
118 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
119 pub enum DefaultPassOption {
120     Default,
121     Private,
122     Coverage,
123     PrivateCoverage,
124     None,
125 }
126
127 /// Returns the given default set of passes.
128 pub fn defaults(default_set: DefaultPassOption) -> &'static [&'static str] {
129     match default_set {
130         DefaultPassOption::Default => DEFAULT_PASSES,
131         DefaultPassOption::Private => DEFAULT_PRIVATE_PASSES,
132         DefaultPassOption::Coverage => DEFAULT_COVERAGE_PASSES,
133         DefaultPassOption::PrivateCoverage => PRIVATE_COVERAGE_PASSES,
134         DefaultPassOption::None => &[],
135     }
136 }
137
138 /// If the given name matches a known pass, returns its information.
139 pub fn find_pass(pass_name: &str) -> Option<&'static Pass> {
140     PASSES.iter().find(|p| p.name == pass_name)
141 }
142
143 struct Stripper<'a> {
144     retained: &'a mut DefIdSet,
145     access_levels: &'a AccessLevels<DefId>,
146     update_retained: bool,
147 }
148
149 impl<'a> DocFolder for Stripper<'a> {
150     fn fold_item(&mut self, i: Item) -> Option<Item> {
151         match i.inner {
152             clean::StrippedItem(..) => {
153                 // We need to recurse into stripped modules to strip things
154                 // like impl methods but when doing so we must not add any
155                 // items to the `retained` set.
156                 debug!("Stripper: recursing into stripped {} {:?}", i.type_(), i.name);
157                 let old = mem::replace(&mut self.update_retained, false);
158                 let ret = self.fold_item_recur(i);
159                 self.update_retained = old;
160                 return ret;
161             }
162             // These items can all get re-exported
163             clean::ExistentialItem(..)
164             | clean::TypedefItem(..)
165             | clean::StaticItem(..)
166             | clean::StructItem(..)
167             | clean::EnumItem(..)
168             | clean::TraitItem(..)
169             | clean::FunctionItem(..)
170             | clean::VariantItem(..)
171             | clean::MethodItem(..)
172             | clean::ForeignFunctionItem(..)
173             | clean::ForeignStaticItem(..)
174             | clean::ConstantItem(..)
175             | clean::UnionItem(..)
176             | clean::AssociatedConstItem(..)
177             | clean::TraitAliasItem(..)
178             | clean::ForeignTypeItem => {
179                 if i.def_id.is_local() {
180                     if !self.access_levels.is_exported(i.def_id) {
181                         debug!("Stripper: stripping {} {:?}", i.type_(), i.name);
182                         return None;
183                     }
184                 }
185             }
186
187             clean::StructFieldItem(..) => {
188                 if i.visibility != Some(clean::Public) {
189                     return StripItem(i).strip();
190                 }
191             }
192
193             clean::ModuleItem(..) => {
194                 if i.def_id.is_local() && i.visibility != Some(clean::Public) {
195                     debug!("Stripper: stripping module {:?}", i.name);
196                     let old = mem::replace(&mut self.update_retained, false);
197                     let ret = StripItem(self.fold_item_recur(i).unwrap()).strip();
198                     self.update_retained = old;
199                     return ret;
200                 }
201             }
202
203             // handled in the `strip-priv-imports` pass
204             clean::ExternCrateItem(..) | clean::ImportItem(..) => {}
205
206             clean::ImplItem(..) => {}
207
208             // tymethods/macros have no control over privacy
209             clean::MacroItem(..) | clean::TyMethodItem(..) => {}
210
211             // Proc-macros are always public
212             clean::ProcMacroItem(..) => {}
213
214             // Primitives are never stripped
215             clean::PrimitiveItem(..) => {}
216
217             // Associated types are never stripped
218             clean::AssociatedTypeItem(..) => {}
219
220             // Keywords are never stripped
221             clean::KeywordItem(..) => {}
222         }
223
224         let fastreturn = match i.inner {
225             // nothing left to do for traits (don't want to filter their
226             // methods out, visibility controlled by the trait)
227             clean::TraitItem(..) => true,
228
229             // implementations of traits are always public.
230             clean::ImplItem(ref imp) if imp.trait_.is_some() => true,
231             // Struct variant fields have inherited visibility
232             clean::VariantItem(clean::Variant {
233                 kind: clean::VariantKind::Struct(..),
234             }) => true,
235             _ => false,
236         };
237
238         let i = if fastreturn {
239             if self.update_retained {
240                 self.retained.insert(i.def_id);
241             }
242             return Some(i);
243         } else {
244             self.fold_item_recur(i)
245         };
246
247         if let Some(ref i) = i {
248             if self.update_retained {
249                 self.retained.insert(i.def_id);
250             }
251         }
252         i
253     }
254 }
255
256 // This stripper discards all impls which reference stripped items
257 struct ImplStripper<'a> {
258     retained: &'a DefIdSet,
259 }
260
261 impl<'a> DocFolder for ImplStripper<'a> {
262     fn fold_item(&mut self, i: Item) -> Option<Item> {
263         if let clean::ImplItem(ref imp) = i.inner {
264             // emptied none trait impls can be stripped
265             if imp.trait_.is_none() && imp.items.is_empty() {
266                 return None;
267             }
268             if let Some(did) = imp.for_.def_id() {
269                 if did.is_local() && !imp.for_.is_generic() && !self.retained.contains(&did) {
270                     debug!("ImplStripper: impl item for stripped type; removing");
271                     return None;
272                 }
273             }
274             if let Some(did) = imp.trait_.def_id() {
275                 if did.is_local() && !self.retained.contains(&did) {
276                     debug!("ImplStripper: impl item for stripped trait; removing");
277                     return None;
278                 }
279             }
280             if let Some(generics) = imp.trait_.as_ref().and_then(|t| t.generics()) {
281                 for typaram in generics {
282                     if let Some(did) = typaram.def_id() {
283                         if did.is_local() && !self.retained.contains(&did) {
284                             debug!("ImplStripper: stripped item in trait's generics; \
285                                     removing impl");
286                             return None;
287                         }
288                     }
289                 }
290             }
291         }
292         self.fold_item_recur(i)
293     }
294 }
295
296 // This stripper discards all private import statements (`use`, `extern crate`)
297 struct ImportStripper;
298 impl DocFolder for ImportStripper {
299     fn fold_item(&mut self, i: Item) -> Option<Item> {
300         match i.inner {
301             clean::ExternCrateItem(..) | clean::ImportItem(..)
302                 if i.visibility != Some(clean::Public) =>
303             {
304                 None
305             }
306             _ => self.fold_item_recur(i),
307         }
308     }
309 }
310
311 pub fn look_for_tests<'tcx>(
312     cx: &DocContext<'tcx>,
313     dox: &str,
314     item: &Item,
315     check_missing_code: bool,
316 ) {
317     if cx.as_local_hir_id(item.def_id).is_none() {
318         // If non-local, no need to check anything.
319         return;
320     }
321
322     struct Tests {
323         found_tests: usize,
324     }
325
326     impl crate::test::Tester for Tests {
327         fn add_test(&mut self, _: String, _: LangString, _: usize) {
328             self.found_tests += 1;
329         }
330     }
331
332     let mut tests = Tests {
333         found_tests: 0,
334     };
335
336     find_testable_code(&dox, &mut tests, ErrorCodes::No);
337
338     if check_missing_code == true && tests.found_tests == 0 {
339         let mut diag = cx.tcx.struct_span_lint_hir(
340             lint::builtin::MISSING_DOC_CODE_EXAMPLES,
341             hir::CRATE_HIR_ID,
342             span_of_attrs(&item.attrs),
343             "Missing code example in this documentation");
344         diag.emit();
345     } else if check_missing_code == false &&
346               tests.found_tests > 0 &&
347               !cx.renderinfo.borrow().access_levels.is_doc_reachable(item.def_id) {
348         let mut diag = cx.tcx.struct_span_lint_hir(
349             lint::builtin::PRIVATE_DOC_TESTS,
350             hir::CRATE_HIR_ID,
351             span_of_attrs(&item.attrs),
352             "Documentation test in private item");
353         diag.emit();
354     }
355 }
356
357 /// Returns a span encompassing all the given attributes.
358 crate fn span_of_attrs(attrs: &clean::Attributes) -> Span {
359     if attrs.doc_strings.is_empty() {
360         return DUMMY_SP;
361     }
362     let start = attrs.doc_strings[0].span();
363     let end = attrs.doc_strings.last().expect("No doc strings provided").span();
364     start.to(end)
365 }
366
367 /// Attempts to match a range of bytes from parsed markdown to a `Span` in the source code.
368 ///
369 /// This method will return `None` if we cannot construct a span from the source map or if the
370 /// attributes are not all sugared doc comments. It's difficult to calculate the correct span in
371 /// that case due to escaping and other source features.
372 crate fn source_span_for_markdown_range(
373     cx: &DocContext<'_>,
374     markdown: &str,
375     md_range: &Range<usize>,
376     attrs: &clean::Attributes,
377 ) -> Option<Span> {
378     let is_all_sugared_doc = attrs.doc_strings.iter().all(|frag| match frag {
379         clean::DocFragment::SugaredDoc(..) => true,
380         _ => false,
381     });
382
383     if !is_all_sugared_doc {
384         return None;
385     }
386
387     let snippet = cx
388         .sess()
389         .source_map()
390         .span_to_snippet(span_of_attrs(attrs))
391         .ok()?;
392
393     let starting_line = markdown[..md_range.start].matches('\n').count();
394     let ending_line = starting_line + markdown[md_range.start..md_range.end].matches('\n').count();
395
396     // We use `split_terminator('\n')` instead of `lines()` when counting bytes so that we treat
397     // CRLF and LF line endings the same way.
398     let mut src_lines = snippet.split_terminator('\n');
399     let md_lines = markdown.split_terminator('\n');
400
401     // The number of bytes from the source span to the markdown span that are not part
402     // of the markdown, like comment markers.
403     let mut start_bytes = 0;
404     let mut end_bytes = 0;
405
406     'outer: for (line_no, md_line) in md_lines.enumerate() {
407         loop {
408             let source_line = src_lines.next().expect("could not find markdown in source");
409             match source_line.find(md_line) {
410                 Some(offset) => {
411                     if line_no == starting_line {
412                         start_bytes += offset;
413
414                         if starting_line == ending_line {
415                             break 'outer;
416                         }
417                     } else if line_no == ending_line {
418                         end_bytes += offset;
419                         break 'outer;
420                     } else if line_no < starting_line {
421                         start_bytes += source_line.len() - md_line.len();
422                     } else {
423                         end_bytes += source_line.len() - md_line.len();
424                     }
425                     break;
426                 }
427                 None => {
428                     // Since this is a source line that doesn't include a markdown line,
429                     // we have to count the newline that we split from earlier.
430                     if line_no <= starting_line {
431                         start_bytes += source_line.len() + 1;
432                     } else {
433                         end_bytes += source_line.len() + 1;
434                     }
435                 }
436             }
437         }
438     }
439
440     let sp = span_of_attrs(attrs).from_inner_byte_pos(
441         md_range.start + start_bytes,
442         md_range.end + start_bytes + end_bytes,
443     );
444
445     Some(sp)
446 }