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