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