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