3 use rustc_target::spec::abi;
5 self, Attribute, CrateSugar, MetaItem, MetaItemKind, NestedMetaItem, NodeId, Path, Visibility,
9 use syntax::source_map::{BytePos, Span, SyntaxContext};
10 use syntax::symbol::{sym, Symbol};
11 use syntax_pos::ExpnId;
12 use unicode_width::UnicodeWidthStr;
14 use crate::comment::{filter_normal_code, CharClasses, FullCodeCharKind, LineClasses};
15 use crate::config::{Config, Version};
16 use crate::rewrite::RewriteContext;
17 use crate::shape::{Indent, Shape};
20 pub(crate) fn depr_skip_annotation() -> Symbol {
21 Symbol::intern("rustfmt_skip")
25 pub(crate) fn skip_annotation() -> Symbol {
26 Symbol::intern("rustfmt::skip")
29 pub(crate) fn rewrite_ident<'a>(context: &'a RewriteContext<'_>, ident: ast::Ident) -> &'a str {
30 context.snippet(ident.span)
33 // Computes the length of a string's last line, minus offset.
34 pub(crate) fn extra_offset(text: &str, shape: Shape) -> usize {
35 match text.rfind('\n') {
36 // 1 for newline character
37 Some(idx) => text.len().saturating_sub(idx + 1 + shape.used_width()),
42 pub(crate) fn is_same_visibility(a: &Visibility, b: &Visibility) -> bool {
43 match (&a.node, &b.node) {
45 VisibilityKind::Restricted { path: p, .. },
46 VisibilityKind::Restricted { path: q, .. },
47 ) => p.to_string() == q.to_string(),
48 (VisibilityKind::Public, VisibilityKind::Public)
49 | (VisibilityKind::Inherited, VisibilityKind::Inherited)
51 VisibilityKind::Crate(CrateSugar::PubCrate),
52 VisibilityKind::Crate(CrateSugar::PubCrate),
55 VisibilityKind::Crate(CrateSugar::JustCrate),
56 VisibilityKind::Crate(CrateSugar::JustCrate),
62 // Uses Cow to avoid allocating in the common cases.
63 pub(crate) fn format_visibility(
64 context: &RewriteContext<'_>,
66 ) -> Cow<'static, str> {
68 VisibilityKind::Public => Cow::from("pub "),
69 VisibilityKind::Inherited => Cow::from(""),
70 VisibilityKind::Crate(CrateSugar::PubCrate) => Cow::from("pub(crate) "),
71 VisibilityKind::Crate(CrateSugar::JustCrate) => Cow::from("crate "),
72 VisibilityKind::Restricted { ref path, .. } => {
73 let Path { ref segments, .. } = **path;
74 let mut segments_iter = segments.iter().map(|seg| rewrite_ident(context, seg.ident));
78 .expect("Non-global path in pub(restricted)?");
80 let is_keyword = |s: &str| s == "self" || s == "super";
81 let path = segments_iter.collect::<Vec<_>>().join("::");
82 let in_str = if is_keyword(&path) { "" } else { "in " };
84 Cow::from(format!("pub({}{}) ", in_str, path))
90 pub(crate) fn format_async(is_async: &ast::IsAsync) -> &'static str {
92 ast::IsAsync::Async { .. } => "async ",
93 ast::IsAsync::NotAsync => "",
98 pub(crate) fn format_constness(constness: ast::Constness) -> &'static str {
100 ast::Constness::Const => "const ",
101 ast::Constness::NotConst => "",
106 pub(crate) fn format_defaultness(defaultness: ast::Defaultness) -> &'static str {
108 ast::Defaultness::Default => "default ",
109 ast::Defaultness::Final => "",
114 pub(crate) fn format_unsafety(unsafety: ast::Unsafety) -> &'static str {
116 ast::Unsafety::Unsafe => "unsafe ",
117 ast::Unsafety::Normal => "",
122 pub(crate) fn format_auto(is_auto: ast::IsAuto) -> &'static str {
124 ast::IsAuto::Yes => "auto ",
125 ast::IsAuto::No => "",
130 pub(crate) fn format_mutability(mutability: ast::Mutability) -> &'static str {
132 ast::Mutability::Mutable => "mut ",
133 ast::Mutability::Immutable => "",
138 pub(crate) fn format_abi(abi: abi::Abi, explicit_abi: bool, is_mod: bool) -> Cow<'static, str> {
139 if abi == abi::Abi::Rust && !is_mod {
141 } else if abi == abi::Abi::C && !explicit_abi {
144 Cow::from(format!("extern {} ", abi))
149 // Transform `Vec<syntax::ptr::P<T>>` into `Vec<&T>`
150 pub(crate) fn ptr_vec_to_ref_vec<T>(vec: &[ptr::P<T>]) -> Vec<&T> {
151 vec.iter().map(|x| &**x).collect::<Vec<_>>()
155 pub(crate) fn filter_attributes(
156 attrs: &[ast::Attribute],
157 style: ast::AttrStyle,
158 ) -> Vec<ast::Attribute> {
161 .filter(|a| a.style == style)
167 pub(crate) fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
168 filter_attributes(attrs, ast::AttrStyle::Inner)
172 pub(crate) fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
173 filter_attributes(attrs, ast::AttrStyle::Outer)
177 pub(crate) fn is_single_line(s: &str) -> bool {
178 s.chars().find(|&c| c == '\n').is_none()
182 pub(crate) fn first_line_contains_single_line_comment(s: &str) -> bool {
183 s.lines().next().map_or(false, |l| l.contains("//"))
187 pub(crate) fn last_line_contains_single_line_comment(s: &str) -> bool {
188 s.lines().last().map_or(false, |l| l.contains("//"))
192 pub(crate) fn is_attributes_extendable(attrs_str: &str) -> bool {
193 !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
196 /// The width of the first line in s.
198 pub(crate) fn first_line_width(s: &str) -> usize {
199 unicode_str_width(s.splitn(2, '\n').next().unwrap_or(""))
202 /// The width of the last line in s.
204 pub(crate) fn last_line_width(s: &str) -> usize {
205 unicode_str_width(s.rsplitn(2, '\n').next().unwrap_or(""))
208 /// The total used width of the last line.
210 pub(crate) fn last_line_used_width(s: &str, offset: usize) -> usize {
211 if s.contains('\n') {
214 offset + unicode_str_width(s)
219 pub(crate) fn trimmed_last_line_width(s: &str) -> usize {
220 unicode_str_width(match s.rfind('\n') {
221 Some(n) => s[(n + 1)..].trim(),
227 pub(crate) fn last_line_extendable(s: &str) -> bool {
228 if s.ends_with("\"#") {
231 for c in s.chars().rev() {
233 '(' | ')' | ']' | '}' | '?' | '>' => continue,
235 _ if c.is_whitespace() => continue,
243 fn is_skip(meta_item: &MetaItem) -> bool {
244 match meta_item.kind {
245 MetaItemKind::Word => {
246 let path_str = meta_item.path.to_string();
247 path_str == skip_annotation().as_str() || path_str == depr_skip_annotation().as_str()
249 MetaItemKind::List(ref l) => {
250 meta_item.check_name(sym::cfg_attr) && l.len() == 2 && is_skip_nested(&l[1])
257 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
259 NestedMetaItem::MetaItem(ref mi) => is_skip(mi),
260 NestedMetaItem::Literal(_) => false,
265 pub(crate) fn contains_skip(attrs: &[Attribute]) -> bool {
268 .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
272 pub(crate) fn semicolon_for_expr(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
274 ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
275 context.config.trailing_semicolon()
282 pub(crate) fn semicolon_for_stmt(context: &RewriteContext<'_>, stmt: &ast::Stmt) -> bool {
284 ast::StmtKind::Semi(ref expr) => match expr.kind {
285 ast::ExprKind::While(..) | ast::ExprKind::Loop(..) | ast::ExprKind::ForLoop(..) => {
288 ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
289 context.config.trailing_semicolon()
293 ast::StmtKind::Expr(..) => false,
299 pub(crate) fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
301 ast::StmtKind::Expr(ref expr) => Some(expr),
306 /// Returns the number of LF and CRLF respectively.
307 pub(crate) fn count_lf_crlf(input: &str) -> (usize, usize) {
310 let mut is_crlf = false;
311 for c in input.as_bytes() {
313 b'\r' => is_crlf = true,
314 b'\n' if is_crlf => crlf += 1,
316 _ => is_crlf = false,
322 pub(crate) fn count_newlines(input: &str) -> usize {
323 // Using bytes to omit UTF-8 decoding
324 bytecount::count(input.as_bytes(), b'\n')
327 // For format_missing and last_pos, need to use the source callsite (if applicable).
328 // Required as generated code spans aren't guaranteed to follow on from the last span.
329 macro_rules! source {
330 ($this:ident, $sp:expr) => {
331 $sp.source_callsite()
335 pub(crate) fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
336 Span::new(lo, hi, SyntaxContext::root())
339 // Returns `true` if the given span does not intersect with file lines.
340 macro_rules! out_of_file_lines_range {
341 ($self:ident, $span:expr) => {
342 !$self.config.file_lines().is_all()
346 .intersects(&$self.source_map.lookup_line_range($span))
350 macro_rules! skip_out_of_file_lines_range {
351 ($self:ident, $span:expr) => {
352 if out_of_file_lines_range!($self, $span) {
358 macro_rules! skip_out_of_file_lines_range_visitor {
359 ($self:ident, $span:expr) => {
360 if out_of_file_lines_range!($self, $span) {
361 $self.push_rewrite($span, None);
367 // Wraps String in an Option. Returns Some when the string adheres to the
368 // Rewrite constraints defined for the Rewrite trait and None otherwise.
369 pub(crate) fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
370 if is_valid_str(&filter_normal_code(&s), max_width, shape) {
377 fn is_valid_str(snippet: &str, max_width: usize, shape: Shape) -> bool {
378 if !snippet.is_empty() {
379 // First line must fits with `shape.width`.
380 if first_line_width(snippet) > shape.width {
383 // If the snippet does not include newline, we are done.
384 if is_single_line(snippet) {
387 // The other lines must fit within the maximum width.
391 .any(|line| unicode_str_width(line) > max_width)
395 // A special check for the last line, since the caller may
396 // place trailing characters on this line.
397 if last_line_width(snippet) > shape.used_width() + shape.width {
405 pub(crate) fn colon_spaces(config: &Config) -> &'static str {
406 let before = config.space_before_colon();
407 let after = config.space_after_colon();
408 match (before, after) {
409 (true, true) => " : ",
410 (true, false) => " :",
411 (false, true) => ": ",
412 (false, false) => ":",
417 pub(crate) fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
419 ast::ExprKind::Call(ref e, _)
420 | ast::ExprKind::Binary(_, ref e, _)
421 | ast::ExprKind::Cast(ref e, _)
422 | ast::ExprKind::Type(ref e, _)
423 | ast::ExprKind::Assign(ref e, _)
424 | ast::ExprKind::AssignOp(_, ref e, _)
425 | ast::ExprKind::Field(ref e, _)
426 | ast::ExprKind::Index(ref e, _)
427 | ast::ExprKind::Range(Some(ref e), _, _)
428 | ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
434 pub(crate) fn starts_with_newline(s: &str) -> bool {
435 s.starts_with('\n') || s.starts_with("\r\n")
439 pub(crate) fn first_line_ends_with(s: &str, c: char) -> bool {
440 s.lines().next().map_or(false, |l| l.ends_with(c))
443 // States whether an expression's last line exclusively consists of closing
444 // parens, braces, and brackets in its idiomatic formatting.
445 pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr: &str) -> bool {
447 ast::ExprKind::Mac(..)
448 | ast::ExprKind::Call(..)
449 | ast::ExprKind::MethodCall(..)
450 | ast::ExprKind::Array(..)
451 | ast::ExprKind::Struct(..)
452 | ast::ExprKind::While(..)
453 | ast::ExprKind::If(..)
454 | ast::ExprKind::Block(..)
455 | ast::ExprKind::Async(..)
456 | ast::ExprKind::Loop(..)
457 | ast::ExprKind::ForLoop(..)
458 | ast::ExprKind::TryBlock(..)
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()
471 ast::ExprKind::AddrOf(..)
472 | ast::ExprKind::Assign(..)
473 | ast::ExprKind::AssignOp(..)
474 | ast::ExprKind::Await(..)
475 | ast::ExprKind::Box(..)
476 | ast::ExprKind::Break(..)
477 | ast::ExprKind::Cast(..)
478 | ast::ExprKind::Continue(..)
480 | ast::ExprKind::Field(..)
481 | ast::ExprKind::InlineAsm(..)
482 | ast::ExprKind::Let(..)
483 | ast::ExprKind::Path(..)
484 | ast::ExprKind::Range(..)
485 | ast::ExprKind::Repeat(..)
486 | ast::ExprKind::Ret(..)
487 | ast::ExprKind::Tup(..)
488 | ast::ExprKind::Type(..)
489 | ast::ExprKind::Yield(None) => false,
493 /// Removes trailing spaces from the specified snippet. We do not remove spaces
494 /// inside strings or comments.
495 pub(crate) fn remove_trailing_white_spaces(text: &str) -> String {
496 let mut buffer = String::with_capacity(text.len());
497 let mut space_buffer = String::with_capacity(128);
498 for (char_kind, c) in CharClasses::new(text.chars()) {
501 if char_kind == FullCodeCharKind::InString {
502 buffer.push_str(&space_buffer);
504 space_buffer.clear();
507 _ if c.is_whitespace() => {
508 space_buffer.push(c);
511 if !space_buffer.is_empty() {
512 buffer.push_str(&space_buffer);
513 space_buffer.clear();
522 /// Indent each line according to the specified `indent`.
525 /// ```rust,compile_fail
539 /// ```rust,compile_fail
550 pub(crate) fn trim_left_preserve_layout(
554 ) -> Option<String> {
555 let mut lines = LineClasses::new(orig);
556 let first_line = lines.next().map(|(_, s)| s.trim_end().to_owned())?;
557 let mut trimmed_lines = Vec::with_capacity(16);
559 let mut veto_trim = false;
560 let min_prefix_space_width = lines
561 .filter_map(|(kind, line)| {
562 let mut trimmed = true;
563 let prefix_space_width = if is_empty_line(&line) {
566 Some(get_prefix_space_width(config, &line))
569 // just InString{Commented} in order to allow the start of a string to be indented
570 let new_veto_trim_value = (kind == FullCodeCharKind::InString
571 || (config.version() == Version::Two
572 && kind == FullCodeCharKind::InStringCommented))
573 && !line.ends_with('\\');
574 let line = if veto_trim || new_veto_trim_value {
575 veto_trim = new_veto_trim_value;
579 line.trim().to_owned()
581 trimmed_lines.push((trimmed, line, prefix_space_width));
583 // Because there is a veto against trimming and indenting lines within a string,
584 // such lines should not be taken into account when computing the minimum.
586 FullCodeCharKind::InStringCommented | FullCodeCharKind::EndStringCommented
587 if config.version() == Version::Two =>
591 FullCodeCharKind::InString | FullCodeCharKind::EndString => None,
592 _ => prefix_space_width,
603 |&(trimmed, ref line, prefix_space_width)| match prefix_space_width {
604 _ if !trimmed => line.to_owned(),
605 Some(original_indent_width) => {
606 let new_indent_width = indent.width()
607 + original_indent_width.saturating_sub(min_prefix_space_width);
608 let new_indent = Indent::from_width(config, new_indent_width);
609 format!("{}{}", new_indent.to_string(config), line)
611 None => String::new(),
619 /// Based on the given line, determine if the next line can be indented or not.
620 /// This allows to preserve the indentation of multi-line literals.
621 pub(crate) fn indent_next_line(kind: FullCodeCharKind, _line: &str, config: &Config) -> bool {
622 !(kind.is_string() || (config.version() == Version::Two && kind.is_commented_string()))
625 pub(crate) fn is_empty_line(s: &str) -> bool {
626 s.is_empty() || s.chars().all(char::is_whitespace)
629 fn get_prefix_space_width(config: &Config, s: &str) -> usize {
634 '\t' => width += config.tab_spaces(),
641 pub(crate) trait NodeIdExt {
645 impl NodeIdExt for NodeId {
646 fn root() -> NodeId {
647 NodeId::placeholder_from_expn_id(ExpnId::root())
651 pub(crate) fn unicode_str_width(s: &str) -> usize {
660 fn test_remove_trailing_white_spaces() {
661 let s = " r#\"\n test\n \"#";
662 assert_eq!(remove_trailing_white_spaces(&s), s);
666 fn test_trim_left_preserve_layout() {
667 let s = "aaa\n\tbbb\n ccc";
668 let config = Config::default();
669 let indent = Indent::new(4, 0);
671 trim_left_preserve_layout(&s, indent, &config),
672 Some("aaa\n bbb\n ccc".to_string())