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