]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes.rs
60b2a82f007ef9367cf00cd72e732c3fd0ed94ab
[rust.git] / src / librustdoc / passes.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use collections::HashSet;
12 use rustc::util::nodemap::NodeSet;
13 use std::cmp;
14 use std::string::String;
15 use std::uint;
16 use syntax::ast;
17 use syntax::ast_util;
18
19 use clean;
20 use clean::Item;
21 use plugins;
22 use fold;
23 use fold::DocFolder;
24
25 /// Strip items marked `#[doc(hidden)]`
26 pub fn strip_hidden(krate: clean::Crate) -> plugins::PluginResult {
27     let mut stripped = HashSet::new();
28
29     // strip all #[doc(hidden)] items
30     let krate = {
31         struct Stripper<'a> {
32             stripped: &'a mut HashSet<ast::NodeId>
33         };
34         impl<'a> fold::DocFolder for Stripper<'a> {
35             fn fold_item(&mut self, i: Item) -> Option<Item> {
36                 if i.is_hidden_from_doc() {
37                     debug!("found one in strip_hidden; removing");
38                     self.stripped.insert(i.def_id.node);
39
40                     // use a dedicated hidden item for given item type if any
41                     match i.inner {
42                         clean::StructFieldItem(..) => {
43                             return Some(clean::Item {
44                                 inner: clean::StructFieldItem(clean::HiddenStructField),
45                                 ..i
46                             });
47                         }
48                         _ => {
49                             return None;
50                         }
51                     }
52                 }
53
54                 self.fold_item_recur(i)
55             }
56         }
57         let mut stripper = Stripper{ stripped: &mut stripped };
58         stripper.fold_crate(krate)
59     };
60
61     // strip any traits implemented on stripped items
62     let krate = {
63         struct ImplStripper<'a> {
64             stripped: &'a mut HashSet<ast::NodeId>
65         };
66         impl<'a> fold::DocFolder for ImplStripper<'a> {
67             fn fold_item(&mut self, i: Item) -> Option<Item> {
68                 match i.inner {
69                     clean::ImplItem(clean::Impl{
70                         for_: clean::ResolvedPath{ did, .. },
71                         ref trait_, ..
72                     }) => {
73                         // Impls for stripped don't need to exist
74                         if self.stripped.contains(&did.node) {
75                             return None;
76                         }
77                         // Impls of stripped traits also don't need to exist
78                         match *trait_ {
79                             Some(clean::ResolvedPath { did, .. }) => {
80                                 if self.stripped.contains(&did.node) {
81                                     return None
82                                 }
83                             }
84                             _ => {}
85                         }
86                     }
87                     _ => {}
88                 }
89                 self.fold_item_recur(i)
90             }
91         }
92         let mut stripper = ImplStripper{ stripped: &mut stripped };
93         stripper.fold_crate(krate)
94     };
95
96     (krate, None)
97 }
98
99 /// Strip private items from the point of view of a crate or externally from a
100 /// crate, specified by the `xcrate` flag.
101 pub fn strip_private(mut krate: clean::Crate) -> plugins::PluginResult {
102     // This stripper collects all *retained* nodes.
103     let mut retained = HashSet::new();
104     let analysis = super::analysiskey.get().unwrap();
105     let exported_items = analysis.exported_items.clone();
106
107     // strip all private items
108     {
109         let mut stripper = Stripper {
110             retained: &mut retained,
111             exported_items: &exported_items,
112         };
113         krate = stripper.fold_crate(krate);
114     }
115
116     // strip all private implementations of traits
117     {
118         let mut stripper = ImplStripper(&retained);
119         krate = stripper.fold_crate(krate);
120     }
121     (krate, None)
122 }
123
124 struct Stripper<'a> {
125     retained: &'a mut HashSet<ast::NodeId>,
126     exported_items: &'a NodeSet,
127 }
128
129 impl<'a> fold::DocFolder for Stripper<'a> {
130     fn fold_item(&mut self, i: Item) -> Option<Item> {
131         match i.inner {
132             // These items can all get re-exported
133             clean::TypedefItem(..) | clean::StaticItem(..) |
134             clean::StructItem(..) | clean::EnumItem(..) |
135             clean::TraitItem(..) | clean::FunctionItem(..) |
136             clean::VariantItem(..) | clean::MethodItem(..) |
137             clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) => {
138                 if ast_util::is_local(i.def_id) &&
139                    !self.exported_items.contains(&i.def_id.node) {
140                     return None;
141                 }
142             }
143
144             clean::ViewItemItem(..) => {
145                 if i.visibility != Some(ast::Public) {
146                     return None
147                 }
148             }
149
150             clean::StructFieldItem(..) => {
151                 if i.visibility != Some(ast::Public) {
152                     return Some(clean::Item {
153                         inner: clean::StructFieldItem(clean::HiddenStructField),
154                         ..i
155                     })
156                 }
157             }
158
159             // handled below
160             clean::ModuleItem(..) => {}
161
162             // trait impls for private items should be stripped
163             clean::ImplItem(clean::Impl{
164                 for_: clean::ResolvedPath{ did, .. }, ..
165             }) => {
166                 if ast_util::is_local(did) &&
167                    !self.exported_items.contains(&did.node) {
168                     return None;
169                 }
170             }
171             clean::ImplItem(..) => {}
172
173             // tymethods/macros have no control over privacy
174             clean::MacroItem(..) | clean::TyMethodItem(..) => {}
175
176             // Primitives are never stripped
177             clean::PrimitiveItem(..) => {}
178         }
179
180         let fastreturn = match i.inner {
181             // nothing left to do for traits (don't want to filter their
182             // methods out, visibility controlled by the trait)
183             clean::TraitItem(..) => true,
184
185             // implementations of traits are always public.
186             clean::ImplItem(ref imp) if imp.trait_.is_some() => true,
187
188             _ => false,
189         };
190
191         let i = if fastreturn {
192             self.retained.insert(i.def_id.node);
193             return Some(i);
194         } else {
195             self.fold_item_recur(i)
196         };
197
198         match i {
199             Some(i) => {
200                 match i.inner {
201                     // emptied modules/impls have no need to exist
202                     clean::ModuleItem(ref m)
203                         if m.items.len() == 0 &&
204                            i.doc_value().is_none() => None,
205                     clean::ImplItem(ref i) if i.methods.len() == 0 => None,
206                     _ => {
207                         self.retained.insert(i.def_id.node);
208                         Some(i)
209                     }
210                 }
211             }
212             None => None,
213         }
214     }
215 }
216
217 // This stripper discards all private impls of traits
218 struct ImplStripper<'a>(&'a HashSet<ast::NodeId>);
219 impl<'a> fold::DocFolder for ImplStripper<'a> {
220     fn fold_item(&mut self, i: Item) -> Option<Item> {
221         match i.inner {
222             clean::ImplItem(ref imp) => {
223                 match imp.trait_ {
224                     Some(clean::ResolvedPath{ did, .. }) => {
225                         let ImplStripper(s) = *self;
226                         if ast_util::is_local(did) && !s.contains(&did.node) {
227                             return None;
228                         }
229                     }
230                     Some(..) | None => {}
231                 }
232             }
233             _ => {}
234         }
235         self.fold_item_recur(i)
236     }
237 }
238
239
240 pub fn unindent_comments(krate: clean::Crate) -> plugins::PluginResult {
241     struct CommentCleaner;
242     impl fold::DocFolder for CommentCleaner {
243         fn fold_item(&mut self, i: Item) -> Option<Item> {
244             let mut i = i;
245             let mut avec: Vec<clean::Attribute> = Vec::new();
246             for attr in i.attrs.iter() {
247                 match attr {
248                     &clean::NameValue(ref x, ref s)
249                             if "doc" == x.as_slice() => {
250                         avec.push(clean::NameValue("doc".to_string(),
251                                                    unindent(s.as_slice())))
252                     }
253                     x => avec.push(x.clone())
254                 }
255             }
256             i.attrs = avec;
257             self.fold_item_recur(i)
258         }
259     }
260     let mut cleaner = CommentCleaner;
261     let krate = cleaner.fold_crate(krate);
262     (krate, None)
263 }
264
265 pub fn collapse_docs(krate: clean::Crate) -> plugins::PluginResult {
266     struct Collapser;
267     impl fold::DocFolder for Collapser {
268         fn fold_item(&mut self, i: Item) -> Option<Item> {
269             let mut docstr = String::new();
270             let mut i = i;
271             for attr in i.attrs.iter() {
272                 match *attr {
273                     clean::NameValue(ref x, ref s)
274                             if "doc" == x.as_slice() => {
275                         docstr.push_str(s.as_slice());
276                         docstr.push_char('\n');
277                     },
278                     _ => ()
279                 }
280             }
281             let mut a: Vec<clean::Attribute> = i.attrs.iter().filter(|&a| match a {
282                 &clean::NameValue(ref x, _) if "doc" == x.as_slice() => false,
283                 _ => true
284             }).map(|x| x.clone()).collect();
285             if docstr.len() > 0 {
286                 a.push(clean::NameValue("doc".to_string(), docstr));
287             }
288             i.attrs = a;
289             self.fold_item_recur(i)
290         }
291     }
292     let mut collapser = Collapser;
293     let krate = collapser.fold_crate(krate);
294     (krate, None)
295 }
296
297 pub fn unindent(s: &str) -> String {
298     let lines = s.lines_any().collect::<Vec<&str> >();
299     let mut saw_first_line = false;
300     let mut saw_second_line = false;
301     let min_indent = lines.iter().fold(uint::MAX, |min_indent, line| {
302
303         // After we see the first non-whitespace line, look at
304         // the line we have. If it is not whitespace, and therefore
305         // part of the first paragraph, then ignore the indentation
306         // level of the first line
307         let ignore_previous_indents =
308             saw_first_line &&
309             !saw_second_line &&
310             !line.is_whitespace();
311
312         let min_indent = if ignore_previous_indents {
313             uint::MAX
314         } else {
315             min_indent
316         };
317
318         if saw_first_line {
319             saw_second_line = true;
320         }
321
322         if line.is_whitespace() {
323             min_indent
324         } else {
325             saw_first_line = true;
326             let mut spaces = 0;
327             line.chars().all(|char| {
328                 // Only comparing against space because I wouldn't
329                 // know what to do with mixed whitespace chars
330                 if char == ' ' {
331                     spaces += 1;
332                     true
333                 } else {
334                     false
335                 }
336             });
337             cmp::min(min_indent, spaces)
338         }
339     });
340
341     if lines.len() >= 1 {
342         let mut unindented = vec![ lines.get(0).trim().to_string() ];
343         unindented.push_all(lines.tail().iter().map(|&line| {
344             if line.is_whitespace() {
345                 line.to_string()
346             } else {
347                 assert!(line.len() >= min_indent);
348                 line.slice_from(min_indent).to_string()
349             }
350         }).collect::<Vec<_>>().as_slice());
351         unindented.connect("\n").to_string()
352     } else {
353         s.to_string()
354     }
355 }
356
357 #[cfg(test)]
358 mod unindent_tests {
359     use super::unindent;
360
361     #[test]
362     fn should_unindent() {
363         let s = "    line1\n    line2".to_string();
364         let r = unindent(s.as_slice());
365         assert_eq!(r.as_slice(), "line1\nline2");
366     }
367
368     #[test]
369     fn should_unindent_multiple_paragraphs() {
370         let s = "    line1\n\n    line2".to_string();
371         let r = unindent(s.as_slice());
372         assert_eq!(r.as_slice(), "line1\n\nline2");
373     }
374
375     #[test]
376     fn should_leave_multiple_indent_levels() {
377         // Line 2 is indented another level beyond the
378         // base indentation and should be preserved
379         let s = "    line1\n\n        line2".to_string();
380         let r = unindent(s.as_slice());
381         assert_eq!(r.as_slice(), "line1\n\n    line2");
382     }
383
384     #[test]
385     fn should_ignore_first_line_indent() {
386         // Thi first line of the first paragraph may not be indented as
387         // far due to the way the doc string was written:
388         //
389         // #[doc = "Start way over here
390         //          and continue here"]
391         let s = "line1\n    line2".to_string();
392         let r = unindent(s.as_slice());
393         assert_eq!(r.as_slice(), "line1\nline2");
394     }
395
396     #[test]
397     fn should_not_ignore_first_line_indent_in_a_single_line_para() {
398         let s = "line1\n\n    line2".to_string();
399         let r = unindent(s.as_slice());
400         assert_eq!(r.as_slice(), "line1\n\n    line2");
401     }
402 }