]> git.lizzy.rs Git - rust.git/blob - src/utils.rs
Cargo fmt
[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 rustc_target::spec::abi;
14 use syntax::ast::{
15     self, Attribute, CrateSugar, MetaItem, MetaItemKind, NestedMetaItem, NestedMetaItemKind, Path,
16     Visibility, VisibilityKind,
17 };
18 use syntax::codemap::{BytePos, Span, NO_EXPANSION};
19 use syntax::ptr;
20
21 use config::Color;
22 use rewrite::RewriteContext;
23 use shape::Shape;
24
25 // When we get scoped annotations, we should have rustfmt::skip.
26 const SKIP_ANNOTATION: &str = "rustfmt_skip";
27
28 // Computes the length of a string's last line, minus offset.
29 pub fn extra_offset(text: &str, shape: Shape) -> usize {
30     match text.rfind('\n') {
31         // 1 for newline character
32         Some(idx) => text
33             .len()
34             .checked_sub(idx + 1 + shape.used_width())
35             .unwrap_or(0),
36         None => text.len(),
37     }
38 }
39
40 // Uses Cow to avoid allocating in the common cases.
41 pub fn format_visibility(vis: &Visibility) -> Cow<'static, str> {
42     match vis.node {
43         VisibilityKind::Public => Cow::from("pub "),
44         VisibilityKind::Inherited => Cow::from(""),
45         VisibilityKind::Crate(CrateSugar::PubCrate) => Cow::from("pub(crate) "),
46         VisibilityKind::Crate(CrateSugar::JustCrate) => Cow::from("crate "),
47         VisibilityKind::Restricted { ref path, .. } => {
48             let Path { ref segments, .. } = **path;
49             let mut segments_iter = segments.iter().map(|seg| seg.ident.name.to_string());
50             if path.is_global() {
51                 segments_iter
52                     .next()
53                     .expect("Non-global path in pub(restricted)?");
54             }
55             let is_keyword = |s: &str| s == "self" || s == "super";
56             let path = segments_iter.collect::<Vec<_>>().join("::");
57             let in_str = if is_keyword(&path) { "" } else { "in " };
58
59             Cow::from(format!("pub({}{}) ", in_str, path))
60         }
61     }
62 }
63
64 #[inline]
65 pub fn format_constness(constness: ast::Constness) -> &'static str {
66     match constness {
67         ast::Constness::Const => "const ",
68         ast::Constness::NotConst => "",
69     }
70 }
71
72 #[inline]
73 pub fn format_defaultness(defaultness: ast::Defaultness) -> &'static str {
74     match defaultness {
75         ast::Defaultness::Default => "default ",
76         ast::Defaultness::Final => "",
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_auto(is_auto: ast::IsAuto) -> &'static str {
90     match is_auto {
91         ast::IsAuto::Yes => "auto ",
92         ast::IsAuto::No => "",
93     }
94 }
95
96 #[inline]
97 pub fn format_mutability(mutability: ast::Mutability) -> &'static str {
98     match mutability {
99         ast::Mutability::Mutable => "mut ",
100         ast::Mutability::Immutable => "",
101     }
102 }
103
104 #[inline]
105 pub fn format_abi(abi: abi::Abi, explicit_abi: bool, is_mod: bool) -> Cow<'static, str> {
106     if abi == abi::Abi::Rust && !is_mod {
107         Cow::from("")
108     } else if abi == abi::Abi::C && !explicit_abi {
109         Cow::from("extern ")
110     } else {
111         Cow::from(format!("extern {} ", abi))
112     }
113 }
114
115 #[inline]
116 // Transform `Vec<syntax::ptr::P<T>>` into `Vec<&T>`
117 pub fn ptr_vec_to_ref_vec<T>(vec: &[ptr::P<T>]) -> Vec<&T> {
118     vec.iter().map(|x| &**x).collect::<Vec<_>>()
119 }
120
121 #[inline]
122 pub fn filter_attributes(attrs: &[ast::Attribute], style: ast::AttrStyle) -> Vec<ast::Attribute> {
123     attrs
124         .iter()
125         .filter(|a| a.style == style)
126         .cloned()
127         .collect::<Vec<_>>()
128 }
129
130 #[inline]
131 pub fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
132     filter_attributes(attrs, ast::AttrStyle::Inner)
133 }
134
135 #[inline]
136 pub fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
137     filter_attributes(attrs, ast::AttrStyle::Outer)
138 }
139
140 #[inline]
141 pub fn is_single_line(s: &str) -> bool {
142     s.chars().find(|&c| c == '\n').is_none()
143 }
144
145 #[inline]
146 pub fn first_line_contains_single_line_comment(s: &str) -> bool {
147     s.lines().next().map_or(false, |l| l.contains("//"))
148 }
149
150 #[inline]
151 pub fn last_line_contains_single_line_comment(s: &str) -> bool {
152     s.lines().last().map_or(false, |l| l.contains("//"))
153 }
154
155 #[inline]
156 pub fn is_attributes_extendable(attrs_str: &str) -> bool {
157     !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
158 }
159
160 // The width of the first line in s.
161 #[inline]
162 pub fn first_line_width(s: &str) -> usize {
163     match s.find('\n') {
164         Some(n) => n,
165         None => s.len(),
166     }
167 }
168
169 // The width of the last line in s.
170 #[inline]
171 pub fn last_line_width(s: &str) -> usize {
172     match s.rfind('\n') {
173         Some(n) => s.len() - n - 1,
174         None => s.len(),
175     }
176 }
177
178 // The total used width of the last line.
179 #[inline]
180 pub fn last_line_used_width(s: &str, offset: usize) -> usize {
181     if s.contains('\n') {
182         last_line_width(s)
183     } else {
184         offset + s.len()
185     }
186 }
187
188 #[inline]
189 pub fn trimmed_last_line_width(s: &str) -> usize {
190     match s.rfind('\n') {
191         Some(n) => s[(n + 1)..].trim().len(),
192         None => s.trim().len(),
193     }
194 }
195
196 #[inline]
197 pub fn last_line_extendable(s: &str) -> bool {
198     if s.ends_with("\"#") {
199         return true;
200     }
201     for c in s.chars().rev() {
202         match c {
203             '(' | ')' | ']' | '}' | '?' | '>' => continue,
204             '\n' => break,
205             _ if c.is_whitespace() => continue,
206             _ => return false,
207         }
208     }
209     true
210 }
211
212 #[inline]
213 fn is_skip(meta_item: &MetaItem) -> bool {
214     match meta_item.node {
215         MetaItemKind::Word => meta_item.name() == SKIP_ANNOTATION,
216         MetaItemKind::List(ref l) => {
217             meta_item.name() == "cfg_attr" && l.len() == 2 && is_skip_nested(&l[1])
218         }
219         _ => false,
220     }
221 }
222
223 #[inline]
224 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
225     match meta_item.node {
226         NestedMetaItemKind::MetaItem(ref mi) => is_skip(mi),
227         NestedMetaItemKind::Literal(_) => false,
228     }
229 }
230
231 #[inline]
232 pub fn contains_skip(attrs: &[Attribute]) -> bool {
233     attrs
234         .iter()
235         .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
236 }
237
238 #[inline]
239 pub fn semicolon_for_expr(context: &RewriteContext, expr: &ast::Expr) -> bool {
240     match expr.node {
241         ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
242             context.config.trailing_semicolon()
243         }
244         _ => false,
245     }
246 }
247
248 #[inline]
249 pub fn semicolon_for_stmt(context: &RewriteContext, stmt: &ast::Stmt) -> bool {
250     match stmt.node {
251         ast::StmtKind::Semi(ref expr) => match expr.node {
252             ast::ExprKind::While(..)
253             | ast::ExprKind::WhileLet(..)
254             | ast::ExprKind::Loop(..)
255             | ast::ExprKind::ForLoop(..) => false,
256             ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
257                 context.config.trailing_semicolon()
258             }
259             _ => true,
260         },
261         ast::StmtKind::Expr(..) => false,
262         _ => true,
263     }
264 }
265
266 #[inline]
267 pub fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
268     match stmt.node {
269         ast::StmtKind::Expr(ref expr) => Some(expr),
270         _ => None,
271     }
272 }
273
274 #[inline]
275 pub fn count_newlines(input: &str) -> usize {
276     // Using `as_bytes` to omit UTF-8 decoding
277     input.as_bytes().iter().filter(|&&c| c == b'\n').count()
278 }
279
280 // For format_missing and last_pos, need to use the source callsite (if applicable).
281 // Required as generated code spans aren't guaranteed to follow on from the last span.
282 macro_rules! source {
283     ($this:ident, $sp:expr) => {
284         $sp.source_callsite()
285     };
286 }
287
288 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
289     Span::new(lo, hi, NO_EXPANSION)
290 }
291
292 // Return true if the given span does not intersect with file lines.
293 macro_rules! out_of_file_lines_range {
294     ($self:ident, $span:expr) => {
295         !$self.config.file_lines().is_all()
296             && !$self
297                 .config
298                 .file_lines()
299                 .intersects(&$self.codemap.lookup_line_range($span))
300     };
301 }
302
303 macro_rules! skip_out_of_file_lines_range {
304     ($self:ident, $span:expr) => {
305         if out_of_file_lines_range!($self, $span) {
306             return None;
307         }
308     };
309 }
310
311 macro_rules! skip_out_of_file_lines_range_visitor {
312     ($self:ident, $span:expr) => {
313         if out_of_file_lines_range!($self, $span) {
314             $self.push_rewrite($span, None);
315             return;
316         }
317     };
318 }
319
320 // Wraps String in an Option. Returns Some when the string adheres to the
321 // Rewrite constraints defined for the Rewrite trait and else otherwise.
322 pub fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
323     if is_valid_str(&s, max_width, shape) {
324         Some(s)
325     } else {
326         None
327     }
328 }
329
330 fn is_valid_str(snippet: &str, max_width: usize, shape: Shape) -> bool {
331     if !snippet.is_empty() {
332         // First line must fits with `shape.width`.
333         if first_line_width(snippet) > shape.width {
334             return false;
335         }
336         // If the snippet does not include newline, we are done.
337         if first_line_width(snippet) == snippet.len() {
338             return true;
339         }
340         // The other lines must fit within the maximum width.
341         if snippet.lines().skip(1).any(|line| line.len() > max_width) {
342             return false;
343         }
344         // A special check for the last line, since the caller may
345         // place trailing characters on this line.
346         if last_line_width(snippet) > shape.used_width() + shape.width {
347             return false;
348         }
349     }
350     true
351 }
352
353 #[inline]
354 pub fn colon_spaces(before: bool, after: bool) -> &'static str {
355     match (before, after) {
356         (true, true) => " : ",
357         (true, false) => " :",
358         (false, true) => ": ",
359         (false, false) => ":",
360     }
361 }
362
363 #[inline]
364 pub fn paren_overhead(context: &RewriteContext) -> usize {
365     if context.config.spaces_within_parens_and_brackets() {
366         4
367     } else {
368         2
369     }
370 }
371
372 pub fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
373     match e.node {
374         ast::ExprKind::Call(ref e, _)
375         | ast::ExprKind::Binary(_, ref e, _)
376         | ast::ExprKind::Cast(ref e, _)
377         | ast::ExprKind::Type(ref e, _)
378         | ast::ExprKind::Assign(ref e, _)
379         | ast::ExprKind::AssignOp(_, ref e, _)
380         | ast::ExprKind::Field(ref e, _)
381         | ast::ExprKind::Index(ref e, _)
382         | ast::ExprKind::Range(Some(ref e), _, _)
383         | ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
384         _ => e,
385     }
386 }
387
388 // isatty shamelessly adapted from cargo.
389 #[cfg(unix)]
390 pub fn isatty() -> bool {
391     extern crate libc;
392
393     unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
394 }
395 #[cfg(windows)]
396 pub fn isatty() -> bool {
397     extern crate winapi;
398
399     unsafe {
400         let handle = winapi::um::processenv::GetStdHandle(winapi::um::winbase::STD_OUTPUT_HANDLE);
401         let mut out = 0;
402         winapi::um::consoleapi::GetConsoleMode(handle, &mut out) != 0
403     }
404 }
405
406 pub fn use_colored_tty(color: Color) -> bool {
407     match color {
408         Color::Always => true,
409         Color::Never => false,
410         Color::Auto => isatty(),
411     }
412 }
413
414 pub fn starts_with_newline(s: &str) -> bool {
415     s.starts_with('\n') || s.starts_with("\r\n")
416 }