4 self, Attribute, CrateSugar, MetaItem, MetaItemKind, NestedMetaItem, NodeId, Path, Visibility,
8 use rustc_ast_pretty::pprust;
9 use rustc_span::{sym, BytePos, ExpnId, Span, Symbol, SyntaxContext};
10 use rustc_target::spec::abi;
11 use unicode_width::UnicodeWidthStr;
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};
19 pub(crate) fn depr_skip_annotation() -> Symbol {
20 Symbol::intern("rustfmt_skip")
24 pub(crate) fn skip_annotation() -> Symbol {
25 Symbol::intern("rustfmt::skip")
28 pub(crate) fn rewrite_ident<'a>(context: &'a RewriteContext<'_>, ident: ast::Ident) -> &'a str {
29 context.snippet(ident.span)
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()),
41 pub(crate) fn is_same_visibility(a: &Visibility, b: &Visibility) -> bool {
42 match (&a.node, &b.node) {
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)
50 VisibilityKind::Crate(CrateSugar::PubCrate),
51 VisibilityKind::Crate(CrateSugar::PubCrate),
54 VisibilityKind::Crate(CrateSugar::JustCrate),
55 VisibilityKind::Crate(CrateSugar::JustCrate),
61 // Uses Cow to avoid allocating in the common cases.
62 pub(crate) fn format_visibility(
63 context: &RewriteContext<'_>,
65 ) -> Cow<'static, str> {
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));
77 .expect("Non-global path in pub(restricted)?");
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 " };
83 Cow::from(format!("pub({}{}) ", in_str, path))
89 pub(crate) fn format_async(is_async: &ast::Async) -> &'static str {
91 ast::Async::Yes { .. } => "async ",
97 pub(crate) fn format_constness(constness: ast::Const) -> &'static str {
99 ast::Const::Yes(..) => "const ",
100 ast::Const::No => "",
105 pub(crate) fn format_defaultness(defaultness: ast::Defaultness) -> &'static str {
107 ast::Defaultness::Default(..) => "default ",
108 ast::Defaultness::Final => "",
113 pub(crate) fn format_unsafety(unsafety: ast::Unsafe) -> &'static str {
115 ast::Unsafe::Yes(..) => "unsafe ",
116 ast::Unsafe::No => "",
121 pub(crate) fn format_auto(is_auto: ast::IsAuto) -> &'static str {
123 ast::IsAuto::Yes => "auto ",
124 ast::IsAuto::No => "",
129 pub(crate) fn format_mutability(mutability: ast::Mutability) -> &'static str {
131 ast::Mutability::Mut => "mut ",
132 ast::Mutability::Not => "",
137 pub(crate) fn format_extern(
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)
150 if abi == abi::Abi::Rust && !is_mod {
152 } else if abi == abi::Abi::C && !explicit_abi {
155 Cow::from(format!("extern {} ", abi))
160 // Transform `Vec<rustc_ast::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<_>>()
166 pub(crate) fn filter_attributes(
167 attrs: &[ast::Attribute],
168 style: ast::AttrStyle,
169 ) -> Vec<ast::Attribute> {
172 .filter(|a| a.style == style)
178 pub(crate) fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
179 filter_attributes(attrs, ast::AttrStyle::Inner)
183 pub(crate) fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
184 filter_attributes(attrs, ast::AttrStyle::Outer)
188 pub(crate) fn is_single_line(s: &str) -> bool {
189 s.chars().find(|&c| c == '\n').is_none()
193 pub(crate) fn first_line_contains_single_line_comment(s: &str) -> bool {
194 s.lines().next().map_or(false, |l| l.contains("//"))
198 pub(crate) fn last_line_contains_single_line_comment(s: &str) -> bool {
199 s.lines().last().map_or(false, |l| l.contains("//"))
203 pub(crate) fn is_attributes_extendable(attrs_str: &str) -> bool {
204 !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
207 /// The width of the first line in s.
209 pub(crate) fn first_line_width(s: &str) -> usize {
210 unicode_str_width(s.splitn(2, '\n').next().unwrap_or(""))
213 /// The width of the last line in s.
215 pub(crate) fn last_line_width(s: &str) -> usize {
216 unicode_str_width(s.rsplitn(2, '\n').next().unwrap_or(""))
219 /// The total used width of the last line.
221 pub(crate) fn last_line_used_width(s: &str, offset: usize) -> usize {
222 if s.contains('\n') {
225 offset + unicode_str_width(s)
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(),
238 pub(crate) fn last_line_extendable(s: &str) -> bool {
239 if s.ends_with("\"#") {
242 for c in s.chars().rev() {
244 '(' | ')' | ']' | '}' | '?' | '>' => continue,
246 _ if c.is_whitespace() => continue,
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()
261 MetaItemKind::List(ref l) => {
262 meta_item.check_name(sym::cfg_attr) && l.len() == 2 && is_skip_nested(&l[1])
269 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
271 NestedMetaItem::MetaItem(ref mi) => is_skip(mi),
272 NestedMetaItem::Literal(_) => false,
277 pub(crate) fn contains_skip(attrs: &[Attribute]) -> bool {
280 .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
284 pub(crate) fn semicolon_for_expr(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
286 ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
287 context.config.trailing_semicolon()
294 pub(crate) fn semicolon_for_stmt(context: &RewriteContext<'_>, stmt: &ast::Stmt) -> bool {
296 ast::StmtKind::Semi(ref expr) => match expr.kind {
297 ast::ExprKind::While(..) | ast::ExprKind::Loop(..) | ast::ExprKind::ForLoop(..) => {
300 ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
301 context.config.trailing_semicolon()
305 ast::StmtKind::Expr(..) => false,
311 pub(crate) fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
313 ast::StmtKind::Expr(ref expr) => Some(expr),
318 /// Returns the number of LF and CRLF respectively.
319 pub(crate) fn count_lf_crlf(input: &str) -> (usize, usize) {
322 let mut is_crlf = false;
323 for c in input.as_bytes() {
325 b'\r' => is_crlf = true,
326 b'\n' if is_crlf => crlf += 1,
328 _ => is_crlf = false,
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')
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()
347 pub(crate) fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
348 Span::new(lo, hi, SyntaxContext::root())
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()
358 .intersects(&$self.parse_sess.lookup_line_range($span))
362 macro_rules! skip_out_of_file_lines_range {
363 ($self:ident, $span:expr) => {
364 if out_of_file_lines_range!($self, $span) {
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);
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) {
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 {
395 // If the snippet does not include newline, we are done.
396 if is_single_line(snippet) {
399 // The other lines must fit within the maximum width.
403 .any(|line| unicode_str_width(line) > max_width)
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 {
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) => ":",
429 pub(crate) fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
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),
446 pub(crate) fn starts_with_newline(s: &str) -> bool {
447 s.starts_with('\n') || s.starts_with("\r\n")
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))
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 {
459 ast::ExprKind::MacCall(..)
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()
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(..)
492 | ast::ExprKind::Field(..)
493 | ast::ExprKind::LlvmInlineAsm(..)
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,
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()) {
513 if char_kind == FullCodeCharKind::InString {
514 buffer.push_str(&space_buffer);
516 space_buffer.clear();
519 _ if c.is_whitespace() => {
520 space_buffer.push(c);
523 if !space_buffer.is_empty() {
524 buffer.push_str(&space_buffer);
525 space_buffer.clear();
534 /// Indent each line according to the specified `indent`.
537 /// ```rust,compile_fail
551 /// ```rust,compile_fail
562 pub(crate) fn trim_left_preserve_layout(
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);
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) {
578 Some(get_prefix_space_width(config, &line))
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;
591 line.trim().to_owned()
593 trimmed_lines.push((trimmed, line, prefix_space_width));
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.
598 FullCodeCharKind::InStringCommented | FullCodeCharKind::EndStringCommented
599 if config.version() == Version::Two =>
603 FullCodeCharKind::InString | FullCodeCharKind::EndString => None,
604 _ => prefix_space_width,
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)
623 None => String::new(),
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()))
637 pub(crate) fn is_empty_line(s: &str) -> bool {
638 s.is_empty() || s.chars().all(char::is_whitespace)
641 fn get_prefix_space_width(config: &Config, s: &str) -> usize {
646 '\t' => width += config.tab_spaces(),
653 pub(crate) trait NodeIdExt {
657 impl NodeIdExt for NodeId {
658 fn root() -> NodeId {
659 NodeId::placeholder_from_expn_id(ExpnId::root())
663 pub(crate) fn unicode_str_width(s: &str) -> usize {
672 fn test_remove_trailing_white_spaces() {
673 let s = " r#\"\n test\n \"#";
674 assert_eq!(remove_trailing_white_spaces(&s), s);
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);
683 trim_left_preserve_layout(&s, indent, &config),
684 Some("aaa\n bbb\n ccc".to_string())