4 self, Attribute, CrateSugar, MetaItem, MetaItemKind, NestedMetaItem, NodeId, Path, Visibility,
8 use rustc_ast_pretty::pprust;
9 use rustc_span::{sym, symbol, BytePos, ExpnId, Span, Symbol, SyntaxContext};
10 use unicode_width::UnicodeWidthStr;
12 use crate::comment::{filter_normal_code, CharClasses, FullCodeCharKind, LineClasses};
13 use crate::config::{Config, Version};
14 use crate::rewrite::RewriteContext;
15 use crate::shape::{Indent, Shape};
18 pub(crate) fn depr_skip_annotation() -> Symbol {
19 Symbol::intern("rustfmt_skip")
23 pub(crate) fn skip_annotation() -> Symbol {
24 Symbol::intern("rustfmt::skip")
27 pub(crate) fn rewrite_ident<'a>(context: &'a RewriteContext<'_>, ident: symbol::Ident) -> &'a str {
28 context.snippet(ident.span)
31 // Computes the length of a string's last line, minus offset.
32 pub(crate) fn extra_offset(text: &str, shape: Shape) -> usize {
33 match text.rfind('\n') {
34 // 1 for newline character
35 Some(idx) => text.len().saturating_sub(idx + 1 + shape.used_width()),
40 pub(crate) fn is_same_visibility(a: &Visibility, b: &Visibility) -> bool {
41 match (&a.kind, &b.kind) {
43 VisibilityKind::Restricted { path: p, .. },
44 VisibilityKind::Restricted { path: q, .. },
45 ) => pprust::path_to_string(&p) == pprust::path_to_string(&q),
46 (VisibilityKind::Public, VisibilityKind::Public)
47 | (VisibilityKind::Inherited, VisibilityKind::Inherited)
49 VisibilityKind::Crate(CrateSugar::PubCrate),
50 VisibilityKind::Crate(CrateSugar::PubCrate),
53 VisibilityKind::Crate(CrateSugar::JustCrate),
54 VisibilityKind::Crate(CrateSugar::JustCrate),
60 // Uses Cow to avoid allocating in the common cases.
61 pub(crate) fn format_visibility(
62 context: &RewriteContext<'_>,
64 ) -> Cow<'static, str> {
66 VisibilityKind::Public => Cow::from("pub "),
67 VisibilityKind::Inherited => Cow::from(""),
68 VisibilityKind::Crate(CrateSugar::PubCrate) => Cow::from("pub(crate) "),
69 VisibilityKind::Crate(CrateSugar::JustCrate) => Cow::from("crate "),
70 VisibilityKind::Restricted { ref path, .. } => {
71 let Path { ref segments, .. } = **path;
72 let mut segments_iter = segments.iter().map(|seg| rewrite_ident(context, seg.ident));
76 .expect("Non-global path in pub(restricted)?");
78 let is_keyword = |s: &str| s == "self" || s == "super";
79 let path = segments_iter.collect::<Vec<_>>().join("::");
80 let in_str = if is_keyword(&path) { "" } else { "in " };
82 Cow::from(format!("pub({}{}) ", in_str, path))
88 pub(crate) fn format_async(is_async: &ast::Async) -> &'static str {
90 ast::Async::Yes { .. } => "async ",
96 pub(crate) fn format_constness(constness: ast::Const) -> &'static str {
98 ast::Const::Yes(..) => "const ",
104 pub(crate) fn format_constness_right(constness: ast::Const) -> &'static str {
106 ast::Const::Yes(..) => " const",
107 ast::Const::No => "",
112 pub(crate) fn format_defaultness(defaultness: ast::Defaultness) -> &'static str {
114 ast::Defaultness::Default(..) => "default ",
115 ast::Defaultness::Final => "",
120 pub(crate) fn format_unsafety(unsafety: ast::Unsafe) -> &'static str {
122 ast::Unsafe::Yes(..) => "unsafe ",
123 ast::Unsafe::No => "",
128 pub(crate) fn format_auto(is_auto: ast::IsAuto) -> &'static str {
130 ast::IsAuto::Yes => "auto ",
131 ast::IsAuto::No => "",
136 pub(crate) fn format_mutability(mutability: ast::Mutability) -> &'static str {
138 ast::Mutability::Mut => "mut ",
139 ast::Mutability::Not => "",
144 pub(crate) fn format_extern(
148 ) -> Cow<'static, str> {
149 let abi = match ext {
150 ast::Extern::None => "Rust".to_owned(),
151 ast::Extern::Implicit => "C".to_owned(),
152 ast::Extern::Explicit(abi) => abi.symbol_unescaped.to_string(),
155 if abi == "Rust" && !is_mod {
157 } else if abi == "C" && !explicit_abi {
160 Cow::from(format!(r#"extern "{}" "#, abi))
165 // Transform `Vec<rustc_ast::ptr::P<T>>` into `Vec<&T>`
166 pub(crate) fn ptr_vec_to_ref_vec<T>(vec: &[ptr::P<T>]) -> Vec<&T> {
167 vec.iter().map(|x| &**x).collect::<Vec<_>>()
171 pub(crate) fn filter_attributes(
172 attrs: &[ast::Attribute],
173 style: ast::AttrStyle,
174 ) -> Vec<ast::Attribute> {
177 .filter(|a| a.style == style)
183 pub(crate) fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
184 filter_attributes(attrs, ast::AttrStyle::Inner)
188 pub(crate) fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
189 filter_attributes(attrs, ast::AttrStyle::Outer)
193 pub(crate) fn is_single_line(s: &str) -> bool {
194 s.chars().find(|&c| c == '\n').is_none()
198 pub(crate) fn first_line_contains_single_line_comment(s: &str) -> bool {
199 s.lines().next().map_or(false, |l| l.contains("//"))
203 pub(crate) fn last_line_contains_single_line_comment(s: &str) -> bool {
204 s.lines().last().map_or(false, |l| l.contains("//"))
208 pub(crate) fn is_attributes_extendable(attrs_str: &str) -> bool {
209 !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
212 /// The width of the first line in s.
214 pub(crate) fn first_line_width(s: &str) -> usize {
215 unicode_str_width(s.splitn(2, '\n').next().unwrap_or(""))
218 /// The width of the last line in s.
220 pub(crate) fn last_line_width(s: &str) -> usize {
221 unicode_str_width(s.rsplitn(2, '\n').next().unwrap_or(""))
224 /// The total used width of the last line.
226 pub(crate) fn last_line_used_width(s: &str, offset: usize) -> usize {
227 if s.contains('\n') {
230 offset + unicode_str_width(s)
235 pub(crate) fn trimmed_last_line_width(s: &str) -> usize {
236 unicode_str_width(match s.rfind('\n') {
237 Some(n) => s[(n + 1)..].trim(),
243 pub(crate) fn last_line_extendable(s: &str) -> bool {
244 if s.ends_with("\"#") {
247 for c in s.chars().rev() {
249 '(' | ')' | ']' | '}' | '?' | '>' => continue,
251 _ if c.is_whitespace() => continue,
259 fn is_skip(meta_item: &MetaItem) -> bool {
260 match meta_item.kind {
261 MetaItemKind::Word => {
262 let path_str = pprust::path_to_string(&meta_item.path);
263 path_str == &*skip_annotation().as_str()
264 || path_str == &*depr_skip_annotation().as_str()
266 MetaItemKind::List(ref l) => {
267 meta_item.has_name(sym::cfg_attr) && l.len() == 2 && is_skip_nested(&l[1])
274 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
276 NestedMetaItem::MetaItem(ref mi) => is_skip(mi),
277 NestedMetaItem::Literal(_) => false,
282 pub(crate) fn contains_skip(attrs: &[Attribute]) -> bool {
285 .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
289 pub(crate) fn semicolon_for_expr(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
290 // Never try to insert semicolons on expressions when we're inside
291 // a macro definition - this can prevent the macro from compiling
292 // when used in expression position
293 if context.is_macro_def {
298 ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
299 context.config.trailing_semicolon()
306 pub(crate) fn semicolon_for_stmt(context: &RewriteContext<'_>, stmt: &ast::Stmt) -> bool {
308 ast::StmtKind::Semi(ref expr) => match expr.kind {
309 ast::ExprKind::While(..) | ast::ExprKind::Loop(..) | ast::ExprKind::ForLoop(..) => {
312 ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
313 context.config.trailing_semicolon()
317 ast::StmtKind::Expr(..) => false,
323 pub(crate) fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
325 ast::StmtKind::Expr(ref expr) => Some(expr),
330 /// Returns the number of LF and CRLF respectively.
331 pub(crate) fn count_lf_crlf(input: &str) -> (usize, usize) {
334 let mut is_crlf = false;
335 for c in input.as_bytes() {
337 b'\r' => is_crlf = true,
338 b'\n' if is_crlf => crlf += 1,
340 _ => is_crlf = false,
346 pub(crate) fn count_newlines(input: &str) -> usize {
347 // Using bytes to omit UTF-8 decoding
348 bytecount::count(input.as_bytes(), b'\n')
351 // For format_missing and last_pos, need to use the source callsite (if applicable).
352 // Required as generated code spans aren't guaranteed to follow on from the last span.
353 macro_rules! source {
354 ($this:ident, $sp:expr) => {
355 $sp.source_callsite()
359 pub(crate) fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
360 Span::new(lo, hi, SyntaxContext::root())
363 pub(crate) fn mk_sp_lo_plus_one(lo: BytePos) -> Span {
364 Span::new(lo, lo + BytePos(1), SyntaxContext::root())
367 // Returns `true` if the given span does not intersect with file lines.
368 macro_rules! out_of_file_lines_range {
369 ($self:ident, $span:expr) => {
370 !$self.config.file_lines().is_all()
374 .intersects(&$self.parse_sess.lookup_line_range($span))
378 macro_rules! skip_out_of_file_lines_range {
379 ($self:ident, $span:expr) => {
380 if out_of_file_lines_range!($self, $span) {
386 macro_rules! skip_out_of_file_lines_range_visitor {
387 ($self:ident, $span:expr) => {
388 if out_of_file_lines_range!($self, $span) {
389 $self.push_rewrite($span, None);
395 // Wraps String in an Option. Returns Some when the string adheres to the
396 // Rewrite constraints defined for the Rewrite trait and None otherwise.
397 pub(crate) fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
398 if is_valid_str(&filter_normal_code(&s), max_width, shape) {
405 fn is_valid_str(snippet: &str, max_width: usize, shape: Shape) -> bool {
406 if !snippet.is_empty() {
407 // First line must fits with `shape.width`.
408 if first_line_width(snippet) > shape.width {
411 // If the snippet does not include newline, we are done.
412 if is_single_line(snippet) {
415 // The other lines must fit within the maximum width.
419 .any(|line| unicode_str_width(line) > max_width)
423 // A special check for the last line, since the caller may
424 // place trailing characters on this line.
425 if last_line_width(snippet) > shape.used_width() + shape.width {
433 pub(crate) fn colon_spaces(config: &Config) -> &'static str {
434 let before = config.space_before_colon();
435 let after = config.space_after_colon();
436 match (before, after) {
437 (true, true) => " : ",
438 (true, false) => " :",
439 (false, true) => ": ",
440 (false, false) => ":",
445 pub(crate) fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
447 ast::ExprKind::Call(ref e, _)
448 | ast::ExprKind::Binary(_, ref e, _)
449 | ast::ExprKind::Cast(ref e, _)
450 | ast::ExprKind::Type(ref e, _)
451 | ast::ExprKind::Assign(ref e, _, _)
452 | ast::ExprKind::AssignOp(_, ref e, _)
453 | ast::ExprKind::Field(ref e, _)
454 | ast::ExprKind::Index(ref e, _)
455 | ast::ExprKind::Range(Some(ref e), _, _)
456 | ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
462 pub(crate) fn starts_with_newline(s: &str) -> bool {
463 s.starts_with('\n') || s.starts_with("\r\n")
467 pub(crate) fn first_line_ends_with(s: &str, c: char) -> bool {
468 s.lines().next().map_or(false, |l| l.ends_with(c))
471 // States whether an expression's last line exclusively consists of closing
472 // parens, braces, and brackets in its idiomatic formatting.
473 pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr: &str) -> bool {
475 ast::ExprKind::MacCall(..)
476 | ast::ExprKind::Call(..)
477 | ast::ExprKind::MethodCall(..)
478 | ast::ExprKind::Array(..)
479 | ast::ExprKind::Struct(..)
480 | ast::ExprKind::While(..)
481 | ast::ExprKind::If(..)
482 | ast::ExprKind::Block(..)
483 | ast::ExprKind::ConstBlock(..)
484 | ast::ExprKind::Async(..)
485 | ast::ExprKind::Loop(..)
486 | ast::ExprKind::ForLoop(..)
487 | ast::ExprKind::TryBlock(..)
488 | ast::ExprKind::Match(..) => repr.contains('\n'),
489 ast::ExprKind::Paren(ref expr)
490 | ast::ExprKind::Binary(_, _, ref expr)
491 | ast::ExprKind::Index(_, ref expr)
492 | ast::ExprKind::Unary(_, ref expr)
493 | ast::ExprKind::Closure(_, _, _, _, ref expr, _)
494 | ast::ExprKind::Try(ref expr)
495 | ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr),
496 // This can only be a string lit
497 ast::ExprKind::Lit(_) => {
498 repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces()
500 ast::ExprKind::AddrOf(..)
501 | ast::ExprKind::Assign(..)
502 | ast::ExprKind::AssignOp(..)
503 | ast::ExprKind::Await(..)
504 | ast::ExprKind::Box(..)
505 | ast::ExprKind::Break(..)
506 | ast::ExprKind::Cast(..)
507 | ast::ExprKind::Continue(..)
509 | ast::ExprKind::Field(..)
510 | ast::ExprKind::InlineAsm(..)
511 | ast::ExprKind::LlvmInlineAsm(..)
512 | ast::ExprKind::Let(..)
513 | ast::ExprKind::Path(..)
514 | ast::ExprKind::Range(..)
515 | ast::ExprKind::Repeat(..)
516 | ast::ExprKind::Ret(..)
517 | ast::ExprKind::Tup(..)
518 | ast::ExprKind::Type(..)
519 | ast::ExprKind::Yield(None)
520 | ast::ExprKind::Underscore => false,
524 /// Removes trailing spaces from the specified snippet. We do not remove spaces
525 /// inside strings or comments.
526 pub(crate) fn remove_trailing_white_spaces(text: &str) -> String {
527 let mut buffer = String::with_capacity(text.len());
528 let mut space_buffer = String::with_capacity(128);
529 for (char_kind, c) in CharClasses::new(text.chars()) {
532 if char_kind == FullCodeCharKind::InString {
533 buffer.push_str(&space_buffer);
535 space_buffer.clear();
538 _ if c.is_whitespace() => {
539 space_buffer.push(c);
542 if !space_buffer.is_empty() {
543 buffer.push_str(&space_buffer);
544 space_buffer.clear();
553 /// Indent each line according to the specified `indent`.
556 /// ```rust,compile_fail
570 /// ```rust,compile_fail
581 pub(crate) fn trim_left_preserve_layout(
585 ) -> Option<String> {
586 let mut lines = LineClasses::new(orig);
587 let first_line = lines.next().map(|(_, s)| s.trim_end().to_owned())?;
588 let mut trimmed_lines = Vec::with_capacity(16);
590 let mut veto_trim = false;
591 let min_prefix_space_width = lines
592 .filter_map(|(kind, line)| {
593 let mut trimmed = true;
594 let prefix_space_width = if is_empty_line(&line) {
597 Some(get_prefix_space_width(config, &line))
600 // just InString{Commented} in order to allow the start of a string to be indented
601 let new_veto_trim_value = (kind == FullCodeCharKind::InString
602 || (config.version() == Version::Two
603 && kind == FullCodeCharKind::InStringCommented))
604 && !line.ends_with('\\');
605 let line = if veto_trim || new_veto_trim_value {
606 veto_trim = new_veto_trim_value;
610 line.trim().to_owned()
612 trimmed_lines.push((trimmed, line, prefix_space_width));
614 // Because there is a veto against trimming and indenting lines within a string,
615 // such lines should not be taken into account when computing the minimum.
617 FullCodeCharKind::InStringCommented | FullCodeCharKind::EndStringCommented
618 if config.version() == Version::Two =>
622 FullCodeCharKind::InString | FullCodeCharKind::EndString => None,
623 _ => prefix_space_width,
634 |&(trimmed, ref line, prefix_space_width)| match prefix_space_width {
635 _ if !trimmed => line.to_owned(),
636 Some(original_indent_width) => {
637 let new_indent_width = indent.width()
638 + original_indent_width.saturating_sub(min_prefix_space_width);
639 let new_indent = Indent::from_width(config, new_indent_width);
640 format!("{}{}", new_indent.to_string(config), line)
642 None => String::new(),
650 /// Based on the given line, determine if the next line can be indented or not.
651 /// This allows to preserve the indentation of multi-line literals.
652 pub(crate) fn indent_next_line(kind: FullCodeCharKind, _line: &str, config: &Config) -> bool {
653 !(kind.is_string() || (config.version() == Version::Two && kind.is_commented_string()))
656 pub(crate) fn is_empty_line(s: &str) -> bool {
657 s.is_empty() || s.chars().all(char::is_whitespace)
660 fn get_prefix_space_width(config: &Config, s: &str) -> usize {
665 '\t' => width += config.tab_spaces(),
672 pub(crate) trait NodeIdExt {
676 impl NodeIdExt for NodeId {
677 fn root() -> NodeId {
678 NodeId::placeholder_from_expn_id(ExpnId::root())
682 pub(crate) fn unicode_str_width(s: &str) -> usize {
691 fn test_remove_trailing_white_spaces() {
692 let s = " r#\"\n test\n \"#";
693 assert_eq!(remove_trailing_white_spaces(&s), s);
697 fn test_trim_left_preserve_layout() {
698 let s = "aaa\n\tbbb\n ccc";
699 let config = Config::default();
700 let indent = Indent::new(4, 0);
702 trim_left_preserve_layout(&s, indent, &config),
703 Some("aaa\n bbb\n ccc".to_string())