]> git.lizzy.rs Git - rust.git/blob - src/utils.rs
rustfmt: add support to specify the Rust edition as argument
[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 bytecount;
14
15 use rustc_target::spec::abi;
16 use syntax::ast::{
17     self, Attribute, CrateSugar, MetaItem, MetaItemKind, NestedMetaItem, NestedMetaItemKind, Path,
18     Visibility, VisibilityKind,
19 };
20 use syntax::ptr;
21 use syntax::source_map::{BytePos, Span, NO_EXPANSION};
22
23 use comment::{filter_normal_code, CharClasses, FullCodeCharKind};
24 use rewrite::RewriteContext;
25 use shape::Shape;
26
27 pub const DEPR_SKIP_ANNOTATION: &str = "rustfmt_skip";
28 pub const SKIP_ANNOTATION: &str = "rustfmt::skip";
29
30 pub fn rewrite_ident<'a>(context: &'a RewriteContext, ident: ast::Ident) -> &'a str {
31     context.snippet(ident.span)
32 }
33
34 // Computes the length of a string's last line, minus offset.
35 pub fn extra_offset(text: &str, shape: Shape) -> usize {
36     match text.rfind('\n') {
37         // 1 for newline character
38         Some(idx) => text.len().saturating_sub(idx + 1 + shape.used_width()),
39         None => text.len(),
40     }
41 }
42
43 pub fn is_same_visibility(a: &Visibility, b: &Visibility) -> bool {
44     match (&a.node, &b.node) {
45         (
46             VisibilityKind::Restricted { path: p, .. },
47             VisibilityKind::Restricted { path: q, .. },
48         ) => p.to_string() == q.to_string(),
49         (VisibilityKind::Public, VisibilityKind::Public)
50         | (VisibilityKind::Inherited, VisibilityKind::Inherited)
51         | (
52             VisibilityKind::Crate(CrateSugar::PubCrate),
53             VisibilityKind::Crate(CrateSugar::PubCrate),
54         )
55         | (
56             VisibilityKind::Crate(CrateSugar::JustCrate),
57             VisibilityKind::Crate(CrateSugar::JustCrate),
58         ) => true,
59         _ => false,
60     }
61 }
62
63 // Uses Cow to avoid allocating in the common cases.
64 pub fn format_visibility(context: &RewriteContext, vis: &Visibility) -> Cow<'static, str> {
65     match vis.node {
66         VisibilityKind::Public => Cow::from("pub "),
67         VisibilityKind::Inherited => Cow::from(""),
68         VisibilityKind::Crate(CrateSugar::PubCrate) => Cow::from("pub(crate) "),
69         VisibilityKind::Crate(CrateSugar::JustCrate) => Cow::from("crate "),
70         VisibilityKind::Restricted { ref path, .. } => {
71             let Path { ref segments, .. } = **path;
72             let mut segments_iter = segments.iter().map(|seg| rewrite_ident(context, seg.ident));
73             if path.is_global() {
74                 segments_iter
75                     .next()
76                     .expect("Non-global path in pub(restricted)?");
77             }
78             let is_keyword = |s: &str| s == "self" || s == "super";
79             let path = segments_iter.collect::<Vec<_>>().join("::");
80             let in_str = if is_keyword(&path) { "" } else { "in " };
81
82             Cow::from(format!("pub({}{}) ", in_str, path))
83         }
84     }
85 }
86
87 #[inline]
88 pub fn format_async(is_async: ast::IsAsync) -> &'static str {
89     match is_async {
90         ast::IsAsync::Async { .. } => "async ",
91         ast::IsAsync::NotAsync => "",
92     }
93 }
94
95 #[inline]
96 pub fn format_constness(constness: ast::Constness) -> &'static str {
97     match constness {
98         ast::Constness::Const => "const ",
99         ast::Constness::NotConst => "",
100     }
101 }
102
103 #[inline]
104 pub fn format_defaultness(defaultness: ast::Defaultness) -> &'static str {
105     match defaultness {
106         ast::Defaultness::Default => "default ",
107         ast::Defaultness::Final => "",
108     }
109 }
110
111 #[inline]
112 pub fn format_unsafety(unsafety: ast::Unsafety) -> &'static str {
113     match unsafety {
114         ast::Unsafety::Unsafe => "unsafe ",
115         ast::Unsafety::Normal => "",
116     }
117 }
118
119 #[inline]
120 pub fn format_auto(is_auto: ast::IsAuto) -> &'static str {
121     match is_auto {
122         ast::IsAuto::Yes => "auto ",
123         ast::IsAuto::No => "",
124     }
125 }
126
127 #[inline]
128 pub fn format_mutability(mutability: ast::Mutability) -> &'static str {
129     match mutability {
130         ast::Mutability::Mutable => "mut ",
131         ast::Mutability::Immutable => "",
132     }
133 }
134
135 #[inline]
136 pub fn format_abi(abi: abi::Abi, explicit_abi: bool, is_mod: bool) -> Cow<'static, str> {
137     if abi == abi::Abi::Rust && !is_mod {
138         Cow::from("")
139     } else if abi == abi::Abi::C && !explicit_abi {
140         Cow::from("extern ")
141     } else {
142         Cow::from(format!("extern {} ", abi))
143     }
144 }
145
146 #[inline]
147 // Transform `Vec<syntax::ptr::P<T>>` into `Vec<&T>`
148 pub fn ptr_vec_to_ref_vec<T>(vec: &[ptr::P<T>]) -> Vec<&T> {
149     vec.iter().map(|x| &**x).collect::<Vec<_>>()
150 }
151
152 #[inline]
153 pub fn filter_attributes(attrs: &[ast::Attribute], style: ast::AttrStyle) -> Vec<ast::Attribute> {
154     attrs
155         .iter()
156         .filter(|a| a.style == style)
157         .cloned()
158         .collect::<Vec<_>>()
159 }
160
161 #[inline]
162 pub fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
163     filter_attributes(attrs, ast::AttrStyle::Inner)
164 }
165
166 #[inline]
167 pub fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
168     filter_attributes(attrs, ast::AttrStyle::Outer)
169 }
170
171 #[inline]
172 pub fn is_single_line(s: &str) -> bool {
173     s.chars().find(|&c| c == '\n').is_none()
174 }
175
176 #[inline]
177 pub fn first_line_contains_single_line_comment(s: &str) -> bool {
178     s.lines().next().map_or(false, |l| l.contains("//"))
179 }
180
181 #[inline]
182 pub fn last_line_contains_single_line_comment(s: &str) -> bool {
183     s.lines().last().map_or(false, |l| l.contains("//"))
184 }
185
186 #[inline]
187 pub fn is_attributes_extendable(attrs_str: &str) -> bool {
188     !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
189 }
190
191 // The width of the first line in s.
192 #[inline]
193 pub fn first_line_width(s: &str) -> usize {
194     match s.find('\n') {
195         Some(n) => n,
196         None => s.len(),
197     }
198 }
199
200 // The width of the last line in s.
201 #[inline]
202 pub fn last_line_width(s: &str) -> usize {
203     match s.rfind('\n') {
204         Some(n) => s.len() - n - 1,
205         None => s.len(),
206     }
207 }
208
209 // The total used width of the last line.
210 #[inline]
211 pub fn last_line_used_width(s: &str, offset: usize) -> usize {
212     if s.contains('\n') {
213         last_line_width(s)
214     } else {
215         offset + s.len()
216     }
217 }
218
219 #[inline]
220 pub fn trimmed_last_line_width(s: &str) -> usize {
221     match s.rfind('\n') {
222         Some(n) => s[(n + 1)..].trim().len(),
223         None => s.trim().len(),
224     }
225 }
226
227 #[inline]
228 pub fn last_line_extendable(s: &str) -> bool {
229     if s.ends_with("\"#") {
230         return true;
231     }
232     for c in s.chars().rev() {
233         match c {
234             '(' | ')' | ']' | '}' | '?' | '>' => continue,
235             '\n' => break,
236             _ if c.is_whitespace() => continue,
237             _ => return false,
238         }
239     }
240     true
241 }
242
243 #[inline]
244 fn is_skip(meta_item: &MetaItem) -> bool {
245     match meta_item.node {
246         MetaItemKind::Word => {
247             let path_str = meta_item.ident.to_string();
248             path_str == SKIP_ANNOTATION || path_str == DEPR_SKIP_ANNOTATION
249         }
250         MetaItemKind::List(ref l) => {
251             meta_item.name() == "cfg_attr" && l.len() == 2 && is_skip_nested(&l[1])
252         }
253         _ => false,
254     }
255 }
256
257 #[inline]
258 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
259     match meta_item.node {
260         NestedMetaItemKind::MetaItem(ref mi) => is_skip(mi),
261         NestedMetaItemKind::Literal(_) => false,
262     }
263 }
264
265 #[inline]
266 pub fn contains_skip(attrs: &[Attribute]) -> bool {
267     attrs
268         .iter()
269         .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
270 }
271
272 #[inline]
273 pub fn semicolon_for_expr(context: &RewriteContext, expr: &ast::Expr) -> bool {
274     match expr.node {
275         ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
276             context.config.trailing_semicolon()
277         }
278         _ => false,
279     }
280 }
281
282 #[inline]
283 pub fn semicolon_for_stmt(context: &RewriteContext, stmt: &ast::Stmt) -> bool {
284     match stmt.node {
285         ast::StmtKind::Semi(ref expr) => match expr.node {
286             ast::ExprKind::While(..)
287             | ast::ExprKind::WhileLet(..)
288             | ast::ExprKind::Loop(..)
289             | ast::ExprKind::ForLoop(..) => false,
290             ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
291                 context.config.trailing_semicolon()
292             }
293             _ => true,
294         },
295         ast::StmtKind::Expr(..) => false,
296         _ => true,
297     }
298 }
299
300 #[inline]
301 pub fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
302     match stmt.node {
303         ast::StmtKind::Expr(ref expr) => Some(expr),
304         _ => None,
305     }
306 }
307
308 #[inline]
309 pub fn count_newlines(input: &str) -> usize {
310     // Using bytes to omit UTF-8 decoding
311     bytecount::count(input.as_bytes(), b'\n')
312 }
313
314 // For format_missing and last_pos, need to use the source callsite (if applicable).
315 // Required as generated code spans aren't guaranteed to follow on from the last span.
316 macro_rules! source {
317     ($this:ident, $sp:expr) => {
318         $sp.source_callsite()
319     };
320 }
321
322 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
323     Span::new(lo, hi, NO_EXPANSION)
324 }
325
326 // Return true if the given span does not intersect with file lines.
327 macro_rules! out_of_file_lines_range {
328     ($self:ident, $span:expr) => {
329         !$self.config.file_lines().is_all()
330             && !$self
331                 .config
332                 .file_lines()
333                 .intersects(&$self.source_map.lookup_line_range($span))
334     };
335 }
336
337 macro_rules! skip_out_of_file_lines_range {
338     ($self:ident, $span:expr) => {
339         if out_of_file_lines_range!($self, $span) {
340             return None;
341         }
342     };
343 }
344
345 macro_rules! skip_out_of_file_lines_range_visitor {
346     ($self:ident, $span:expr) => {
347         if out_of_file_lines_range!($self, $span) {
348             $self.push_rewrite($span, None);
349             return;
350         }
351     };
352 }
353
354 // Wraps String in an Option. Returns Some when the string adheres to the
355 // Rewrite constraints defined for the Rewrite trait and None otherwise.
356 pub fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
357     if is_valid_str(&filter_normal_code(&s), max_width, shape) {
358         Some(s)
359     } else {
360         None
361     }
362 }
363
364 fn is_valid_str(snippet: &str, max_width: usize, shape: Shape) -> bool {
365     if !snippet.is_empty() {
366         // First line must fits with `shape.width`.
367         if first_line_width(snippet) > shape.width {
368             return false;
369         }
370         // If the snippet does not include newline, we are done.
371         if first_line_width(snippet) == snippet.len() {
372             return true;
373         }
374         // The other lines must fit within the maximum width.
375         if snippet.lines().skip(1).any(|line| line.len() > max_width) {
376             return false;
377         }
378         // A special check for the last line, since the caller may
379         // place trailing characters on this line.
380         if last_line_width(snippet) > shape.used_width() + shape.width {
381             return false;
382         }
383     }
384     true
385 }
386
387 #[inline]
388 pub fn colon_spaces(before: bool, after: bool) -> &'static str {
389     match (before, after) {
390         (true, true) => " : ",
391         (true, false) => " :",
392         (false, true) => ": ",
393         (false, false) => ":",
394     }
395 }
396
397 #[inline]
398 pub fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
399     match e.node {
400         ast::ExprKind::Call(ref e, _)
401         | ast::ExprKind::Binary(_, ref e, _)
402         | ast::ExprKind::Cast(ref e, _)
403         | ast::ExprKind::Type(ref e, _)
404         | ast::ExprKind::Assign(ref e, _)
405         | ast::ExprKind::AssignOp(_, ref e, _)
406         | ast::ExprKind::Field(ref e, _)
407         | ast::ExprKind::Index(ref e, _)
408         | ast::ExprKind::Range(Some(ref e), _, _)
409         | ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
410         _ => e,
411     }
412 }
413
414 #[inline]
415 pub fn starts_with_newline(s: &str) -> bool {
416     s.starts_with('\n') || s.starts_with("\r\n")
417 }
418
419 #[inline]
420 pub fn first_line_ends_with(s: &str, c: char) -> bool {
421     s.lines().next().map_or(false, |l| l.ends_with(c))
422 }
423
424 // States whether an expression's last line exclusively consists of closing
425 // parens, braces, and brackets in its idiomatic formatting.
426 pub fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
427     match expr.node {
428         ast::ExprKind::Mac(..)
429         | ast::ExprKind::Call(..)
430         | ast::ExprKind::MethodCall(..)
431         | ast::ExprKind::Array(..)
432         | ast::ExprKind::Struct(..)
433         | ast::ExprKind::While(..)
434         | ast::ExprKind::WhileLet(..)
435         | ast::ExprKind::If(..)
436         | ast::ExprKind::IfLet(..)
437         | ast::ExprKind::Block(..)
438         | ast::ExprKind::Loop(..)
439         | ast::ExprKind::ForLoop(..)
440         | ast::ExprKind::Match(..) => repr.contains('\n'),
441         ast::ExprKind::Paren(ref expr)
442         | ast::ExprKind::Binary(_, _, ref expr)
443         | ast::ExprKind::Index(_, ref expr)
444         | ast::ExprKind::Unary(_, ref expr)
445         | ast::ExprKind::Closure(_, _, _, _, ref expr, _)
446         | ast::ExprKind::Try(ref expr)
447         | ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr),
448         // This can only be a string lit
449         ast::ExprKind::Lit(_) => {
450             repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces()
451         }
452         _ => false,
453     }
454 }
455
456 /// Remove trailing spaces from the specified snippet. We do not remove spaces
457 /// inside strings or comments.
458 pub fn remove_trailing_white_spaces(text: &str) -> String {
459     let mut buffer = String::with_capacity(text.len());
460     let mut space_buffer = String::with_capacity(128);
461     for (char_kind, c) in CharClasses::new(text.chars()) {
462         match c {
463             '\n' => {
464                 if char_kind == FullCodeCharKind::InString {
465                     buffer.push_str(&space_buffer);
466                 }
467                 space_buffer.clear();
468                 buffer.push('\n');
469             }
470             _ if c.is_whitespace() => {
471                 space_buffer.push(c);
472             }
473             _ => {
474                 if !space_buffer.is_empty() {
475                     buffer.push_str(&space_buffer);
476                     space_buffer.clear();
477                 }
478                 buffer.push(c);
479             }
480         }
481     }
482     buffer
483 }
484
485 #[test]
486 fn test_remove_trailing_white_spaces() {
487     let s = "    r#\"\n        test\n    \"#";
488     assert_eq!(remove_trailing_white_spaces(&s), s);
489 }