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