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