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};
13 use syntax_pos::ExpnId;
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(..) | ast::ExprKind::Loop(..) | ast::ExprKind::ForLoop(..) => {
290 ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
291 context.config.trailing_semicolon()
295 ast::StmtKind::Expr(..) => false,
301 pub(crate) fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
303 ast::StmtKind::Expr(ref expr) => Some(expr),
308 /// Returns the number of LF and CRLF respectively.
309 pub(crate) fn count_lf_crlf(input: &str) -> (usize, usize) {
312 let mut is_crlf = false;
313 for c in input.as_bytes() {
315 b'\r' => is_crlf = true,
316 b'\n' if is_crlf => crlf += 1,
318 _ => is_crlf = false,
324 pub(crate) fn count_newlines(input: &str) -> usize {
325 // Using bytes to omit UTF-8 decoding
326 bytecount::count(input.as_bytes(), b'\n')
329 // For format_missing and last_pos, need to use the source callsite (if applicable).
330 // Required as generated code spans aren't guaranteed to follow on from the last span.
331 macro_rules! source {
332 ($this:ident, $sp:expr) => {
333 $sp.source_callsite()
337 pub(crate) fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
338 Span::new(lo, hi, NO_EXPANSION)
341 // Returns `true` if the given span does not intersect with file lines.
342 macro_rules! out_of_file_lines_range {
343 ($self:ident, $span:expr) => {
344 !$self.config.file_lines().is_all()
348 .intersects(&$self.source_map.lookup_line_range($span))
352 macro_rules! skip_out_of_file_lines_range {
353 ($self:ident, $span:expr) => {
354 if out_of_file_lines_range!($self, $span) {
360 macro_rules! skip_out_of_file_lines_range_visitor {
361 ($self:ident, $span:expr) => {
362 if out_of_file_lines_range!($self, $span) {
363 $self.push_rewrite($span, None);
369 // Wraps String in an Option. Returns Some when the string adheres to the
370 // Rewrite constraints defined for the Rewrite trait and None otherwise.
371 pub(crate) fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
372 if is_valid_str(&filter_normal_code(&s), max_width, shape) {
379 fn is_valid_str(snippet: &str, max_width: usize, shape: Shape) -> bool {
380 if !snippet.is_empty() {
381 // First line must fits with `shape.width`.
382 if first_line_width(snippet) > shape.width {
385 // If the snippet does not include newline, we are done.
386 if is_single_line(snippet) {
389 // The other lines must fit within the maximum width.
393 .any(|line| unicode_str_width(line) > max_width)
397 // A special check for the last line, since the caller may
398 // place trailing characters on this line.
399 if last_line_width(snippet) > shape.used_width() + shape.width {
407 pub(crate) fn colon_spaces(config: &Config) -> &'static str {
408 let before = config.space_before_colon();
409 let after = config.space_after_colon();
410 match (before, after) {
411 (true, true) => " : ",
412 (true, false) => " :",
413 (false, true) => ": ",
414 (false, false) => ":",
419 pub(crate) fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
421 ast::ExprKind::Call(ref e, _)
422 | ast::ExprKind::Binary(_, ref e, _)
423 | ast::ExprKind::Cast(ref e, _)
424 | ast::ExprKind::Type(ref e, _)
425 | ast::ExprKind::Assign(ref e, _)
426 | ast::ExprKind::AssignOp(_, ref e, _)
427 | ast::ExprKind::Field(ref e, _)
428 | ast::ExprKind::Index(ref e, _)
429 | ast::ExprKind::Range(Some(ref e), _, _)
430 | ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
436 pub(crate) fn starts_with_newline(s: &str) -> bool {
437 s.starts_with('\n') || s.starts_with("\r\n")
441 pub(crate) fn first_line_ends_with(s: &str, c: char) -> bool {
442 s.lines().next().map_or(false, |l| l.ends_with(c))
445 // States whether an expression's last line exclusively consists of closing
446 // parens, braces, and brackets in its idiomatic formatting.
447 pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr: &str) -> bool {
449 ast::ExprKind::Mac(..)
450 | ast::ExprKind::Call(..)
451 | ast::ExprKind::MethodCall(..)
452 | ast::ExprKind::Array(..)
453 | ast::ExprKind::Struct(..)
454 | ast::ExprKind::While(..)
455 | ast::ExprKind::If(..)
456 | ast::ExprKind::Block(..)
457 | ast::ExprKind::Loop(..)
458 | ast::ExprKind::ForLoop(..)
459 | ast::ExprKind::Match(..) => repr.contains('\n'),
460 ast::ExprKind::Paren(ref expr)
461 | ast::ExprKind::Binary(_, _, ref expr)
462 | ast::ExprKind::Index(_, ref expr)
463 | ast::ExprKind::Unary(_, ref expr)
464 | ast::ExprKind::Closure(_, _, _, _, ref expr, _)
465 | ast::ExprKind::Try(ref expr)
466 | ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr),
467 // This can only be a string lit
468 ast::ExprKind::Lit(_) => {
469 repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces()
475 /// Removes trailing spaces from the specified snippet. We do not remove spaces
476 /// inside strings or comments.
477 pub(crate) fn remove_trailing_white_spaces(text: &str) -> String {
478 let mut buffer = String::with_capacity(text.len());
479 let mut space_buffer = String::with_capacity(128);
480 for (char_kind, c) in CharClasses::new(text.chars()) {
483 if char_kind == FullCodeCharKind::InString {
484 buffer.push_str(&space_buffer);
486 space_buffer.clear();
489 _ if c.is_whitespace() => {
490 space_buffer.push(c);
493 if !space_buffer.is_empty() {
494 buffer.push_str(&space_buffer);
495 space_buffer.clear();
504 /// Indent each line according to the specified `indent`.
507 /// ```rust,compile_fail
521 /// ```rust,compile_fail
532 pub(crate) fn trim_left_preserve_layout(
536 ) -> Option<String> {
537 let mut lines = LineClasses::new(orig);
538 let first_line = lines.next().map(|(_, s)| s.trim_end().to_owned())?;
539 let mut trimmed_lines = Vec::with_capacity(16);
541 let mut veto_trim = false;
542 let min_prefix_space_width = lines
543 .filter_map(|(kind, line)| {
544 let mut trimmed = true;
545 let prefix_space_width = if is_empty_line(&line) {
548 Some(get_prefix_space_width(config, &line))
551 // just InString{Commented} in order to allow the start of a string to be indented
552 let new_veto_trim_value = (kind == FullCodeCharKind::InString
553 || (config.version() == Version::Two
554 && kind == FullCodeCharKind::InStringCommented))
555 && !line.ends_with('\\');
556 let line = if veto_trim || new_veto_trim_value {
557 veto_trim = new_veto_trim_value;
561 line.trim().to_owned()
563 trimmed_lines.push((trimmed, line, prefix_space_width));
565 // Because there is a veto against trimming and indenting lines within a string,
566 // such lines should not be taken into account when computing the minimum.
568 FullCodeCharKind::InStringCommented | FullCodeCharKind::EndStringCommented
569 if config.version() == Version::Two =>
573 FullCodeCharKind::InString | FullCodeCharKind::EndString => None,
574 _ => prefix_space_width,
585 |&(trimmed, ref line, prefix_space_width)| match prefix_space_width {
586 _ if !trimmed => line.to_owned(),
587 Some(original_indent_width) => {
588 let new_indent_width = indent.width()
589 + original_indent_width.saturating_sub(min_prefix_space_width);
590 let new_indent = Indent::from_width(config, new_indent_width);
591 format!("{}{}", new_indent.to_string(config), line)
593 None => String::new(),
601 /// Based on the given line, determine if the next line can be indented or not.
602 /// This allows to preserve the indentation of multi-line literals.
603 pub(crate) fn indent_next_line(kind: FullCodeCharKind, line: &str, config: &Config) -> bool {
604 !(kind.is_string() || (config.version() == Version::Two && kind.is_commented_string()))
605 || line.ends_with('\\')
608 pub(crate) fn is_empty_line(s: &str) -> bool {
609 s.is_empty() || s.chars().all(char::is_whitespace)
612 fn get_prefix_space_width(config: &Config, s: &str) -> usize {
617 '\t' => width += config.tab_spaces(),
624 pub(crate) trait NodeIdExt {
628 impl NodeIdExt for NodeId {
629 fn root() -> NodeId {
630 NodeId::placeholder_from_expn_id(ExpnId::root())
634 pub(crate) fn unicode_str_width(s: &str) -> usize {
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())