]> git.lizzy.rs Git - rust.git/blob - src/utils.rs
Move isatty() to utils.rs
[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 syntax::abi;
15 use syntax::ast::{self, Attribute, MetaItem, MetaItemKind, NestedMetaItem, NestedMetaItemKind,
16                   Path, Visibility};
17 use syntax::codemap::{BytePos, Span, NO_EXPANSION};
18
19 use Shape;
20 use rewrite::{Rewrite, RewriteContext};
21
22 // When we get scoped annotations, we should have rustfmt::skip.
23 const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
24
25 // Computes the length of a string's last line, minus offset.
26 pub fn extra_offset(text: &str, shape: Shape) -> usize {
27     match text.rfind('\n') {
28         // 1 for newline character
29         Some(idx) => text.len()
30             .checked_sub(idx + 1 + shape.used_width())
31             .unwrap_or(0),
32         None => text.len(),
33     }
34 }
35
36 // Uses Cow to avoid allocating in the common cases.
37 pub fn format_visibility(vis: &Visibility) -> Cow<'static, str> {
38     match *vis {
39         Visibility::Public => Cow::from("pub "),
40         Visibility::Inherited => Cow::from(""),
41         Visibility::Crate(_) => Cow::from("pub(crate) "),
42         Visibility::Restricted { ref path, .. } => {
43             let Path { ref segments, .. } = **path;
44             let mut segments_iter = segments.iter().map(|seg| seg.identifier.name.to_string());
45             if path.is_global() {
46                 segments_iter
47                     .next()
48                     .expect("Non-global path in pub(restricted)?");
49             }
50             let is_keyword = |s: &str| s == "self" || s == "super";
51             let path = segments_iter.collect::<Vec<_>>().join("::");
52             let in_str = if is_keyword(&path) { "" } else { "in " };
53
54             Cow::from(format!("pub({}{}) ", in_str, path))
55         }
56     }
57 }
58
59 #[inline]
60 pub fn format_constness(constness: ast::Constness) -> &'static str {
61     match constness {
62         ast::Constness::Const => "const ",
63         ast::Constness::NotConst => "",
64     }
65 }
66
67 #[inline]
68 pub fn format_defaultness(defaultness: ast::Defaultness) -> &'static str {
69     match defaultness {
70         ast::Defaultness::Default => "default ",
71         ast::Defaultness::Final => "",
72     }
73 }
74
75 #[inline]
76 pub fn format_unsafety(unsafety: ast::Unsafety) -> &'static str {
77     match unsafety {
78         ast::Unsafety::Unsafe => "unsafe ",
79         ast::Unsafety::Normal => "",
80     }
81 }
82
83 #[inline]
84 pub fn format_mutability(mutability: ast::Mutability) -> &'static str {
85     match mutability {
86         ast::Mutability::Mutable => "mut ",
87         ast::Mutability::Immutable => "",
88     }
89 }
90
91 #[inline]
92 pub fn format_abi(abi: abi::Abi, explicit_abi: bool) -> String {
93     if abi == abi::Abi::C && !explicit_abi {
94         "extern ".into()
95     } else {
96         format!("extern {} ", abi)
97     }
98 }
99
100 #[inline]
101 pub fn filter_attributes(attrs: &[ast::Attribute], style: ast::AttrStyle) -> Vec<ast::Attribute> {
102     attrs
103         .iter()
104         .filter(|a| a.style == style)
105         .cloned()
106         .collect::<Vec<_>>()
107 }
108
109 #[inline]
110 pub fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
111     filter_attributes(attrs, ast::AttrStyle::Inner)
112 }
113
114 #[inline]
115 pub fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
116     filter_attributes(attrs, ast::AttrStyle::Outer)
117 }
118
119 #[inline]
120 pub fn last_line_contains_single_line_comment(s: &str) -> bool {
121     s.lines().last().map_or(false, |l| l.contains("//"))
122 }
123
124 #[inline]
125 pub fn is_attributes_extendable(attrs_str: &str) -> bool {
126     !attrs_str.contains('\n') && !last_line_contains_single_line_comment(&attrs_str)
127 }
128
129 // The width of the first line in s.
130 #[inline]
131 pub fn first_line_width(s: &str) -> usize {
132     match s.find('\n') {
133         Some(n) => n,
134         None => s.len(),
135     }
136 }
137
138 // The width of the last line in s.
139 #[inline]
140 pub fn last_line_width(s: &str) -> usize {
141     match s.rfind('\n') {
142         Some(n) => s.len() - n - 1,
143         None => s.len(),
144     }
145 }
146
147 // The total used width of the last line.
148 #[inline]
149 pub fn last_line_used_width(s: &str, offset: usize) -> usize {
150     if s.contains('\n') {
151         last_line_width(s)
152     } else {
153         offset + s.len()
154     }
155 }
156
157 #[inline]
158 pub fn trimmed_last_line_width(s: &str) -> usize {
159     match s.rfind('\n') {
160         Some(n) => s[(n + 1)..].trim().len(),
161         None => s.trim().len(),
162     }
163 }
164
165 #[inline]
166 pub fn last_line_extendable(s: &str) -> bool {
167     s.lines().last().map_or(false, |s| {
168         s.ends_with("\"#") ||
169             s.trim()
170                 .chars()
171                 .all(|c| c == ')' || c == ']' || c == '}' || c == '?')
172     })
173 }
174
175 #[inline]
176 fn is_skip(meta_item: &MetaItem) -> bool {
177     match meta_item.node {
178         MetaItemKind::Word => meta_item.name == SKIP_ANNOTATION,
179         MetaItemKind::List(ref l) => {
180             meta_item.name == "cfg_attr" && l.len() == 2 && is_skip_nested(&l[1])
181         }
182         _ => false,
183     }
184 }
185
186 #[inline]
187 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
188     match meta_item.node {
189         NestedMetaItemKind::MetaItem(ref mi) => is_skip(mi),
190         NestedMetaItemKind::Literal(_) => false,
191     }
192 }
193
194 #[inline]
195 pub fn contains_skip(attrs: &[Attribute]) -> bool {
196     attrs
197         .iter()
198         .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
199 }
200
201 // Find the end of a TyParam
202 #[inline]
203 pub fn end_typaram(typaram: &ast::TyParam) -> BytePos {
204     typaram
205         .bounds
206         .last()
207         .map_or(typaram.span, |bound| match *bound {
208             ast::RegionTyParamBound(ref lt) => lt.span,
209             ast::TraitTyParamBound(ref prt, _) => prt.span,
210         })
211         .hi
212 }
213
214 #[inline]
215 pub fn semicolon_for_expr(context: &RewriteContext, expr: &ast::Expr) -> bool {
216     match expr.node {
217         ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
218             context.config.trailing_semicolon()
219         }
220         _ => false,
221     }
222 }
223
224 #[inline]
225 pub fn semicolon_for_stmt(context: &RewriteContext, stmt: &ast::Stmt) -> bool {
226     match stmt.node {
227         ast::StmtKind::Semi(ref expr) => match expr.node {
228             ast::ExprKind::While(..) |
229             ast::ExprKind::WhileLet(..) |
230             ast::ExprKind::Loop(..) |
231             ast::ExprKind::ForLoop(..) => false,
232             ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
233                 context.config.trailing_semicolon()
234             }
235             _ => true,
236         },
237         ast::StmtKind::Expr(..) => false,
238         _ => true,
239     }
240 }
241
242 #[inline]
243 pub fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
244     match stmt.node {
245         ast::StmtKind::Expr(ref expr) => Some(expr),
246         _ => None,
247     }
248 }
249
250 #[inline]
251 pub fn trim_newlines(input: &str) -> &str {
252     match input.find(|c| c != '\n' && c != '\r') {
253         Some(start) => {
254             let end = input.rfind(|c| c != '\n' && c != '\r').unwrap_or(0) + 1;
255             &input[start..end]
256         }
257         None => "",
258     }
259 }
260
261 // Macro for deriving implementations of Serialize/Deserialize for enums
262 #[macro_export]
263 macro_rules! impl_enum_serialize_and_deserialize {
264     ( $e:ident, $( $x:ident ),* ) => {
265         impl ::serde::ser::Serialize for $e {
266             fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
267                 where S: ::serde::ser::Serializer
268             {
269                 use serde::ser::Error;
270
271                 // We don't know whether the user of the macro has given us all options.
272                 #[allow(unreachable_patterns)]
273                 match *self {
274                     $(
275                         $e::$x => serializer.serialize_str(stringify!($x)),
276                     )*
277                     _ => {
278                         Err(S::Error::custom(format!("Cannot serialize {:?}", self)))
279                     }
280                 }
281             }
282         }
283
284         impl<'de> ::serde::de::Deserialize<'de> for $e {
285             fn deserialize<D>(d: D) -> Result<Self, D::Error>
286                     where D: ::serde::Deserializer<'de> {
287                 use std::ascii::AsciiExt;
288                 use serde::de::{Error, Visitor};
289                 use std::marker::PhantomData;
290                 use std::fmt;
291                 struct StringOnly<T>(PhantomData<T>);
292                 impl<'de, T> Visitor<'de> for StringOnly<T>
293                         where T: ::serde::Deserializer<'de> {
294                     type Value = String;
295                     fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
296                         formatter.write_str("string")
297                     }
298                     fn visit_str<E>(self, value: &str) -> Result<String, E> {
299                         Ok(String::from(value))
300                     }
301                 }
302                 let s = d.deserialize_string(StringOnly::<D>(PhantomData))?;
303                 $(
304                     if stringify!($x).eq_ignore_ascii_case(&s) {
305                       return Ok($e::$x);
306                     }
307                 )*
308                 static ALLOWED: &'static[&str] = &[$(stringify!($x),)*];
309                 Err(D::Error::unknown_variant(&s, ALLOWED))
310             }
311         }
312
313         impl ::std::str::FromStr for $e {
314             type Err = &'static str;
315
316             fn from_str(s: &str) -> Result<Self, Self::Err> {
317                 use std::ascii::AsciiExt;
318                 $(
319                     if stringify!($x).eq_ignore_ascii_case(s) {
320                         return Ok($e::$x);
321                     }
322                 )*
323                 Err("Bad variant")
324             }
325         }
326
327         impl ::config::ConfigType for $e {
328             fn doc_hint() -> String {
329                 let mut variants = Vec::new();
330                 $(
331                     variants.push(stringify!($x));
332                 )*
333                 format!("[{}]", variants.join("|"))
334             }
335         }
336     };
337 }
338
339 // Same as try!, but for Option
340 #[macro_export]
341 macro_rules! try_opt {
342     ($expr:expr) => (match $expr {
343         Some(val) => val,
344         None => { return None; }
345     })
346 }
347
348 macro_rules! msg {
349     ($($arg:tt)*) => (
350         match writeln!(&mut ::std::io::stderr(), $($arg)* ) {
351             Ok(_) => {},
352             Err(x) => panic!("Unable to write to stderr: {}", x),
353         }
354     )
355 }
356
357 // For format_missing and last_pos, need to use the source callsite (if applicable).
358 // Required as generated code spans aren't guaranteed to follow on from the last span.
359 macro_rules! source {
360     ($this:ident, $sp: expr) => {
361         $sp.source_callsite()
362     }
363 }
364
365 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
366     Span {
367         lo,
368         hi,
369         ctxt: NO_EXPANSION,
370     }
371 }
372
373 // Return true if the given span does not intersect with file lines.
374 macro_rules! out_of_file_lines_range {
375     ($self:ident, $span:expr) => {
376         !$self.config
377             .file_lines()
378             .intersects(&$self.codemap.lookup_line_range($span))
379     }
380 }
381
382 macro_rules! skip_out_of_file_lines_range {
383     ($self:ident, $span:expr) => {
384         if out_of_file_lines_range!($self, $span) {
385             return None;
386         }
387     }
388 }
389
390 macro_rules! skip_out_of_file_lines_range_visitor {
391     ($self:ident, $span:expr) => {
392         if out_of_file_lines_range!($self, $span) {
393             $self.push_rewrite($span, None);
394             return;
395         }
396     }
397 }
398
399 // Wraps string-like values in an Option. Returns Some when the string adheres
400 // to the Rewrite constraints defined for the Rewrite trait and else otherwise.
401 pub fn wrap_str<S: AsRef<str>>(s: S, max_width: usize, shape: Shape) -> Option<S> {
402     {
403         let snippet = s.as_ref();
404
405         if !snippet.is_empty() {
406             if !snippet.contains('\n') && snippet.len() > shape.width {
407                 return None;
408             } else {
409                 let mut lines = snippet.lines();
410
411                 if lines.next().unwrap().len() > shape.width {
412                     return None;
413                 }
414
415                 // The other lines must fit within the maximum width.
416                 if lines.any(|line| line.len() > max_width) {
417                     return None;
418                 }
419
420                 // `width` is the maximum length of the last line, excluding
421                 // indentation.
422                 // A special check for the last line, since the caller may
423                 // place trailing characters on this line.
424                 if snippet.lines().rev().next().unwrap().len() > shape.used_width() + shape.width {
425                     return None;
426                 }
427             }
428         }
429     }
430
431     Some(s)
432 }
433
434 impl Rewrite for String {
435     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
436         wrap_str(self, context.config.max_width(), shape).map(ToOwned::to_owned)
437     }
438 }
439
440 // Binary search in integer range. Returns the first Ok value returned by the
441 // callback.
442 // The callback takes an integer and returns either an Ok, or an Err indicating
443 // whether the `guess' was too high (Ordering::Less), or too low.
444 // This function is guaranteed to try to the hi value first.
445 pub fn binary_search<C, T>(mut lo: usize, mut hi: usize, callback: C) -> Option<T>
446 where
447     C: Fn(usize) -> Result<T, Ordering>,
448 {
449     let mut middle = hi;
450
451     while lo <= hi {
452         match callback(middle) {
453             Ok(val) => return Some(val),
454             Err(Ordering::Less) => {
455                 hi = middle - 1;
456             }
457             Err(..) => {
458                 lo = middle + 1;
459             }
460         }
461         middle = (hi + lo) / 2;
462     }
463
464     None
465 }
466
467 #[inline]
468 pub fn colon_spaces(before: bool, after: bool) -> &'static str {
469     match (before, after) {
470         (true, true) => " : ",
471         (true, false) => " :",
472         (false, true) => ": ",
473         (false, false) => ":",
474     }
475 }
476
477 #[inline]
478 pub fn paren_overhead(context: &RewriteContext) -> usize {
479     if context.config.spaces_within_parens() {
480         4
481     } else {
482         2
483     }
484 }
485
486 #[test]
487 fn bin_search_test() {
488     let closure = |i| match i {
489         4 => Ok(()),
490         j if j > 4 => Err(Ordering::Less),
491         j if j < 4 => Err(Ordering::Greater),
492         _ => unreachable!(),
493     };
494
495     assert_eq!(Some(()), binary_search(1, 10, &closure));
496     assert_eq!(None, binary_search(1, 3, &closure));
497     assert_eq!(Some(()), binary_search(0, 44, &closure));
498     assert_eq!(Some(()), binary_search(4, 125, &closure));
499     assert_eq!(None, binary_search(6, 100, &closure));
500 }
501
502 pub fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
503     match e.node {
504         ast::ExprKind::InPlace(ref e, _) |
505         ast::ExprKind::Call(ref e, _) |
506         ast::ExprKind::Binary(_, ref e, _) |
507         ast::ExprKind::Cast(ref e, _) |
508         ast::ExprKind::Type(ref e, _) |
509         ast::ExprKind::Assign(ref e, _) |
510         ast::ExprKind::AssignOp(_, ref e, _) |
511         ast::ExprKind::Field(ref e, _) |
512         ast::ExprKind::TupField(ref e, _) |
513         ast::ExprKind::Index(ref e, _) |
514         ast::ExprKind::Range(Some(ref e), _, _) |
515         ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
516         _ => e,
517     }
518 }
519
520 // isatty shamelessly adapted from cargo.
521 #[cfg(unix)]
522 pub fn isatty() -> bool {
523     extern crate libc;
524
525     unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
526 }
527 #[cfg(windows)]
528 pub fn isatty() -> bool {
529     extern crate kernel32;
530     extern crate winapi;
531
532     unsafe {
533         let handle = kernel32::GetStdHandle(winapi::winbase::STD_OUTPUT_HANDLE);
534         let mut out = 0;
535         kernel32::GetConsoleMode(handle, &mut out) != 0
536     }
537 }