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