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