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