]> git.lizzy.rs Git - rust.git/blob - src/utils.rs
Update rustc-ap-* crates to 541.0.0 (#3707)
[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::ExpnId;
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(..) | ast::ExprKind::Loop(..) | ast::ExprKind::ForLoop(..) => {
288                 false
289             }
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(crate) 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 /// Returns the number of LF and CRLF respectively.
309 pub(crate) fn count_lf_crlf(input: &str) -> (usize, usize) {
310     let mut lf = 0;
311     let mut crlf = 0;
312     let mut is_crlf = false;
313     for c in input.as_bytes() {
314         match c {
315             b'\r' => is_crlf = true,
316             b'\n' if is_crlf => crlf += 1,
317             b'\n' => lf += 1,
318             _ => is_crlf = false,
319         }
320     }
321     (lf, crlf)
322 }
323
324 pub(crate) fn count_newlines(input: &str) -> usize {
325     // Using bytes to omit UTF-8 decoding
326     bytecount::count(input.as_bytes(), b'\n')
327 }
328
329 // For format_missing and last_pos, need to use the source callsite (if applicable).
330 // Required as generated code spans aren't guaranteed to follow on from the last span.
331 macro_rules! source {
332     ($this:ident, $sp:expr) => {
333         $sp.source_callsite()
334     };
335 }
336
337 pub(crate) fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
338     Span::new(lo, hi, NO_EXPANSION)
339 }
340
341 // Returns `true` if the given span does not intersect with file lines.
342 macro_rules! out_of_file_lines_range {
343     ($self:ident, $span:expr) => {
344         !$self.config.file_lines().is_all()
345             && !$self
346                 .config
347                 .file_lines()
348                 .intersects(&$self.source_map.lookup_line_range($span))
349     };
350 }
351
352 macro_rules! skip_out_of_file_lines_range {
353     ($self:ident, $span:expr) => {
354         if out_of_file_lines_range!($self, $span) {
355             return None;
356         }
357     };
358 }
359
360 macro_rules! skip_out_of_file_lines_range_visitor {
361     ($self:ident, $span:expr) => {
362         if out_of_file_lines_range!($self, $span) {
363             $self.push_rewrite($span, None);
364             return;
365         }
366     };
367 }
368
369 // Wraps String in an Option. Returns Some when the string adheres to the
370 // Rewrite constraints defined for the Rewrite trait and None otherwise.
371 pub(crate) fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
372     if is_valid_str(&filter_normal_code(&s), max_width, shape) {
373         Some(s)
374     } else {
375         None
376     }
377 }
378
379 fn is_valid_str(snippet: &str, max_width: usize, shape: Shape) -> bool {
380     if !snippet.is_empty() {
381         // First line must fits with `shape.width`.
382         if first_line_width(snippet) > shape.width {
383             return false;
384         }
385         // If the snippet does not include newline, we are done.
386         if is_single_line(snippet) {
387             return true;
388         }
389         // The other lines must fit within the maximum width.
390         if snippet
391             .lines()
392             .skip(1)
393             .any(|line| unicode_str_width(line) > max_width)
394         {
395             return false;
396         }
397         // A special check for the last line, since the caller may
398         // place trailing characters on this line.
399         if last_line_width(snippet) > shape.used_width() + shape.width {
400             return false;
401         }
402     }
403     true
404 }
405
406 #[inline]
407 pub(crate) fn colon_spaces(config: &Config) -> &'static str {
408     let before = config.space_before_colon();
409     let after = config.space_after_colon();
410     match (before, after) {
411         (true, true) => " : ",
412         (true, false) => " :",
413         (false, true) => ": ",
414         (false, false) => ":",
415     }
416 }
417
418 #[inline]
419 pub(crate) fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
420     match e.node {
421         ast::ExprKind::Call(ref e, _)
422         | ast::ExprKind::Binary(_, ref e, _)
423         | ast::ExprKind::Cast(ref e, _)
424         | ast::ExprKind::Type(ref e, _)
425         | ast::ExprKind::Assign(ref e, _)
426         | ast::ExprKind::AssignOp(_, ref e, _)
427         | ast::ExprKind::Field(ref e, _)
428         | ast::ExprKind::Index(ref e, _)
429         | ast::ExprKind::Range(Some(ref e), _, _)
430         | ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
431         _ => e,
432     }
433 }
434
435 #[inline]
436 pub(crate) fn starts_with_newline(s: &str) -> bool {
437     s.starts_with('\n') || s.starts_with("\r\n")
438 }
439
440 #[inline]
441 pub(crate) fn first_line_ends_with(s: &str, c: char) -> bool {
442     s.lines().next().map_or(false, |l| l.ends_with(c))
443 }
444
445 // States whether an expression's last line exclusively consists of closing
446 // parens, braces, and brackets in its idiomatic formatting.
447 pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr: &str) -> bool {
448     match expr.node {
449         ast::ExprKind::Mac(..)
450         | ast::ExprKind::Call(..)
451         | ast::ExprKind::MethodCall(..)
452         | ast::ExprKind::Array(..)
453         | ast::ExprKind::Struct(..)
454         | ast::ExprKind::While(..)
455         | ast::ExprKind::If(..)
456         | ast::ExprKind::Block(..)
457         | ast::ExprKind::Loop(..)
458         | ast::ExprKind::ForLoop(..)
459         | ast::ExprKind::Match(..) => repr.contains('\n'),
460         ast::ExprKind::Paren(ref expr)
461         | ast::ExprKind::Binary(_, _, ref expr)
462         | ast::ExprKind::Index(_, ref expr)
463         | ast::ExprKind::Unary(_, ref expr)
464         | ast::ExprKind::Closure(_, _, _, _, ref expr, _)
465         | ast::ExprKind::Try(ref expr)
466         | ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr),
467         // This can only be a string lit
468         ast::ExprKind::Lit(_) => {
469             repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces()
470         }
471         _ => false,
472     }
473 }
474
475 /// Removes trailing spaces from the specified snippet. We do not remove spaces
476 /// inside strings or comments.
477 pub(crate) fn remove_trailing_white_spaces(text: &str) -> String {
478     let mut buffer = String::with_capacity(text.len());
479     let mut space_buffer = String::with_capacity(128);
480     for (char_kind, c) in CharClasses::new(text.chars()) {
481         match c {
482             '\n' => {
483                 if char_kind == FullCodeCharKind::InString {
484                     buffer.push_str(&space_buffer);
485                 }
486                 space_buffer.clear();
487                 buffer.push('\n');
488             }
489             _ if c.is_whitespace() => {
490                 space_buffer.push(c);
491             }
492             _ => {
493                 if !space_buffer.is_empty() {
494                     buffer.push_str(&space_buffer);
495                     space_buffer.clear();
496                 }
497                 buffer.push(c);
498             }
499         }
500     }
501     buffer
502 }
503
504 /// Indent each line according to the specified `indent`.
505 /// e.g.
506 ///
507 /// ```rust,compile_fail
508 /// foo!{
509 /// x,
510 /// y,
511 /// foo(
512 ///     a,
513 ///     b,
514 ///     c,
515 /// ),
516 /// }
517 /// ```
518 ///
519 /// will become
520 ///
521 /// ```rust,compile_fail
522 /// foo!{
523 ///     x,
524 ///     y,
525 ///     foo(
526 ///         a,
527 ///         b,
528 ///         c,
529 ///     ),
530 /// }
531 /// ```
532 pub(crate) fn trim_left_preserve_layout(
533     orig: &str,
534     indent: Indent,
535     config: &Config,
536 ) -> Option<String> {
537     let mut lines = LineClasses::new(orig);
538     let first_line = lines.next().map(|(_, s)| s.trim_end().to_owned())?;
539     let mut trimmed_lines = Vec::with_capacity(16);
540
541     let mut veto_trim = false;
542     let min_prefix_space_width = lines
543         .filter_map(|(kind, line)| {
544             let mut trimmed = true;
545             let prefix_space_width = if is_empty_line(&line) {
546                 None
547             } else {
548                 Some(get_prefix_space_width(config, &line))
549             };
550
551             // just InString{Commented} in order to allow the start of a string to be indented
552             let new_veto_trim_value = (kind == FullCodeCharKind::InString
553                 || (config.version() == Version::Two
554                     && kind == FullCodeCharKind::InStringCommented))
555                 && !line.ends_with('\\');
556             let line = if veto_trim || new_veto_trim_value {
557                 veto_trim = new_veto_trim_value;
558                 trimmed = false;
559                 line
560             } else {
561                 line.trim().to_owned()
562             };
563             trimmed_lines.push((trimmed, line, prefix_space_width));
564
565             // Because there is a veto against trimming and indenting lines within a string,
566             // such lines should not be taken into account when computing the minimum.
567             match kind {
568                 FullCodeCharKind::InStringCommented | FullCodeCharKind::EndStringCommented
569                     if config.version() == Version::Two =>
570                 {
571                     None
572                 }
573                 FullCodeCharKind::InString | FullCodeCharKind::EndString => None,
574                 _ => prefix_space_width,
575             }
576         })
577         .min()?;
578
579     Some(
580         first_line
581             + "\n"
582             + &trimmed_lines
583                 .iter()
584                 .map(
585                     |&(trimmed, ref line, prefix_space_width)| match prefix_space_width {
586                         _ if !trimmed => line.to_owned(),
587                         Some(original_indent_width) => {
588                             let new_indent_width = indent.width()
589                                 + original_indent_width.saturating_sub(min_prefix_space_width);
590                             let new_indent = Indent::from_width(config, new_indent_width);
591                             format!("{}{}", new_indent.to_string(config), line)
592                         }
593                         None => String::new(),
594                     },
595                 )
596                 .collect::<Vec<_>>()
597                 .join("\n"),
598     )
599 }
600
601 /// Based on the given line, determine if the next line can be indented or not.
602 /// This allows to preserve the indentation of multi-line literals.
603 pub(crate) fn indent_next_line(kind: FullCodeCharKind, line: &str, config: &Config) -> bool {
604     !(kind.is_string() || (config.version() == Version::Two && kind.is_commented_string()))
605         || line.ends_with('\\')
606 }
607
608 pub(crate) fn is_empty_line(s: &str) -> bool {
609     s.is_empty() || s.chars().all(char::is_whitespace)
610 }
611
612 fn get_prefix_space_width(config: &Config, s: &str) -> usize {
613     let mut width = 0;
614     for c in s.chars() {
615         match c {
616             ' ' => width += 1,
617             '\t' => width += config.tab_spaces(),
618             _ => return width,
619         }
620     }
621     width
622 }
623
624 pub(crate) trait NodeIdExt {
625     fn root() -> Self;
626 }
627
628 impl NodeIdExt for NodeId {
629     fn root() -> NodeId {
630         NodeId::placeholder_from_expn_id(ExpnId::root())
631     }
632 }
633
634 pub(crate) fn unicode_str_width(s: &str) -> usize {
635     s.width()
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 }