1 //! Contains information about "passes", used to modify crate information during the documentation
4 use rustc::hir::def_id::DefId;
5 use rustc::lint as lint;
6 use rustc::middle::privacy::AccessLevels;
7 use rustc::util::nodemap::DefIdSet;
9 use syntax_pos::{DUMMY_SP, InnerSpan, Span};
12 use crate::clean::{self, GetDefId, Item};
13 use crate::core::{DocContext, DocAccessLevels};
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 pass: fn(clean::Crate, &DocContext<'_>) -> clean::Crate,
57 pub description: &'static str,
60 /// The full list of passes.
61 pub const PASSES: &'static [Pass] = &[
62 CHECK_PRIVATE_ITEMS_DOC_TESTS,
69 COLLECT_INTRA_DOC_LINKS,
70 CHECK_CODE_BLOCK_SYNTAX,
72 CALCULATE_DOC_COVERAGE,
75 /// The list of passes run by default.
76 pub const DEFAULT_PASSES: &[&str] = &[
77 "collect-trait-impls",
80 "check-private-items-doc-tests",
83 "collect-intra-doc-links",
84 "check-code-block-syntax",
88 /// The list of default passes run with `--document-private-items` is passed to rustdoc.
89 pub const DEFAULT_PRIVATE_PASSES: &[&str] = &[
90 "collect-trait-impls",
93 "check-private-items-doc-tests",
95 "collect-intra-doc-links",
96 "check-code-block-syntax",
100 /// The list of default passes run when `--doc-coverage` is passed to rustdoc.
101 pub const DEFAULT_COVERAGE_PASSES: &'static [&'static str] = &[
102 "collect-trait-impls",
105 "calculate-doc-coverage",
108 /// The list of default passes run when `--doc-coverage --document-private-items` is passed to
110 pub const PRIVATE_COVERAGE_PASSES: &'static [&'static str] = &[
111 "collect-trait-impls",
112 "calculate-doc-coverage",
115 /// A shorthand way to refer to which set of passes to use, based on the presence of
116 /// `--no-defaults` or `--document-private-items`.
117 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
118 pub enum DefaultPassOption {
126 /// Returns the given default set of passes.
127 pub fn defaults(default_set: DefaultPassOption) -> &'static [&'static str] {
129 DefaultPassOption::Default => DEFAULT_PASSES,
130 DefaultPassOption::Private => DEFAULT_PRIVATE_PASSES,
131 DefaultPassOption::Coverage => DEFAULT_COVERAGE_PASSES,
132 DefaultPassOption::PrivateCoverage => PRIVATE_COVERAGE_PASSES,
133 DefaultPassOption::None => &[],
137 /// If the given name matches a known pass, returns its information.
138 pub fn find_pass(pass_name: &str) -> Option<&'static Pass> {
139 PASSES.iter().find(|p| p.name == pass_name)
142 struct Stripper<'a> {
143 retained: &'a mut DefIdSet,
144 access_levels: &'a AccessLevels<DefId>,
145 update_retained: bool,
148 impl<'a> DocFolder for Stripper<'a> {
149 fn fold_item(&mut self, i: Item) -> Option<Item> {
151 clean::StrippedItem(..) => {
152 // We need to recurse into stripped modules to strip things
153 // like impl methods but when doing so we must not add any
154 // items to the `retained` set.
155 debug!("Stripper: recursing into stripped {} {:?}", i.type_(), i.name);
156 let old = mem::replace(&mut self.update_retained, false);
157 let ret = self.fold_item_recur(i);
158 self.update_retained = old;
161 // These items can all get re-exported
162 clean::ExistentialItem(..)
163 | clean::TypedefItem(..)
164 | clean::StaticItem(..)
165 | clean::StructItem(..)
166 | clean::EnumItem(..)
167 | clean::TraitItem(..)
168 | clean::FunctionItem(..)
169 | clean::VariantItem(..)
170 | clean::MethodItem(..)
171 | clean::ForeignFunctionItem(..)
172 | clean::ForeignStaticItem(..)
173 | clean::ConstantItem(..)
174 | clean::UnionItem(..)
175 | clean::AssocConstItem(..)
176 | clean::TraitAliasItem(..)
177 | clean::ForeignTypeItem => {
178 if i.def_id.is_local() {
179 if !self.access_levels.is_exported(i.def_id) {
180 debug!("Stripper: stripping {} {:?}", i.type_(), i.name);
186 clean::StructFieldItem(..) => {
187 if i.visibility != Some(clean::Public) {
188 return StripItem(i).strip();
192 clean::ModuleItem(..) => {
193 if i.def_id.is_local() && i.visibility != Some(clean::Public) {
194 debug!("Stripper: stripping module {:?}", i.name);
195 let old = mem::replace(&mut self.update_retained, false);
196 let ret = StripItem(self.fold_item_recur(i).unwrap()).strip();
197 self.update_retained = old;
202 // handled in the `strip-priv-imports` pass
203 clean::ExternCrateItem(..) | clean::ImportItem(..) => {}
205 clean::ImplItem(..) => {}
207 // tymethods/macros have no control over privacy
208 clean::MacroItem(..) | clean::TyMethodItem(..) => {}
210 // Proc-macros are always public
211 clean::ProcMacroItem(..) => {}
213 // Primitives are never stripped
214 clean::PrimitiveItem(..) => {}
216 // Associated types are never stripped
217 clean::AssocTypeItem(..) => {}
219 // Keywords are never stripped
220 clean::KeywordItem(..) => {}
223 let fastreturn = match i.inner {
224 // nothing left to do for traits (don't want to filter their
225 // methods out, visibility controlled by the trait)
226 clean::TraitItem(..) => true,
228 // implementations of traits are always public.
229 clean::ImplItem(ref imp) if imp.trait_.is_some() => true,
230 // Struct variant fields have inherited visibility
231 clean::VariantItem(clean::Variant {
232 kind: clean::VariantKind::Struct(..),
237 let i = if fastreturn {
238 if self.update_retained {
239 self.retained.insert(i.def_id);
243 self.fold_item_recur(i)
246 if let Some(ref i) = i {
247 if self.update_retained {
248 self.retained.insert(i.def_id);
255 // This stripper discards all impls which reference stripped items
256 struct ImplStripper<'a> {
257 retained: &'a DefIdSet,
260 impl<'a> DocFolder for ImplStripper<'a> {
261 fn fold_item(&mut self, i: Item) -> Option<Item> {
262 if let clean::ImplItem(ref imp) = i.inner {
263 // emptied none trait impls can be stripped
264 if imp.trait_.is_none() && imp.items.is_empty() {
267 if let Some(did) = imp.for_.def_id() {
268 if did.is_local() && !imp.for_.is_generic() && !self.retained.contains(&did) {
269 debug!("ImplStripper: impl item for stripped type; removing");
273 if let Some(did) = imp.trait_.def_id() {
274 if did.is_local() && !self.retained.contains(&did) {
275 debug!("ImplStripper: impl item for stripped trait; removing");
279 if let Some(generics) = imp.trait_.as_ref().and_then(|t| t.generics()) {
280 for typaram in generics {
281 if let Some(did) = typaram.def_id() {
282 if did.is_local() && !self.retained.contains(&did) {
283 debug!("ImplStripper: stripped item in trait's generics; \
291 self.fold_item_recur(i)
295 // This stripper discards all private import statements (`use`, `extern crate`)
296 struct ImportStripper;
297 impl DocFolder for ImportStripper {
298 fn fold_item(&mut self, i: Item) -> Option<Item> {
300 clean::ExternCrateItem(..) | clean::ImportItem(..)
301 if i.visibility != Some(clean::Public) =>
305 _ => self.fold_item_recur(i),
310 pub fn look_for_tests<'tcx>(
311 cx: &DocContext<'tcx>,
314 check_missing_code: bool,
316 let hir_id = match cx.as_local_hir_id(item.def_id) {
317 Some(hir_id) => hir_id,
319 // If non-local, no need to check anything.
328 impl crate::test::Tester for Tests {
329 fn add_test(&mut self, _: String, _: LangString, _: usize) {
330 self.found_tests += 1;
334 let mut tests = Tests {
338 find_testable_code(&dox, &mut tests, ErrorCodes::No);
340 if check_missing_code == true && tests.found_tests == 0 {
341 let sp = span_of_attrs(&item.attrs).substitute_dummy(item.source.span());
342 let mut diag = cx.tcx.struct_span_lint_hir(
343 lint::builtin::MISSING_DOC_CODE_EXAMPLES,
346 "Missing code example in this documentation");
348 } else if check_missing_code == false &&
349 tests.found_tests > 0 &&
350 !cx.renderinfo.borrow().access_levels.is_doc_reachable(item.def_id) {
351 let mut diag = cx.tcx.struct_span_lint_hir(
352 lint::builtin::PRIVATE_DOC_TESTS,
354 span_of_attrs(&item.attrs),
355 "Documentation test in private item");
360 /// Returns a span encompassing all the given attributes.
361 crate fn span_of_attrs(attrs: &clean::Attributes) -> Span {
362 if attrs.doc_strings.is_empty() {
365 let start = attrs.doc_strings[0].span();
366 let end = attrs.doc_strings.last().expect("No doc strings provided").span();
370 /// Attempts to match a range of bytes from parsed markdown to a `Span` in the source code.
372 /// This method will return `None` if we cannot construct a span from the source map or if the
373 /// attributes are not all sugared doc comments. It's difficult to calculate the correct span in
374 /// that case due to escaping and other source features.
375 crate fn source_span_for_markdown_range(
378 md_range: &Range<usize>,
379 attrs: &clean::Attributes,
381 let is_all_sugared_doc = attrs.doc_strings.iter().all(|frag| match frag {
382 clean::DocFragment::SugaredDoc(..) => true,
386 if !is_all_sugared_doc {
393 .span_to_snippet(span_of_attrs(attrs))
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 let sp = span_of_attrs(attrs).from_inner(InnerSpan::new(
444 md_range.start + start_bytes,
445 md_range.end + start_bytes + end_bytes,