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