5 use rustc_target::spec::abi;
7 self, Attribute, CrateSugar, MetaItem, MetaItemKind, NestedMetaItem, NestedMetaItemKind,
8 NodeId, Path, Visibility, VisibilityKind,
11 use syntax::source_map::{BytePos, Span, NO_EXPANSION};
13 use unicode_width::UnicodeWidthStr;
15 use crate::comment::{filter_normal_code, CharClasses, FullCodeCharKind, LineClasses};
16 use crate::config::{Config, Version};
17 use crate::rewrite::RewriteContext;
18 use crate::shape::{Indent, Shape};
20 pub(crate) const DEPR_SKIP_ANNOTATION: &str = "rustfmt_skip";
21 pub(crate) const SKIP_ANNOTATION: &str = "rustfmt::skip";
23 pub(crate) fn rewrite_ident<'a>(context: &'a RewriteContext<'_>, ident: ast::Ident) -> &'a str {
24 context.snippet(ident.span)
27 // Computes the length of a string's last line, minus offset.
28 pub(crate) fn extra_offset(text: &str, shape: Shape) -> usize {
29 match text.rfind('\n') {
30 // 1 for newline character
31 Some(idx) => text.len().saturating_sub(idx + 1 + shape.used_width()),
36 pub(crate) fn is_same_visibility(a: &Visibility, b: &Visibility) -> bool {
37 match (&a.node, &b.node) {
39 VisibilityKind::Restricted { path: p, .. },
40 VisibilityKind::Restricted { path: q, .. },
41 ) => p.to_string() == q.to_string(),
42 (VisibilityKind::Public, VisibilityKind::Public)
43 | (VisibilityKind::Inherited, VisibilityKind::Inherited)
45 VisibilityKind::Crate(CrateSugar::PubCrate),
46 VisibilityKind::Crate(CrateSugar::PubCrate),
49 VisibilityKind::Crate(CrateSugar::JustCrate),
50 VisibilityKind::Crate(CrateSugar::JustCrate),
56 // Uses Cow to avoid allocating in the common cases.
57 pub(crate) fn format_visibility(
58 context: &RewriteContext<'_>,
60 ) -> Cow<'static, str> {
62 VisibilityKind::Public => Cow::from("pub "),
63 VisibilityKind::Inherited => Cow::from(""),
64 VisibilityKind::Crate(CrateSugar::PubCrate) => Cow::from("pub(crate) "),
65 VisibilityKind::Crate(CrateSugar::JustCrate) => Cow::from("crate "),
66 VisibilityKind::Restricted { ref path, .. } => {
67 let Path { ref segments, .. } = **path;
68 let mut segments_iter = segments.iter().map(|seg| rewrite_ident(context, seg.ident));
72 .expect("Non-global path in pub(restricted)?");
74 let is_keyword = |s: &str| s == "self" || s == "super";
75 let path = segments_iter.collect::<Vec<_>>().join("::");
76 let in_str = if is_keyword(&path) { "" } else { "in " };
78 Cow::from(format!("pub({}{}) ", in_str, path))
84 pub(crate) fn format_async(is_async: ast::IsAsync) -> &'static str {
86 ast::IsAsync::Async { .. } => "async ",
87 ast::IsAsync::NotAsync => "",
92 pub(crate) fn format_constness(constness: ast::Constness) -> &'static str {
94 ast::Constness::Const => "const ",
95 ast::Constness::NotConst => "",
100 pub(crate) fn format_defaultness(defaultness: ast::Defaultness) -> &'static str {
102 ast::Defaultness::Default => "default ",
103 ast::Defaultness::Final => "",
108 pub(crate) fn format_unsafety(unsafety: ast::Unsafety) -> &'static str {
110 ast::Unsafety::Unsafe => "unsafe ",
111 ast::Unsafety::Normal => "",
116 pub(crate) fn format_auto(is_auto: ast::IsAuto) -> &'static str {
118 ast::IsAuto::Yes => "auto ",
119 ast::IsAuto::No => "",
124 pub(crate) fn format_mutability(mutability: ast::Mutability) -> &'static str {
126 ast::Mutability::Mutable => "mut ",
127 ast::Mutability::Immutable => "",
132 pub(crate) fn format_abi(abi: abi::Abi, explicit_abi: bool, is_mod: bool) -> Cow<'static, str> {
133 if abi == abi::Abi::Rust && !is_mod {
135 } else if abi == abi::Abi::C && !explicit_abi {
138 Cow::from(format!("extern {} ", abi))
143 // Transform `Vec<syntax::ptr::P<T>>` into `Vec<&T>`
144 pub(crate) fn ptr_vec_to_ref_vec<T>(vec: &[ptr::P<T>]) -> Vec<&T> {
145 vec.iter().map(|x| &**x).collect::<Vec<_>>()
149 pub(crate) fn filter_attributes(
150 attrs: &[ast::Attribute],
151 style: ast::AttrStyle,
152 ) -> Vec<ast::Attribute> {
155 .filter(|a| a.style == style)
161 pub(crate) fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
162 filter_attributes(attrs, ast::AttrStyle::Inner)
166 pub(crate) fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
167 filter_attributes(attrs, ast::AttrStyle::Outer)
171 pub(crate) fn is_single_line(s: &str) -> bool {
172 s.chars().find(|&c| c == '\n').is_none()
176 pub(crate) fn first_line_contains_single_line_comment(s: &str) -> bool {
177 s.lines().next().map_or(false, |l| l.contains("//"))
181 pub(crate) fn last_line_contains_single_line_comment(s: &str) -> bool {
182 s.lines().last().map_or(false, |l| l.contains("//"))
186 pub(crate) fn is_attributes_extendable(attrs_str: &str) -> bool {
187 !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
190 // The width of the first line in s.
192 pub(crate) fn first_line_width(s: &str) -> usize {
193 unicode_str_width(s.splitn(2, '\n').next().unwrap_or(""))
196 // The width of the last line in s.
198 pub(crate) fn last_line_width(s: &str) -> usize {
199 unicode_str_width(s.rsplitn(2, '\n').next().unwrap_or(""))
202 // The total used width of the last line.
204 pub(crate) fn last_line_used_width(s: &str, offset: usize) -> usize {
205 if s.contains('\n') {
208 offset + unicode_str_width(s)
213 pub(crate) fn trimmed_last_line_width(s: &str) -> usize {
214 unicode_str_width(match s.rfind('\n') {
215 Some(n) => s[(n + 1)..].trim(),
221 pub(crate) fn last_line_extendable(s: &str) -> bool {
222 if s.ends_with("\"#") {
225 for c in s.chars().rev() {
227 '(' | ')' | ']' | '}' | '?' | '>' => continue,
229 _ if c.is_whitespace() => continue,
237 fn is_skip(meta_item: &MetaItem) -> bool {
238 match meta_item.node {
239 MetaItemKind::Word => {
240 let path_str = meta_item.ident.to_string();
241 path_str == SKIP_ANNOTATION || path_str == DEPR_SKIP_ANNOTATION
243 MetaItemKind::List(ref l) => {
244 meta_item.name() == "cfg_attr" && l.len() == 2 && is_skip_nested(&l[1])
251 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
252 match meta_item.node {
253 NestedMetaItemKind::MetaItem(ref mi) => is_skip(mi),
254 NestedMetaItemKind::Literal(_) => false,
259 pub(crate) fn contains_skip(attrs: &[Attribute]) -> bool {
262 .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
266 pub(crate) fn semicolon_for_expr(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
268 ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
269 context.config.trailing_semicolon()
276 pub(crate) fn semicolon_for_stmt(context: &RewriteContext<'_>, stmt: &ast::Stmt) -> bool {
278 ast::StmtKind::Semi(ref expr) => match expr.node {
279 ast::ExprKind::While(..)
280 | ast::ExprKind::WhileLet(..)
281 | ast::ExprKind::Loop(..)
282 | ast::ExprKind::ForLoop(..) => false,
283 ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
284 context.config.trailing_semicolon()
288 ast::StmtKind::Expr(..) => false,
294 pub(crate) fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
296 ast::StmtKind::Expr(ref expr) => Some(expr),
302 pub(crate) fn count_newlines(input: &str) -> usize {
303 // Using bytes to omit UTF-8 decoding
304 bytecount::count(input.as_bytes(), b'\n')
307 // For format_missing and last_pos, need to use the source callsite (if applicable).
308 // Required as generated code spans aren't guaranteed to follow on from the last span.
309 macro_rules! source {
310 ($this:ident, $sp:expr) => {
311 $sp.source_callsite()
315 pub(crate) fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
316 Span::new(lo, hi, NO_EXPANSION)
319 // Returns `true` if the given span does not intersect with file lines.
320 macro_rules! out_of_file_lines_range {
321 ($self:ident, $span:expr) => {
322 !$self.config.file_lines().is_all()
326 .intersects(&$self.source_map.lookup_line_range($span))
330 macro_rules! skip_out_of_file_lines_range {
331 ($self:ident, $span:expr) => {
332 if out_of_file_lines_range!($self, $span) {
338 macro_rules! skip_out_of_file_lines_range_visitor {
339 ($self:ident, $span:expr) => {
340 if out_of_file_lines_range!($self, $span) {
341 $self.push_rewrite($span, None);
347 // Wraps String in an Option. Returns Some when the string adheres to the
348 // Rewrite constraints defined for the Rewrite trait and None otherwise.
349 pub(crate) fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
350 if is_valid_str(&filter_normal_code(&s), max_width, shape) {
357 fn is_valid_str(snippet: &str, max_width: usize, shape: Shape) -> bool {
358 if !snippet.is_empty() {
359 // First line must fits with `shape.width`.
360 if first_line_width(snippet) > shape.width {
363 // If the snippet does not include newline, we are done.
364 if is_single_line(snippet) {
367 // The other lines must fit within the maximum width.
371 .any(|line| unicode_str_width(line) > max_width)
375 // A special check for the last line, since the caller may
376 // place trailing characters on this line.
377 if last_line_width(snippet) > shape.used_width() + shape.width {
385 pub(crate) fn colon_spaces(config: &Config) -> &'static str {
386 let before = config.space_before_colon();
387 let after = config.space_after_colon();
388 match (before, after) {
389 (true, true) => " : ",
390 (true, false) => " :",
391 (false, true) => ": ",
392 (false, false) => ":",
397 pub(crate) fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
399 ast::ExprKind::Call(ref e, _)
400 | ast::ExprKind::Binary(_, ref e, _)
401 | ast::ExprKind::Cast(ref e, _)
402 | ast::ExprKind::Type(ref e, _)
403 | ast::ExprKind::Assign(ref e, _)
404 | ast::ExprKind::AssignOp(_, ref e, _)
405 | ast::ExprKind::Field(ref e, _)
406 | ast::ExprKind::Index(ref e, _)
407 | ast::ExprKind::Range(Some(ref e), _, _)
408 | ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
414 pub(crate) fn starts_with_newline(s: &str) -> bool {
415 s.starts_with('\n') || s.starts_with("\r\n")
419 pub(crate) fn first_line_ends_with(s: &str, c: char) -> bool {
420 s.lines().next().map_or(false, |l| l.ends_with(c))
423 // States whether an expression's last line exclusively consists of closing
424 // parens, braces, and brackets in its idiomatic formatting.
425 pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr: &str) -> bool {
427 ast::ExprKind::Mac(..)
428 | ast::ExprKind::Call(..)
429 | ast::ExprKind::MethodCall(..)
430 | ast::ExprKind::Array(..)
431 | ast::ExprKind::Struct(..)
432 | ast::ExprKind::While(..)
433 | ast::ExprKind::WhileLet(..)
434 | ast::ExprKind::If(..)
435 | ast::ExprKind::IfLet(..)
436 | ast::ExprKind::Block(..)
437 | ast::ExprKind::Loop(..)
438 | ast::ExprKind::ForLoop(..)
439 | ast::ExprKind::Match(..) => repr.contains('\n'),
440 ast::ExprKind::Paren(ref expr)
441 | ast::ExprKind::Binary(_, _, ref expr)
442 | ast::ExprKind::Index(_, ref expr)
443 | ast::ExprKind::Unary(_, ref expr)
444 | ast::ExprKind::Closure(_, _, _, _, ref expr, _)
445 | ast::ExprKind::Try(ref expr)
446 | ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr),
447 // This can only be a string lit
448 ast::ExprKind::Lit(_) => {
449 repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces()
455 /// Removes trailing spaces from the specified snippet. We do not remove spaces
456 /// inside strings or comments.
457 pub(crate) fn remove_trailing_white_spaces(text: &str) -> String {
458 let mut buffer = String::with_capacity(text.len());
459 let mut space_buffer = String::with_capacity(128);
460 for (char_kind, c) in CharClasses::new(text.chars()) {
463 if char_kind == FullCodeCharKind::InString {
464 buffer.push_str(&space_buffer);
466 space_buffer.clear();
469 _ if c.is_whitespace() => {
470 space_buffer.push(c);
473 if !space_buffer.is_empty() {
474 buffer.push_str(&space_buffer);
475 space_buffer.clear();
484 /// Indent each line according to the specified `indent`.
512 pub(crate) fn trim_left_preserve_layout(
516 ) -> Option<String> {
517 let mut lines = LineClasses::new(orig);
518 let first_line = lines.next().map(|(_, s)| s.trim_end().to_owned())?;
519 let mut trimmed_lines = Vec::with_capacity(16);
521 let mut veto_trim = false;
522 let min_prefix_space_width = lines
523 .filter_map(|(kind, line)| {
524 let mut trimmed = true;
525 let prefix_space_width = if is_empty_line(&line) {
528 Some(get_prefix_space_width(config, &line))
531 // just InString{Commented} in order to allow the start of a string to be indented
532 let new_veto_trim_value = (kind == FullCodeCharKind::InString
533 || (config.version() == Version::Two
534 && kind == FullCodeCharKind::InStringCommented))
535 && !line.ends_with('\\');
536 let line = if veto_trim || new_veto_trim_value {
537 veto_trim = new_veto_trim_value;
541 line.trim().to_owned()
543 trimmed_lines.push((trimmed, line, prefix_space_width));
545 // Because there is a veto against trimming and indenting lines within a string,
546 // such lines should not be taken into account when computing the minimum.
548 FullCodeCharKind::InStringCommented | FullCodeCharKind::EndStringCommented
549 if config.version() == Version::Two =>
553 FullCodeCharKind::InString | FullCodeCharKind::EndString => None,
554 _ => prefix_space_width,
565 |&(trimmed, ref line, prefix_space_width)| match prefix_space_width {
566 _ if !trimmed => line.to_owned(),
567 Some(original_indent_width) => {
568 let new_indent_width = indent.width()
569 + original_indent_width.saturating_sub(min_prefix_space_width);
570 let new_indent = Indent::from_width(config, new_indent_width);
571 format!("{}{}", new_indent.to_string(config), line)
573 None => String::new(),
581 /// Based on the given line, determine if the next line can be indented or not.
582 /// This allows to preserve the indentation of multi-line literals.
583 pub(crate) fn indent_next_line(kind: FullCodeCharKind, line: &str, config: &Config) -> bool {
584 !(kind.is_string() || (config.version() == Version::Two && kind.is_commented_string()))
585 || line.ends_with('\\')
588 pub(crate) fn is_empty_line(s: &str) -> bool {
589 s.is_empty() || s.chars().all(char::is_whitespace)
592 fn get_prefix_space_width(config: &Config, s: &str) -> usize {
597 '\t' => width += config.tab_spaces(),
604 pub(crate) trait NodeIdExt {
608 impl NodeIdExt for NodeId {
609 fn root() -> NodeId {
610 NodeId::placeholder_from_mark(Mark::root())
614 pub(crate) fn unicode_str_width(s: &str) -> usize {
618 pub(crate) fn get_skip_macro_names(attrs: &[ast::Attribute]) -> Vec<String> {
619 let mut skip_macro_names = vec![];
621 // syntax::ast::Path is implemented partialEq
622 // but it is designed for segments.len() == 1
623 if format!("{}", attr.path) != "rustfmt::skip::macros" {
627 if let Some(list) = attr.meta_item_list() {
628 for spanned in list {
629 if let Some(name) = spanned.name() {
630 skip_macro_names.push(name.to_string());
643 fn test_remove_trailing_white_spaces() {
644 let s = " r#\"\n test\n \"#";
645 assert_eq!(remove_trailing_white_spaces(&s), s);
649 fn test_trim_left_preserve_layout() {
650 let s = "aaa\n\tbbb\n ccc";
651 let config = Config::default();
652 let indent = Indent::new(4, 0);
654 trim_left_preserve_layout(&s, indent, &config),
655 Some("aaa\n bbb\n ccc".to_string())