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