5 use rustc_target::spec::abi;
7 self, Attribute, CrateSugar, MetaItem, MetaItemKind, NestedMetaItem, NodeId, Path, Visibility,
11 use syntax::source_map::{BytePos, Span, NO_EXPANSION};
12 use syntax::symbol::{sym, Symbol};
14 use unicode_width::UnicodeWidthStr;
16 use crate::comment::{filter_normal_code, CharClasses, FullCodeCharKind, LineClasses};
17 use crate::config::{Config, Version};
18 use crate::rewrite::RewriteContext;
19 use crate::shape::{Indent, Shape};
22 pub(crate) fn depr_skip_annotation() -> Symbol {
23 Symbol::intern("rustfmt_skip")
27 pub(crate) fn skip_annotation() -> Symbol {
28 Symbol::intern("rustfmt::skip")
31 pub(crate) fn rewrite_ident<'a>(context: &'a RewriteContext<'_>, ident: ast::Ident) -> &'a str {
32 context.snippet(ident.span)
35 // Computes the length of a string's last line, minus offset.
36 pub(crate) fn extra_offset(text: &str, shape: Shape) -> usize {
37 match text.rfind('\n') {
38 // 1 for newline character
39 Some(idx) => text.len().saturating_sub(idx + 1 + shape.used_width()),
44 pub(crate) fn is_same_visibility(a: &Visibility, b: &Visibility) -> bool {
45 match (&a.node, &b.node) {
47 VisibilityKind::Restricted { path: p, .. },
48 VisibilityKind::Restricted { path: q, .. },
49 ) => p.to_string() == q.to_string(),
50 (VisibilityKind::Public, VisibilityKind::Public)
51 | (VisibilityKind::Inherited, VisibilityKind::Inherited)
53 VisibilityKind::Crate(CrateSugar::PubCrate),
54 VisibilityKind::Crate(CrateSugar::PubCrate),
57 VisibilityKind::Crate(CrateSugar::JustCrate),
58 VisibilityKind::Crate(CrateSugar::JustCrate),
64 // Uses Cow to avoid allocating in the common cases.
65 pub(crate) fn format_visibility(
66 context: &RewriteContext<'_>,
68 ) -> Cow<'static, str> {
70 VisibilityKind::Public => Cow::from("pub "),
71 VisibilityKind::Inherited => Cow::from(""),
72 VisibilityKind::Crate(CrateSugar::PubCrate) => Cow::from("pub(crate) "),
73 VisibilityKind::Crate(CrateSugar::JustCrate) => Cow::from("crate "),
74 VisibilityKind::Restricted { ref path, .. } => {
75 let Path { ref segments, .. } = **path;
76 let mut segments_iter = segments.iter().map(|seg| rewrite_ident(context, seg.ident));
80 .expect("Non-global path in pub(restricted)?");
82 let is_keyword = |s: &str| s == "self" || s == "super";
83 let path = segments_iter.collect::<Vec<_>>().join("::");
84 let in_str = if is_keyword(&path) { "" } else { "in " };
86 Cow::from(format!("pub({}{}) ", in_str, path))
92 pub(crate) fn format_async(is_async: &ast::IsAsync) -> &'static str {
94 ast::IsAsync::Async { .. } => "async ",
95 ast::IsAsync::NotAsync => "",
100 pub(crate) fn format_constness(constness: ast::Constness) -> &'static str {
102 ast::Constness::Const => "const ",
103 ast::Constness::NotConst => "",
108 pub(crate) fn format_defaultness(defaultness: ast::Defaultness) -> &'static str {
110 ast::Defaultness::Default => "default ",
111 ast::Defaultness::Final => "",
116 pub(crate) fn format_unsafety(unsafety: ast::Unsafety) -> &'static str {
118 ast::Unsafety::Unsafe => "unsafe ",
119 ast::Unsafety::Normal => "",
124 pub(crate) fn format_auto(is_auto: ast::IsAuto) -> &'static str {
126 ast::IsAuto::Yes => "auto ",
127 ast::IsAuto::No => "",
132 pub(crate) fn format_mutability(mutability: ast::Mutability) -> &'static str {
134 ast::Mutability::Mutable => "mut ",
135 ast::Mutability::Immutable => "",
140 pub(crate) fn format_abi(abi: abi::Abi, explicit_abi: bool, is_mod: bool) -> Cow<'static, str> {
141 if abi == abi::Abi::Rust && !is_mod {
143 } else if abi == abi::Abi::C && !explicit_abi {
146 Cow::from(format!("extern {} ", abi))
151 // Transform `Vec<syntax::ptr::P<T>>` into `Vec<&T>`
152 pub(crate) fn ptr_vec_to_ref_vec<T>(vec: &[ptr::P<T>]) -> Vec<&T> {
153 vec.iter().map(|x| &**x).collect::<Vec<_>>()
157 pub(crate) fn filter_attributes(
158 attrs: &[ast::Attribute],
159 style: ast::AttrStyle,
160 ) -> Vec<ast::Attribute> {
163 .filter(|a| a.style == style)
169 pub(crate) fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
170 filter_attributes(attrs, ast::AttrStyle::Inner)
174 pub(crate) fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
175 filter_attributes(attrs, ast::AttrStyle::Outer)
179 pub(crate) fn is_single_line(s: &str) -> bool {
180 s.chars().find(|&c| c == '\n').is_none()
184 pub(crate) fn first_line_contains_single_line_comment(s: &str) -> bool {
185 s.lines().next().map_or(false, |l| l.contains("//"))
189 pub(crate) fn last_line_contains_single_line_comment(s: &str) -> bool {
190 s.lines().last().map_or(false, |l| l.contains("//"))
194 pub(crate) fn is_attributes_extendable(attrs_str: &str) -> bool {
195 !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
198 // The width of the first line in s.
200 pub(crate) fn first_line_width(s: &str) -> usize {
201 unicode_str_width(s.splitn(2, '\n').next().unwrap_or(""))
204 // The width of the last line in s.
206 pub(crate) fn last_line_width(s: &str) -> usize {
207 unicode_str_width(s.rsplitn(2, '\n').next().unwrap_or(""))
210 // The total used width of the last line.
212 pub(crate) fn last_line_used_width(s: &str, offset: usize) -> usize {
213 if s.contains('\n') {
216 offset + unicode_str_width(s)
221 pub(crate) fn trimmed_last_line_width(s: &str) -> usize {
222 unicode_str_width(match s.rfind('\n') {
223 Some(n) => s[(n + 1)..].trim(),
229 pub(crate) fn last_line_extendable(s: &str) -> bool {
230 if s.ends_with("\"#") {
233 for c in s.chars().rev() {
235 '(' | ')' | ']' | '}' | '?' | '>' => continue,
237 _ if c.is_whitespace() => continue,
245 fn is_skip(meta_item: &MetaItem) -> bool {
246 match meta_item.node {
247 MetaItemKind::Word => {
248 let path_str = meta_item.path.to_string();
249 path_str == skip_annotation().as_str() || path_str == depr_skip_annotation().as_str()
251 MetaItemKind::List(ref l) => {
252 meta_item.check_name(sym::cfg_attr) && l.len() == 2 && is_skip_nested(&l[1])
259 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
261 NestedMetaItem::MetaItem(ref mi) => is_skip(mi),
262 NestedMetaItem::Literal(_) => false,
267 pub(crate) fn contains_skip(attrs: &[Attribute]) -> bool {
270 .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
274 pub(crate) fn semicolon_for_expr(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
276 ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
277 context.config.trailing_semicolon()
284 pub(crate) fn semicolon_for_stmt(context: &RewriteContext<'_>, stmt: &ast::Stmt) -> bool {
286 ast::StmtKind::Semi(ref expr) => match expr.node {
287 ast::ExprKind::While(..)
288 | ast::ExprKind::WhileLet(..)
289 | ast::ExprKind::Loop(..)
290 | ast::ExprKind::ForLoop(..) => false,
291 ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
292 context.config.trailing_semicolon()
296 ast::StmtKind::Expr(..) => false,
302 pub(crate) fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
304 ast::StmtKind::Expr(ref expr) => Some(expr),
310 pub(crate) fn count_newlines(input: &str) -> usize {
311 // Using bytes to omit UTF-8 decoding
312 bytecount::count(input.as_bytes(), b'\n')
315 // For format_missing and last_pos, need to use the source callsite (if applicable).
316 // Required as generated code spans aren't guaranteed to follow on from the last span.
317 macro_rules! source {
318 ($this:ident, $sp:expr) => {
319 $sp.source_callsite()
323 pub(crate) fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
324 Span::new(lo, hi, NO_EXPANSION)
327 // Returns `true` if the given span does not intersect with file lines.
328 macro_rules! out_of_file_lines_range {
329 ($self:ident, $span:expr) => {
330 !$self.config.file_lines().is_all()
334 .intersects(&$self.source_map.lookup_line_range($span))
338 macro_rules! skip_out_of_file_lines_range {
339 ($self:ident, $span:expr) => {
340 if out_of_file_lines_range!($self, $span) {
346 macro_rules! skip_out_of_file_lines_range_visitor {
347 ($self:ident, $span:expr) => {
348 if out_of_file_lines_range!($self, $span) {
349 $self.push_rewrite($span, None);
355 // Wraps String in an Option. Returns Some when the string adheres to the
356 // Rewrite constraints defined for the Rewrite trait and None otherwise.
357 pub(crate) fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
358 if is_valid_str(&filter_normal_code(&s), max_width, shape) {
365 fn is_valid_str(snippet: &str, max_width: usize, shape: Shape) -> bool {
366 if !snippet.is_empty() {
367 // First line must fits with `shape.width`.
368 if first_line_width(snippet) > shape.width {
371 // If the snippet does not include newline, we are done.
372 if is_single_line(snippet) {
375 // The other lines must fit within the maximum width.
379 .any(|line| unicode_str_width(line) > max_width)
383 // A special check for the last line, since the caller may
384 // place trailing characters on this line.
385 if last_line_width(snippet) > shape.used_width() + shape.width {
393 pub(crate) fn colon_spaces(config: &Config) -> &'static str {
394 let before = config.space_before_colon();
395 let after = config.space_after_colon();
396 match (before, after) {
397 (true, true) => " : ",
398 (true, false) => " :",
399 (false, true) => ": ",
400 (false, false) => ":",
405 pub(crate) fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
407 ast::ExprKind::Call(ref e, _)
408 | ast::ExprKind::Binary(_, ref e, _)
409 | ast::ExprKind::Cast(ref e, _)
410 | ast::ExprKind::Type(ref e, _)
411 | ast::ExprKind::Assign(ref e, _)
412 | ast::ExprKind::AssignOp(_, ref e, _)
413 | ast::ExprKind::Field(ref e, _)
414 | ast::ExprKind::Index(ref e, _)
415 | ast::ExprKind::Range(Some(ref e), _, _)
416 | ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
422 pub(crate) fn starts_with_newline(s: &str) -> bool {
423 s.starts_with('\n') || s.starts_with("\r\n")
427 pub(crate) fn first_line_ends_with(s: &str, c: char) -> bool {
428 s.lines().next().map_or(false, |l| l.ends_with(c))
431 // States whether an expression's last line exclusively consists of closing
432 // parens, braces, and brackets in its idiomatic formatting.
433 pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr: &str) -> bool {
435 ast::ExprKind::Mac(..)
436 | ast::ExprKind::Call(..)
437 | ast::ExprKind::MethodCall(..)
438 | ast::ExprKind::Array(..)
439 | ast::ExprKind::Struct(..)
440 | ast::ExprKind::While(..)
441 | ast::ExprKind::WhileLet(..)
442 | ast::ExprKind::If(..)
443 | ast::ExprKind::IfLet(..)
444 | ast::ExprKind::Block(..)
445 | ast::ExprKind::Loop(..)
446 | ast::ExprKind::ForLoop(..)
447 | ast::ExprKind::Match(..) => repr.contains('\n'),
448 ast::ExprKind::Paren(ref expr)
449 | ast::ExprKind::Binary(_, _, ref expr)
450 | ast::ExprKind::Index(_, ref expr)
451 | ast::ExprKind::Unary(_, ref expr)
452 | ast::ExprKind::Closure(_, _, _, _, ref expr, _)
453 | ast::ExprKind::Try(ref expr)
454 | ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr),
455 // This can only be a string lit
456 ast::ExprKind::Lit(_) => {
457 repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces()
463 /// Removes trailing spaces from the specified snippet. We do not remove spaces
464 /// inside strings or comments.
465 pub(crate) fn remove_trailing_white_spaces(text: &str) -> String {
466 let mut buffer = String::with_capacity(text.len());
467 let mut space_buffer = String::with_capacity(128);
468 for (char_kind, c) in CharClasses::new(text.chars()) {
471 if char_kind == FullCodeCharKind::InString {
472 buffer.push_str(&space_buffer);
474 space_buffer.clear();
477 _ if c.is_whitespace() => {
478 space_buffer.push(c);
481 if !space_buffer.is_empty() {
482 buffer.push_str(&space_buffer);
483 space_buffer.clear();
492 /// Indent each line according to the specified `indent`.
520 pub(crate) fn trim_left_preserve_layout(
524 ) -> Option<String> {
525 let mut lines = LineClasses::new(orig);
526 let first_line = lines.next().map(|(_, s)| s.trim_end().to_owned())?;
527 let mut trimmed_lines = Vec::with_capacity(16);
529 let mut veto_trim = false;
530 let min_prefix_space_width = lines
531 .filter_map(|(kind, line)| {
532 let mut trimmed = true;
533 let prefix_space_width = if is_empty_line(&line) {
536 Some(get_prefix_space_width(config, &line))
539 // just InString{Commented} in order to allow the start of a string to be indented
540 let new_veto_trim_value = (kind == FullCodeCharKind::InString
541 || (config.version() == Version::Two
542 && kind == FullCodeCharKind::InStringCommented))
543 && !line.ends_with('\\');
544 let line = if veto_trim || new_veto_trim_value {
545 veto_trim = new_veto_trim_value;
549 line.trim().to_owned()
551 trimmed_lines.push((trimmed, line, prefix_space_width));
553 // Because there is a veto against trimming and indenting lines within a string,
554 // such lines should not be taken into account when computing the minimum.
556 FullCodeCharKind::InStringCommented | FullCodeCharKind::EndStringCommented
557 if config.version() == Version::Two =>
561 FullCodeCharKind::InString | FullCodeCharKind::EndString => None,
562 _ => prefix_space_width,
573 |&(trimmed, ref line, prefix_space_width)| match prefix_space_width {
574 _ if !trimmed => line.to_owned(),
575 Some(original_indent_width) => {
576 let new_indent_width = indent.width()
577 + original_indent_width.saturating_sub(min_prefix_space_width);
578 let new_indent = Indent::from_width(config, new_indent_width);
579 format!("{}{}", new_indent.to_string(config), line)
581 None => String::new(),
589 /// Based on the given line, determine if the next line can be indented or not.
590 /// This allows to preserve the indentation of multi-line literals.
591 pub(crate) fn indent_next_line(kind: FullCodeCharKind, line: &str, config: &Config) -> bool {
592 !(kind.is_string() || (config.version() == Version::Two && kind.is_commented_string()))
593 || line.ends_with('\\')
596 pub(crate) fn is_empty_line(s: &str) -> bool {
597 s.is_empty() || s.chars().all(char::is_whitespace)
600 fn get_prefix_space_width(config: &Config, s: &str) -> usize {
605 '\t' => width += config.tab_spaces(),
612 pub(crate) trait NodeIdExt {
616 impl NodeIdExt for NodeId {
617 fn root() -> NodeId {
618 NodeId::placeholder_from_mark(Mark::root())
622 pub(crate) fn unicode_str_width(s: &str) -> usize {
626 pub(crate) fn get_skip_macro_names(attrs: &[ast::Attribute]) -> Vec<String> {
627 let mut skip_macro_names = vec![];
629 // syntax::ast::Path is implemented partialEq
630 // but it is designed for segments.len() == 1
631 if format!("{}", attr.path) != "rustfmt::skip::macros" {
635 if let Some(list) = attr.meta_item_list() {
636 for nested_meta_item in list {
637 if let Some(name) = nested_meta_item.ident() {
638 skip_macro_names.push(name.to_string());
651 fn test_remove_trailing_white_spaces() {
652 let s = " r#\"\n test\n \"#";
653 assert_eq!(remove_trailing_white_spaces(&s), s);
657 fn test_trim_left_preserve_layout() {
658 let s = "aaa\n\tbbb\n ccc";
659 let config = Config::default();
660 let indent = Indent::new(4, 0);
662 trim_left_preserve_layout(&s, indent, &config),
663 Some("aaa\n bbb\n ccc".to_string())