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 const DEPR_SKIP_ANNOTATION: &str = "rustfmt_skip";
21 pub const SKIP_ANNOTATION: &str = "rustfmt::skip";
23 pub 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 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 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 fn format_visibility(context: &RewriteContext<'_>, vis: &Visibility) -> Cow<'static, str> {
59 VisibilityKind::Public => Cow::from("pub "),
60 VisibilityKind::Inherited => Cow::from(""),
61 VisibilityKind::Crate(CrateSugar::PubCrate) => Cow::from("pub(crate) "),
62 VisibilityKind::Crate(CrateSugar::JustCrate) => Cow::from("crate "),
63 VisibilityKind::Restricted { ref path, .. } => {
64 let Path { ref segments, .. } = **path;
65 let mut segments_iter = segments.iter().map(|seg| rewrite_ident(context, seg.ident));
69 .expect("Non-global path in pub(restricted)?");
71 let is_keyword = |s: &str| s == "self" || s == "super";
72 let path = segments_iter.collect::<Vec<_>>().join("::");
73 let in_str = if is_keyword(&path) { "" } else { "in " };
75 Cow::from(format!("pub({}{}) ", in_str, path))
81 pub fn format_async(is_async: ast::IsAsync) -> &'static str {
83 ast::IsAsync::Async { .. } => "async ",
84 ast::IsAsync::NotAsync => "",
89 pub fn format_constness(constness: ast::Constness) -> &'static str {
91 ast::Constness::Const => "const ",
92 ast::Constness::NotConst => "",
97 pub fn format_defaultness(defaultness: ast::Defaultness) -> &'static str {
99 ast::Defaultness::Default => "default ",
100 ast::Defaultness::Final => "",
105 pub fn format_unsafety(unsafety: ast::Unsafety) -> &'static str {
107 ast::Unsafety::Unsafe => "unsafe ",
108 ast::Unsafety::Normal => "",
113 pub fn format_auto(is_auto: ast::IsAuto) -> &'static str {
115 ast::IsAuto::Yes => "auto ",
116 ast::IsAuto::No => "",
121 pub fn format_mutability(mutability: ast::Mutability) -> &'static str {
123 ast::Mutability::Mutable => "mut ",
124 ast::Mutability::Immutable => "",
129 pub fn format_abi(abi: abi::Abi, explicit_abi: bool, is_mod: bool) -> Cow<'static, str> {
130 if abi == abi::Abi::Rust && !is_mod {
132 } else if abi == abi::Abi::C && !explicit_abi {
135 Cow::from(format!("extern {} ", abi))
140 // Transform `Vec<syntax::ptr::P<T>>` into `Vec<&T>`
141 pub fn ptr_vec_to_ref_vec<T>(vec: &[ptr::P<T>]) -> Vec<&T> {
142 vec.iter().map(|x| &**x).collect::<Vec<_>>()
146 pub fn filter_attributes(attrs: &[ast::Attribute], style: ast::AttrStyle) -> Vec<ast::Attribute> {
149 .filter(|a| a.style == style)
155 pub fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
156 filter_attributes(attrs, ast::AttrStyle::Inner)
160 pub fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
161 filter_attributes(attrs, ast::AttrStyle::Outer)
165 pub fn is_single_line(s: &str) -> bool {
166 s.chars().find(|&c| c == '\n').is_none()
170 pub fn first_line_contains_single_line_comment(s: &str) -> bool {
171 s.lines().next().map_or(false, |l| l.contains("//"))
175 pub fn last_line_contains_single_line_comment(s: &str) -> bool {
176 s.lines().last().map_or(false, |l| l.contains("//"))
180 pub fn is_attributes_extendable(attrs_str: &str) -> bool {
181 !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
184 // The width of the first line in s.
186 pub fn first_line_width(s: &str) -> usize {
187 unicode_str_width(s.splitn(2, '\n').next().unwrap_or(""))
190 // The width of the last line in s.
192 pub fn last_line_width(s: &str) -> usize {
193 unicode_str_width(s.rsplitn(2, '\n').next().unwrap_or(""))
196 // The total used width of the last line.
198 pub fn last_line_used_width(s: &str, offset: usize) -> usize {
199 if s.contains('\n') {
202 offset + unicode_str_width(s)
207 pub fn trimmed_last_line_width(s: &str) -> usize {
208 unicode_str_width(match s.rfind('\n') {
209 Some(n) => s[(n + 1)..].trim(),
215 pub fn last_line_extendable(s: &str) -> bool {
216 if s.ends_with("\"#") {
219 for c in s.chars().rev() {
221 '(' | ')' | ']' | '}' | '?' | '>' => continue,
223 _ if c.is_whitespace() => continue,
231 fn is_skip(meta_item: &MetaItem) -> bool {
232 match meta_item.node {
233 MetaItemKind::Word => {
234 let path_str = meta_item.ident.to_string();
235 path_str == SKIP_ANNOTATION || path_str == DEPR_SKIP_ANNOTATION
237 MetaItemKind::List(ref l) => {
238 meta_item.name() == "cfg_attr" && l.len() == 2 && is_skip_nested(&l[1])
245 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
246 match meta_item.node {
247 NestedMetaItemKind::MetaItem(ref mi) => is_skip(mi),
248 NestedMetaItemKind::Literal(_) => false,
253 pub fn contains_skip(attrs: &[Attribute]) -> bool {
256 .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
260 pub fn semicolon_for_expr(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
262 ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
263 context.config.trailing_semicolon()
270 pub fn semicolon_for_stmt(context: &RewriteContext<'_>, stmt: &ast::Stmt) -> bool {
272 ast::StmtKind::Semi(ref expr) => match expr.node {
273 ast::ExprKind::While(..)
274 | ast::ExprKind::WhileLet(..)
275 | ast::ExprKind::Loop(..)
276 | ast::ExprKind::ForLoop(..) => false,
277 ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
278 context.config.trailing_semicolon()
282 ast::StmtKind::Expr(..) => false,
288 pub fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
290 ast::StmtKind::Expr(ref expr) => Some(expr),
296 pub fn count_newlines(input: &str) -> usize {
297 // Using bytes to omit UTF-8 decoding
298 bytecount::count(input.as_bytes(), b'\n')
301 // For format_missing and last_pos, need to use the source callsite (if applicable).
302 // Required as generated code spans aren't guaranteed to follow on from the last span.
303 macro_rules! source {
304 ($this:ident, $sp:expr) => {
305 $sp.source_callsite()
309 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
310 Span::new(lo, hi, NO_EXPANSION)
313 // Returns `true` if the given span does not intersect with file lines.
314 macro_rules! out_of_file_lines_range {
315 ($self:ident, $span:expr) => {
316 !$self.config.file_lines().is_all()
320 .intersects(&$self.source_map.lookup_line_range($span))
324 macro_rules! skip_out_of_file_lines_range {
325 ($self:ident, $span:expr) => {
326 if out_of_file_lines_range!($self, $span) {
332 macro_rules! skip_out_of_file_lines_range_visitor {
333 ($self:ident, $span:expr) => {
334 if out_of_file_lines_range!($self, $span) {
335 $self.push_rewrite($span, None);
341 // Wraps String in an Option. Returns Some when the string adheres to the
342 // Rewrite constraints defined for the Rewrite trait and None otherwise.
343 pub fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
344 if is_valid_str(&filter_normal_code(&s), max_width, shape) {
351 fn is_valid_str(snippet: &str, max_width: usize, shape: Shape) -> bool {
352 if !snippet.is_empty() {
353 // First line must fits with `shape.width`.
354 if first_line_width(snippet) > shape.width {
357 // If the snippet does not include newline, we are done.
358 if is_single_line(snippet) {
361 // The other lines must fit within the maximum width.
365 .any(|line| unicode_str_width(line) > max_width)
369 // A special check for the last line, since the caller may
370 // place trailing characters on this line.
371 if last_line_width(snippet) > shape.used_width() + shape.width {
379 pub fn colon_spaces(before: bool, after: bool) -> &'static str {
380 match (before, after) {
381 (true, true) => " : ",
382 (true, false) => " :",
383 (false, true) => ": ",
384 (false, false) => ":",
389 pub fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
391 ast::ExprKind::Call(ref e, _)
392 | ast::ExprKind::Binary(_, ref e, _)
393 | ast::ExprKind::Cast(ref e, _)
394 | ast::ExprKind::Type(ref e, _)
395 | ast::ExprKind::Assign(ref e, _)
396 | ast::ExprKind::AssignOp(_, ref e, _)
397 | ast::ExprKind::Field(ref e, _)
398 | ast::ExprKind::Index(ref e, _)
399 | ast::ExprKind::Range(Some(ref e), _, _)
400 | ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
406 pub fn starts_with_newline(s: &str) -> bool {
407 s.starts_with('\n') || s.starts_with("\r\n")
411 pub fn first_line_ends_with(s: &str, c: char) -> bool {
412 s.lines().next().map_or(false, |l| l.ends_with(c))
415 // States whether an expression's last line exclusively consists of closing
416 // parens, braces, and brackets in its idiomatic formatting.
417 pub fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr: &str) -> bool {
419 ast::ExprKind::Mac(..)
420 | ast::ExprKind::Call(..)
421 | ast::ExprKind::MethodCall(..)
422 | ast::ExprKind::Array(..)
423 | ast::ExprKind::Struct(..)
424 | ast::ExprKind::While(..)
425 | ast::ExprKind::WhileLet(..)
426 | ast::ExprKind::If(..)
427 | ast::ExprKind::IfLet(..)
428 | ast::ExprKind::Block(..)
429 | ast::ExprKind::Loop(..)
430 | ast::ExprKind::ForLoop(..)
431 | ast::ExprKind::Match(..) => repr.contains('\n'),
432 ast::ExprKind::Paren(ref expr)
433 | ast::ExprKind::Binary(_, _, ref expr)
434 | ast::ExprKind::Index(_, ref expr)
435 | ast::ExprKind::Unary(_, ref expr)
436 | ast::ExprKind::Closure(_, _, _, _, ref expr, _)
437 | ast::ExprKind::Try(ref expr)
438 | ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr),
439 // This can only be a string lit
440 ast::ExprKind::Lit(_) => {
441 repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces()
447 /// Removes trailing spaces from the specified snippet. We do not remove spaces
448 /// inside strings or comments.
449 pub fn remove_trailing_white_spaces(text: &str) -> String {
450 let mut buffer = String::with_capacity(text.len());
451 let mut space_buffer = String::with_capacity(128);
452 for (char_kind, c) in CharClasses::new(text.chars()) {
455 if char_kind == FullCodeCharKind::InString {
456 buffer.push_str(&space_buffer);
458 space_buffer.clear();
461 _ if c.is_whitespace() => {
462 space_buffer.push(c);
465 if !space_buffer.is_empty() {
466 buffer.push_str(&space_buffer);
467 space_buffer.clear();
476 /// Indent each line according to the specified `indent`.
504 pub fn trim_left_preserve_layout(orig: &str, indent: Indent, config: &Config) -> Option<String> {
505 let mut lines = LineClasses::new(orig);
506 let first_line = lines.next().map(|(_, s)| s.trim_end().to_owned())?;
507 let mut trimmed_lines = Vec::with_capacity(16);
509 let mut veto_trim = false;
510 let min_prefix_space_width = lines
511 .filter_map(|(kind, line)| {
512 let mut trimmed = true;
513 let prefix_space_width = if is_empty_line(&line) {
516 Some(get_prefix_space_width(config, &line))
519 // just InString{Commented} in order to allow the start of a string to be indented
520 let new_veto_trim_value = (kind == FullCodeCharKind::InString
521 || (config.version() == Version::Two
522 && kind == FullCodeCharKind::InStringCommented))
523 && !line.ends_with('\\');
524 let line = if veto_trim || new_veto_trim_value {
525 veto_trim = new_veto_trim_value;
529 line.trim().to_owned()
531 trimmed_lines.push((trimmed, line, prefix_space_width));
533 // Because there is a veto against trimming and indenting lines within a string,
534 // such lines should not be taken into account when computing the minimum.
536 FullCodeCharKind::InStringCommented | FullCodeCharKind::EndStringCommented
537 if config.version() == Version::Two =>
541 FullCodeCharKind::InString | FullCodeCharKind::EndString => None,
542 _ => prefix_space_width,
553 |&(trimmed, ref line, prefix_space_width)| match prefix_space_width {
554 _ if !trimmed => line.to_owned(),
555 Some(original_indent_width) => {
556 let new_indent_width = indent.width()
557 + original_indent_width.saturating_sub(min_prefix_space_width);
558 let new_indent = Indent::from_width(config, new_indent_width);
559 format!("{}{}", new_indent.to_string(config), line)
561 None => String::new(),
569 /// Based on the given line, determine if the next line can be indented or not.
570 /// This allows to preserve the indentation of multi-line literals.
571 pub fn indent_next_line(kind: FullCodeCharKind, line: &str, config: &Config) -> bool {
572 !(kind.is_string() || (config.version() == Version::Two && kind.is_commented_string()))
573 || line.ends_with('\\')
576 pub fn is_empty_line(s: &str) -> bool {
577 s.is_empty() || s.chars().all(char::is_whitespace)
580 fn get_prefix_space_width(config: &Config, s: &str) -> usize {
585 '\t' => width += config.tab_spaces(),
592 pub(crate) trait NodeIdExt {
596 impl NodeIdExt for NodeId {
597 fn root() -> NodeId {
598 NodeId::placeholder_from_mark(Mark::root())
602 pub(crate) fn unicode_str_width(s: &str) -> usize {
606 pub fn get_skip_macro_names(attrs: &[ast::Attribute]) -> Vec<String> {
607 let mut skip_macro_names = vec![];
609 // syntax::ast::Path is implemented partialEq
610 // but it is designed for segments.len() == 1
611 if format!("{}", attr.path) != "rustfmt::skip::macros" {
615 if let Some(list) = attr.meta_item_list() {
616 for spanned in list {
617 if let Some(name) = spanned.name() {
618 skip_macro_names.push(name.to_string());
631 fn test_remove_trailing_white_spaces() {
632 let s = " r#\"\n test\n \"#";
633 assert_eq!(remove_trailing_white_spaces(&s), s);
637 fn test_trim_left_preserve_layout() {
638 let s = "aaa\n\tbbb\n ccc";
639 let config = Config::default();
640 let indent = Indent::new(4, 0);
642 trim_left_preserve_layout(&s, indent, &config),
643 Some("aaa\n bbb\n ccc".to_string())