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