]> git.lizzy.rs Git - rust.git/blob - src/utils.rs
Merge pull request #1326 from durka/assoc-type-density
[rust.git] / src / utils.rs
1 // Copyright 2015 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 std::borrow::Cow;
12 use std::cmp::Ordering;
13
14 use itertools::Itertools;
15
16 use syntax::ast::{self, Visibility, Attribute, MetaItem, MetaItemKind, NestedMetaItem,
17                   NestedMetaItemKind, Path};
18 use syntax::codemap::BytePos;
19 use syntax::abi;
20
21 use Shape;
22 use rewrite::{Rewrite, RewriteContext};
23
24 use SKIP_ANNOTATION;
25
26 // Computes the length of a string's last line, minus offset.
27 pub fn extra_offset(text: &str, shape: Shape) -> usize {
28     match text.rfind('\n') {
29         // 1 for newline character
30         Some(idx) => text.len().checked_sub(idx + 1 + shape.used_width()).unwrap_or(0),
31         None => text.len(),
32     }
33 }
34
35 // Uses Cow to avoid allocating in the common cases.
36 pub fn format_visibility(vis: &Visibility) -> Cow<'static, str> {
37     match *vis {
38         Visibility::Public => Cow::from("pub "),
39         Visibility::Inherited => Cow::from(""),
40         Visibility::Crate(_) => Cow::from("pub(crate) "),
41         Visibility::Restricted { ref path, .. } => {
42             let Path { ref segments, .. } = **path;
43             let mut segments_iter = segments.iter().map(|seg| seg.identifier.name.as_str());
44             if path.is_global() {
45                 segments_iter.next().expect("Non-global path in pub(restricted)?");
46             }
47
48             Cow::from(format!("pub({}) ", segments_iter.join("::")))
49         }
50     }
51 }
52
53 #[inline]
54 pub fn format_unsafety(unsafety: ast::Unsafety) -> &'static str {
55     match unsafety {
56         ast::Unsafety::Unsafe => "unsafe ",
57         ast::Unsafety::Normal => "",
58     }
59 }
60
61 #[inline]
62 pub fn format_mutability(mutability: ast::Mutability) -> &'static str {
63     match mutability {
64         ast::Mutability::Mutable => "mut ",
65         ast::Mutability::Immutable => "",
66     }
67 }
68
69 #[inline]
70 pub fn format_abi(abi: abi::Abi, explicit_abi: bool) -> String {
71     if abi == abi::Abi::C && !explicit_abi {
72         "extern ".into()
73     } else {
74         format!("extern {} ", abi)
75     }
76 }
77
78 // The width of the first line in s.
79 #[inline]
80 pub fn first_line_width(s: &str) -> usize {
81     match s.find('\n') {
82         Some(n) => n,
83         None => s.len(),
84     }
85 }
86
87 // The width of the last line in s.
88 #[inline]
89 pub fn last_line_width(s: &str) -> usize {
90     match s.rfind('\n') {
91         Some(n) => s.len() - n - 1,
92         None => s.len(),
93     }
94 }
95 #[inline]
96 pub fn trimmed_last_line_width(s: &str) -> usize {
97     match s.rfind('\n') {
98         Some(n) => s[(n + 1)..].trim().len(),
99         None => s.trim().len(),
100     }
101 }
102
103 #[inline]
104 fn is_skip(meta_item: &MetaItem) -> bool {
105     match meta_item.node {
106         MetaItemKind::Word => meta_item.name == SKIP_ANNOTATION,
107         MetaItemKind::List(ref l) => {
108             meta_item.name == "cfg_attr" && l.len() == 2 && is_skip_nested(&l[1])
109         }
110         _ => false,
111     }
112 }
113
114 #[inline]
115 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
116     match meta_item.node {
117         NestedMetaItemKind::MetaItem(ref mi) => is_skip(mi),
118         NestedMetaItemKind::Literal(_) => false,
119     }
120 }
121
122 #[inline]
123 pub fn contains_skip(attrs: &[Attribute]) -> bool {
124     attrs.iter().any(|a| is_skip(&a.value))
125 }
126
127 // Find the end of a TyParam
128 #[inline]
129 pub fn end_typaram(typaram: &ast::TyParam) -> BytePos {
130     typaram.bounds
131         .last()
132         .map_or(typaram.span, |bound| match *bound {
133             ast::RegionTyParamBound(ref lt) => lt.span,
134             ast::TraitTyParamBound(ref prt, _) => prt.span,
135         })
136         .hi
137 }
138
139 #[inline]
140 pub fn semicolon_for_expr(expr: &ast::Expr) -> bool {
141     match expr.node {
142         ast::ExprKind::Ret(..) |
143         ast::ExprKind::Continue(..) |
144         ast::ExprKind::Break(..) => true,
145         _ => false,
146     }
147 }
148
149 #[inline]
150 pub fn semicolon_for_stmt(stmt: &ast::Stmt) -> bool {
151     match stmt.node {
152         ast::StmtKind::Semi(ref expr) => {
153             match expr.node {
154                 ast::ExprKind::While(..) |
155                 ast::ExprKind::WhileLet(..) |
156                 ast::ExprKind::Loop(..) |
157                 ast::ExprKind::ForLoop(..) => false,
158                 _ => true,
159             }
160         }
161         ast::StmtKind::Expr(..) => false,
162         _ => true,
163     }
164 }
165
166 #[inline]
167 pub fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
168     match stmt.node {
169         ast::StmtKind::Expr(ref expr) => Some(expr),
170         _ => None,
171     }
172 }
173
174 #[inline]
175 pub fn trim_newlines(input: &str) -> &str {
176     match input.find(|c| c != '\n' && c != '\r') {
177         Some(start) => {
178             let end = input.rfind(|c| c != '\n' && c != '\r').unwrap_or(0) + 1;
179             &input[start..end]
180         }
181         None => "",
182     }
183 }
184
185 // Macro for deriving implementations of Decodable for enums
186 #[macro_export]
187 macro_rules! impl_enum_decodable {
188     ( $e:ident, $( $x:ident ),* ) => {
189         impl ::rustc_serialize::Decodable for $e {
190             fn decode<D: ::rustc_serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
191                 use std::ascii::AsciiExt;
192                 let s = try!(d.read_str());
193                 $(
194                     if stringify!($x).eq_ignore_ascii_case(&s) {
195                       return Ok($e::$x);
196                     }
197                 )*
198                 Err(d.error("Bad variant"))
199             }
200         }
201
202         impl ::std::str::FromStr for $e {
203             type Err = &'static str;
204
205             fn from_str(s: &str) -> Result<Self, Self::Err> {
206                 use std::ascii::AsciiExt;
207                 $(
208                     if stringify!($x).eq_ignore_ascii_case(s) {
209                         return Ok($e::$x);
210                     }
211                 )*
212                 Err("Bad variant")
213             }
214         }
215
216         impl ::config::ConfigType for $e {
217             fn doc_hint() -> String {
218                 let mut variants = Vec::new();
219                 $(
220                     variants.push(stringify!($x));
221                 )*
222                 format!("[{}]", variants.join("|"))
223             }
224         }
225     };
226 }
227
228 // Same as try!, but for Option
229 #[macro_export]
230 macro_rules! try_opt {
231     ($expr:expr) => (match $expr {
232         Some(val) => val,
233         None => { return None; }
234     })
235 }
236
237 macro_rules! msg {
238     ($($arg:tt)*) => (
239         match writeln!(&mut ::std::io::stderr(), $($arg)* ) {
240             Ok(_) => {},
241             Err(x) => panic!("Unable to write to stderr: {}", x),
242         }
243     )
244 }
245
246 // For format_missing and last_pos, need to use the source callsite (if applicable).
247 // Required as generated code spans aren't guaranteed to follow on from the last span.
248 macro_rules! source {
249     ($this:ident, $sp: expr) => {
250         $this.codemap.source_callsite($sp)
251     }
252 }
253
254 // Wraps string-like values in an Option. Returns Some when the string adheres
255 // to the Rewrite constraints defined for the Rewrite trait and else otherwise.
256 pub fn wrap_str<S: AsRef<str>>(s: S, max_width: usize, shape: Shape) -> Option<S> {
257     {
258         let snippet = s.as_ref();
259
260         if !snippet.contains('\n') && snippet.len() > shape.width {
261             return None;
262         } else {
263             let mut lines = snippet.lines();
264
265             // The caller of this function has already placed `shape.offset`
266             // characters on the first line.
267             let first_line_max_len = try_opt!(max_width.checked_sub(shape.indent.width()));
268             if lines.next().unwrap().len() > first_line_max_len {
269                 return None;
270             }
271
272             // The other lines must fit within the maximum width.
273             if lines.any(|line| line.len() > max_width) {
274                 return None;
275             }
276
277             // `width` is the maximum length of the last line, excluding
278             // indentation.
279             // A special check for the last line, since the caller may
280             // place trailing characters on this line.
281             if snippet.lines().rev().next().unwrap().len() > shape.indent.width() + shape.width {
282                 return None;
283             }
284         }
285     }
286
287     Some(s)
288 }
289
290 impl Rewrite for String {
291     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
292         wrap_str(self, context.config.max_width, shape).map(ToOwned::to_owned)
293     }
294 }
295
296 // Binary search in integer range. Returns the first Ok value returned by the
297 // callback.
298 // The callback takes an integer and returns either an Ok, or an Err indicating
299 // whether the `guess' was too high (Ordering::Less), or too low.
300 // This function is guaranteed to try to the hi value first.
301 pub fn binary_search<C, T>(mut lo: usize, mut hi: usize, callback: C) -> Option<T>
302     where C: Fn(usize) -> Result<T, Ordering>
303 {
304     let mut middle = hi;
305
306     while lo <= hi {
307         match callback(middle) {
308             Ok(val) => return Some(val),
309             Err(Ordering::Less) => {
310                 hi = middle - 1;
311             }
312             Err(..) => {
313                 lo = middle + 1;
314             }
315         }
316         middle = (hi + lo) / 2;
317     }
318
319     None
320 }
321
322 #[test]
323 fn bin_search_test() {
324     let closure = |i| match i {
325         4 => Ok(()),
326         j if j > 4 => Err(Ordering::Less),
327         j if j < 4 => Err(Ordering::Greater),
328         _ => unreachable!(),
329     };
330
331     assert_eq!(Some(()), binary_search(1, 10, &closure));
332     assert_eq!(None, binary_search(1, 3, &closure));
333     assert_eq!(Some(()), binary_search(0, 44, &closure));
334     assert_eq!(Some(()), binary_search(4, 125, &closure));
335     assert_eq!(None, binary_search(6, 100, &closure));
336 }
337
338 pub fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
339     match e.node {
340         ast::ExprKind::InPlace(ref e, _) |
341         ast::ExprKind::Call(ref e, _) |
342         ast::ExprKind::Binary(_, ref e, _) |
343         ast::ExprKind::Cast(ref e, _) |
344         ast::ExprKind::Type(ref e, _) |
345         ast::ExprKind::Assign(ref e, _) |
346         ast::ExprKind::AssignOp(_, ref e, _) |
347         ast::ExprKind::Field(ref e, _) |
348         ast::ExprKind::TupField(ref e, _) |
349         ast::ExprKind::Index(ref e, _) |
350         ast::ExprKind::Range(Some(ref e), _, _) |
351         ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
352         _ => e,
353     }
354 }