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