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