3 use rustc_target::spec::abi;
5 self, Attribute, CrateSugar, MetaItem, MetaItemKind, NestedMetaItem, NodeId, Path, Visibility,
9 use syntax::source_map::{BytePos, Span, SyntaxContext};
10 use syntax::symbol::{sym, Symbol};
11 use syntax_pos::ExpnId;
12 use unicode_width::UnicodeWidthStr;
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};
20 pub(crate) fn depr_skip_annotation() -> Symbol {
21 Symbol::intern("rustfmt_skip")
25 pub(crate) fn skip_annotation() -> Symbol {
26 Symbol::intern("rustfmt::skip")
29 pub(crate) fn rewrite_ident<'a>(context: &'a RewriteContext<'_>, ident: ast::Ident) -> &'a str {
30 context.snippet(ident.span)
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()),
42 pub(crate) fn is_same_visibility(a: &Visibility, b: &Visibility) -> bool {
43 match (&a.node, &b.node) {
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)
51 VisibilityKind::Crate(CrateSugar::PubCrate),
52 VisibilityKind::Crate(CrateSugar::PubCrate),
55 VisibilityKind::Crate(CrateSugar::JustCrate),
56 VisibilityKind::Crate(CrateSugar::JustCrate),
62 // Uses Cow to avoid allocating in the common cases.
63 pub(crate) fn format_visibility(
64 context: &RewriteContext<'_>,
66 ) -> Cow<'static, str> {
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));
78 .expect("Non-global path in pub(restricted)?");
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 " };
84 Cow::from(format!("pub({}{}) ", in_str, path))
90 pub(crate) fn format_async(is_async: &ast::IsAsync) -> &'static str {
92 ast::IsAsync::Async { .. } => "async ",
93 ast::IsAsync::NotAsync => "",
98 pub(crate) fn format_constness(constness: ast::Constness) -> &'static str {
100 ast::Constness::Const => "const ",
101 ast::Constness::NotConst => "",
106 pub(crate) fn format_defaultness(defaultness: ast::Defaultness) -> &'static str {
108 ast::Defaultness::Default => "default ",
109 ast::Defaultness::Final => "",
114 pub(crate) fn format_unsafety(unsafety: ast::Unsafety) -> &'static str {
116 ast::Unsafety::Unsafe => "unsafe ",
117 ast::Unsafety::Normal => "",
122 pub(crate) fn format_auto(is_auto: ast::IsAuto) -> &'static str {
124 ast::IsAuto::Yes => "auto ",
125 ast::IsAuto::No => "",
130 pub(crate) fn format_mutability(mutability: ast::Mutability) -> &'static str {
132 ast::Mutability::Mutable => "mut ",
133 ast::Mutability::Immutable => "",
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 {
141 } else if abi == abi::Abi::C && !explicit_abi {
144 Cow::from(format!("extern {} ", abi))
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<_>>()
155 pub(crate) fn filter_attributes(
156 attrs: &[ast::Attribute],
157 style: ast::AttrStyle,
158 ) -> Vec<ast::Attribute> {
161 .filter(|a| a.style == style)
167 pub(crate) fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
168 filter_attributes(attrs, ast::AttrStyle::Inner)
172 pub(crate) fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
173 filter_attributes(attrs, ast::AttrStyle::Outer)
177 pub(crate) fn is_single_line(s: &str) -> bool {
178 s.chars().find(|&c| c == '\n').is_none()
182 pub(crate) fn first_line_contains_single_line_comment(s: &str) -> bool {
183 s.lines().next().map_or(false, |l| l.contains("//"))
187 pub(crate) fn last_line_contains_single_line_comment(s: &str) -> bool {
188 s.lines().last().map_or(false, |l| l.contains("//"))
192 pub(crate) fn is_attributes_extendable(attrs_str: &str) -> bool {
193 !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
196 /// The width of the first line in s.
198 pub(crate) fn first_line_width(s: &str) -> usize {
199 unicode_str_width(s.splitn(2, '\n').next().unwrap_or(""))
202 /// The width of the last line in s.
204 pub(crate) fn last_line_width(s: &str) -> usize {
205 unicode_str_width(s.rsplitn(2, '\n').next().unwrap_or(""))
208 /// The indent width of the last line in s.
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()
215 /// The total used width of the last line.
217 pub(crate) fn last_line_used_width(s: &str, offset: usize) -> usize {
218 if s.contains('\n') {
221 offset + unicode_str_width(s)
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(),
234 pub(crate) fn last_line_extendable(s: &str) -> bool {
235 if s.ends_with("\"#") {
238 for c in s.chars().rev() {
240 '(' | ')' | ']' | '}' | '?' | '>' => continue,
242 _ if c.is_whitespace() => continue,
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()
256 MetaItemKind::List(ref l) => {
257 meta_item.check_name(sym::cfg_attr) && l.len() == 2 && is_skip_nested(&l[1])
264 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
266 NestedMetaItem::MetaItem(ref mi) => is_skip(mi),
267 NestedMetaItem::Literal(_) => false,
272 pub(crate) fn contains_skip(attrs: &[Attribute]) -> bool {
275 .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
279 pub(crate) fn semicolon_for_expr(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
281 ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
282 context.config.trailing_semicolon()
289 pub(crate) fn semicolon_for_stmt(context: &RewriteContext<'_>, stmt: &ast::Stmt) -> bool {
291 ast::StmtKind::Semi(ref expr) => match expr.kind {
292 ast::ExprKind::While(..) | ast::ExprKind::Loop(..) | ast::ExprKind::ForLoop(..) => {
295 ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
296 context.config.trailing_semicolon()
300 ast::StmtKind::Expr(..) => false,
306 pub(crate) fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
308 ast::StmtKind::Expr(ref expr) => Some(expr),
313 /// Returns the number of LF and CRLF respectively.
314 pub(crate) fn count_lf_crlf(input: &str) -> (usize, usize) {
317 let mut is_crlf = false;
318 for c in input.as_bytes() {
320 b'\r' => is_crlf = true,
321 b'\n' if is_crlf => crlf += 1,
323 _ => is_crlf = false,
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')
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()
342 pub(crate) fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
343 Span::new(lo, hi, SyntaxContext::root())
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()
353 .intersects(&$self.source_map.lookup_line_range($span))
357 macro_rules! skip_out_of_file_lines_range {
358 ($self:ident, $span:expr) => {
359 if out_of_file_lines_range!($self, $span) {
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);
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) {
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 {
390 // If the snippet does not include newline, we are done.
391 if is_single_line(snippet) {
394 // The other lines must fit within the maximum width.
398 .any(|line| unicode_str_width(line) > max_width)
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 {
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) => ":",
424 pub(crate) fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
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),
441 pub(crate) fn starts_with_newline(s: &str) -> bool {
442 s.starts_with('\n') || s.starts_with("\r\n")
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))
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 {
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()
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(..)
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,
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()) {
508 if char_kind == FullCodeCharKind::InString {
509 buffer.push_str(&space_buffer);
511 space_buffer.clear();
514 _ if c.is_whitespace() => {
515 space_buffer.push(c);
518 if !space_buffer.is_empty() {
519 buffer.push_str(&space_buffer);
520 space_buffer.clear();
529 /// Indent each line according to the specified `indent`.
532 /// ```rust,compile_fail
546 /// ```rust,compile_fail
557 pub(crate) fn trim_left_preserve_layout(
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);
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) {
573 Some(get_prefix_space_width(config, &line))
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;
586 line.trim().to_owned()
588 trimmed_lines.push((trimmed, line, prefix_space_width));
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.
593 FullCodeCharKind::InStringCommented | FullCodeCharKind::EndStringCommented
594 if config.version() == Version::Two =>
598 FullCodeCharKind::InString | FullCodeCharKind::EndString => None,
599 _ => prefix_space_width,
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)
618 None => String::new(),
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('\\')
633 pub(crate) fn is_empty_line(s: &str) -> bool {
634 s.is_empty() || s.chars().all(char::is_whitespace)
637 fn get_prefix_space_width(config: &Config, s: &str) -> usize {
642 '\t' => width += config.tab_spaces(),
649 pub(crate) trait NodeIdExt {
653 impl NodeIdExt for NodeId {
654 fn root() -> NodeId {
655 NodeId::placeholder_from_expn_id(ExpnId::root())
659 pub(crate) fn unicode_str_width(s: &str) -> usize {
668 fn test_remove_trailing_white_spaces() {
669 let s = " r#\"\n test\n \"#";
670 assert_eq!(remove_trailing_white_spaces(&s), s);
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);
679 trim_left_preserve_layout(&s, indent, &config),
680 Some("aaa\n bbb\n ccc".to_string())