1use std::borrow::Cow;
2
3use rustc_ast::YieldKind;
4use rustc_ast::ast::{
5 self, Attribute, ImplRestriction, MetaItem, MetaItemInner, MetaItemKind, MutRestriction,
6 NodeId, Path, RestrictionKind, Visibility, VisibilityKind,
7};
8use rustc_ast_pretty::pprust;
9use rustc_feature::is_builtin_attr_name;
10use rustc_span::{BytePos, LocalExpnId, Span, Symbol, SyntaxContext, sym, symbol};
11use unicode_width::UnicodeWidthStr;
12
13use crate::comment::{CharClasses, FullCodeCharKind, LineClasses, filter_normal_code};
14use crate::config::{Config, StyleEdition};
15use crate::rewrite::RewriteContext;
16use crate::shape::{Indent, Shape};
17
18#[inline]
19pub(crate) fn depr_skip_annotation() -> Symbol {
20 Symbol::intern("rustfmt_skip")
21}
22
23#[inline]
24pub(crate) fn skip_annotation() -> Symbol {
25 Symbol::intern("rustfmt::skip")
26}
27
28pub(crate) fn rewrite_ident<'a>(context: &'a RewriteContext<'_>, ident: symbol::Ident) -> &'a str {
29 context.snippet(ident.span)
30}
31
32pub(crate) fn extra_offset(text: &str, shape: Shape) -> usize {
34 match text.rfind('\n') {
35 Some(idx) => text.len().saturating_sub(idx + 1 + shape.used_width()),
37 None => text.len(),
38 }
39}
40
41pub(crate) fn is_same_visibility(a: &Visibility, b: &Visibility) -> bool {
42 match (&a.kind, &b.kind) {
43 (
44 VisibilityKind::Restricted { path: p, .. },
45 VisibilityKind::Restricted { path: q, .. },
46 ) => pprust::path_to_string(p) == pprust::path_to_string(q),
47 (VisibilityKind::Public, VisibilityKind::Public)
48 | (VisibilityKind::Inherited, VisibilityKind::Inherited) => true,
49 _ => false,
50 }
51}
52
53pub(crate) fn format_visibility(
55 context: &RewriteContext<'_>,
56 vis: &Visibility,
57) -> Cow<'static, str> {
58 match vis.kind {
59 VisibilityKind::Public => Cow::from("pub "),
60 VisibilityKind::Inherited => Cow::from(""),
61 VisibilityKind::Restricted { ref path, .. } => {
62 let Path { ref segments, .. } = **path;
63 let mut segments_iter = segments.iter().map(|seg| rewrite_ident(context, seg.ident));
64 if path.is_global() {
65 segments_iter
66 .next()
67 .expect("Non-global path in pub(restricted)?");
68 }
69 let is_keyword = |s: &str| s == "crate" || s == "self" || s == "super";
70 let path = segments_iter.collect::<Vec<_>>().join("::");
71 let in_str = if is_keyword(&path) { "" } else { "in " };
72
73 Cow::from(format!("pub({in_str}{path}) "))
74 }
75 }
76}
77
78pub(crate) fn format_impl_restriction(
79 context: &RewriteContext<'_>,
80 impl_restriction: &ImplRestriction,
81) -> String {
82 format_restriction("impl", context, &impl_restriction.kind)
83}
84
85pub(crate) fn format_mut_restriction(
86 context: &RewriteContext<'_>,
87 mut_restriction: &MutRestriction,
88) -> String {
89 format_restriction("mut", context, &mut_restriction.kind)
90}
91
92fn format_restriction(
93 kw: &'static str,
94 context: &RewriteContext<'_>,
95 restriction: &RestrictionKind,
96) -> String {
97 match restriction {
98 RestrictionKind::Unrestricted => String::new(),
99 RestrictionKind::Restricted {
100 ref path,
101 id: _,
102 shorthand,
103 } => {
104 let Path { ref segments, .. } = **path;
105 let mut segments_iter = segments.iter().map(|seg| rewrite_ident(context, seg.ident));
106 if path.is_global() && segments_iter.next().is_none() {
107 panic!("non-global path in {kw}(restricted)?");
108 }
109 let path = itertools::join(segments_iter, "::");
112 let in_str = if *shorthand { "" } else { "in " };
113
114 format!("{kw}({in_str}{path}) ")
115 }
116 }
117}
118
119#[inline]
120pub(crate) fn format_coro(coroutine_kind: &ast::CoroutineKind) -> &'static str {
121 match coroutine_kind {
122 ast::CoroutineKind::Async { .. } => "async ",
123 ast::CoroutineKind::Gen { .. } => "gen ",
124 ast::CoroutineKind::AsyncGen { .. } => "async gen ",
125 }
126}
127
128#[inline]
129pub(crate) fn format_constness(constness: ast::Const) -> &'static str {
130 match constness {
131 ast::Const::Yes(..) => "const ",
132 ast::Const::No => "",
133 }
134}
135
136#[inline]
137pub(crate) fn format_defaultness(defaultness: ast::Defaultness) -> &'static str {
138 match defaultness {
139 ast::Defaultness::Implicit => "",
140 ast::Defaultness::Default(..) => "default ",
141 ast::Defaultness::Final(..) => "final ",
142 }
143}
144
145#[inline]
146pub(crate) fn format_safety(unsafety: ast::Safety) -> &'static str {
147 match unsafety {
148 ast::Safety::Unsafe(..) => "unsafe ",
149 ast::Safety::Safe(..) => "safe ",
150 ast::Safety::Default => "",
151 }
152}
153
154#[inline]
155pub(crate) fn format_auto(is_auto: ast::IsAuto) -> &'static str {
156 match is_auto {
157 ast::IsAuto::Yes => "auto ",
158 ast::IsAuto::No => "",
159 }
160}
161
162#[inline]
163pub(crate) fn format_mutability(mutability: ast::Mutability) -> &'static str {
164 match mutability {
165 ast::Mutability::Mut => "mut ",
166 ast::Mutability::Not => "",
167 }
168}
169
170#[inline]
171pub(crate) fn format_pinnedness_and_mutability(
172 pinnedness: ast::Pinnedness,
173 mutability: ast::Mutability,
174) -> (&'static str, &'static str) {
175 match (pinnedness, mutability) {
176 (ast::Pinnedness::Pinned, ast::Mutability::Mut) => ("pin ", "mut "),
177 (ast::Pinnedness::Pinned, ast::Mutability::Not) => ("pin ", "const "),
178 (ast::Pinnedness::Not, ast::Mutability::Mut) => ("", "mut "),
179 (ast::Pinnedness::Not, ast::Mutability::Not) => ("", ""),
180 }
181}
182
183#[inline]
184pub(crate) fn format_range_end(end: ast::RangeEnd) -> &'static str {
185 match end {
186 ast::RangeEnd::Included(ast::RangeSyntax::DotDotDot) => "...",
187 ast::RangeEnd::Included(ast::RangeSyntax::DotDotEq) => "..=",
188 ast::RangeEnd::Excluded => "..",
189 }
190}
191
192#[inline]
193pub(crate) fn format_extern(ext: ast::Extern, explicit_abi: bool) -> Cow<'static, str> {
194 match ext {
195 ast::Extern::None => Cow::from(""),
196 ast::Extern::Implicit(_) if explicit_abi => Cow::from("extern \"C\" "),
197 ast::Extern::Implicit(_) => Cow::from("extern "),
198 ast::Extern::Explicit(abi, _) if abi.symbol_unescaped == sym::C && !explicit_abi => {
200 Cow::from("extern ")
201 }
202 ast::Extern::Explicit(abi, _) => {
203 Cow::from(format!(r#"extern "{}" "#, abi.symbol_unescaped))
204 }
205 }
206}
207
208#[inline]
209pub(crate) fn ptr_vec_to_ref_vec<T>(vec: &[Box<T>]) -> Vec<&T> {
211 vec.iter().map(|x| &**x).collect::<Vec<_>>()
212}
213
214#[inline]
215pub(crate) fn filter_attributes(
216 attrs: &[ast::Attribute],
217 style: ast::AttrStyle,
218) -> Vec<ast::Attribute> {
219 attrs
220 .iter()
221 .filter(|a| a.style == style)
222 .cloned()
223 .collect::<Vec<_>>()
224}
225
226#[inline]
227pub(crate) fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
228 filter_attributes(attrs, ast::AttrStyle::Inner)
229}
230
231#[inline]
232pub(crate) fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
233 filter_attributes(attrs, ast::AttrStyle::Outer)
234}
235
236#[inline]
237pub(crate) fn is_single_line(s: &str) -> bool {
238 !s.chars().any(|c| c == '\n')
239}
240
241#[inline]
242pub(crate) fn first_line_contains_single_line_comment(s: &str) -> bool {
243 s.lines().next().map_or(false, |l| l.contains("//"))
244}
245
246#[inline]
247pub(crate) fn last_line_contains_single_line_comment(s: &str) -> bool {
248 s.lines().last().map_or(false, |l| l.contains("//"))
249}
250
251#[inline]
252pub(crate) fn is_attributes_extendable(attrs_str: &str) -> bool {
253 !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
254}
255
256#[inline]
258pub(crate) fn first_line_width(s: &str) -> usize {
259 unicode_str_width(s.splitn(2, '\n').next().unwrap_or(""))
260}
261
262#[inline]
264pub(crate) fn last_line_width(s: &str) -> usize {
265 unicode_str_width(s.rsplitn(2, '\n').next().unwrap_or(""))
266}
267
268#[inline]
270pub(crate) fn last_line_used_width(s: &str, offset: usize) -> usize {
271 if s.contains('\n') {
272 last_line_width(s)
273 } else {
274 offset + unicode_str_width(s)
275 }
276}
277
278#[inline]
279pub(crate) fn trimmed_last_line_width(s: &str) -> usize {
280 unicode_str_width(match s.rfind('\n') {
281 Some(n) => s[(n + 1)..].trim(),
282 None => s.trim(),
283 })
284}
285
286#[inline]
287pub(crate) fn last_line_extendable(s: &str) -> bool {
288 if s.ends_with("\"#") {
289 return true;
290 }
291 for c in s.chars().rev() {
292 match c {
293 '(' | ')' | ']' | '}' | '?' | '>' => continue,
294 '\n' => break,
295 _ if c.is_whitespace() => continue,
296 _ => return false,
297 }
298 }
299 true
300}
301
302#[inline]
303fn is_skip(meta_item: &MetaItem) -> bool {
304 match meta_item.kind {
305 MetaItemKind::Word => {
306 let path_str = pprust::path_to_string(&meta_item.path);
307 path_str == skip_annotation().as_str() || path_str == depr_skip_annotation().as_str()
308 }
309 MetaItemKind::List(ref l) => {
310 meta_item.has_name(sym::cfg_attr) && l.len() == 2 && is_skip_nested(&l[1])
311 }
312 _ => false,
313 }
314}
315
316#[inline]
317fn is_skip_nested(meta_item: &MetaItemInner) -> bool {
318 match meta_item {
319 MetaItemInner::MetaItem(ref mi) => is_skip(mi),
320 MetaItemInner::Lit(_) => false,
321 }
322}
323
324#[inline]
325pub(crate) fn contains_skip(attrs: &[Attribute]) -> bool {
326 attrs
327 .iter()
328 .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
329}
330
331#[inline]
332pub(crate) fn contains_custom_attributes(attrs: &[Attribute]) -> bool {
333 attrs
334 .iter()
335 .any(|a| a.name().is_some_and(|name| !is_builtin_attr_name(name)))
336}
337
338#[inline]
339pub(crate) fn semicolon_for_expr(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
340 if context.is_macro_def {
344 return false;
345 }
346
347 match expr.kind {
348 ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
349 context.config.trailing_semicolon()
350 }
351 _ => false,
352 }
353}
354
355#[inline]
356pub(crate) fn semicolon_for_stmt(
357 context: &RewriteContext<'_>,
358 stmt: &ast::Stmt,
359 is_last_expr: bool,
360) -> bool {
361 match stmt.kind {
362 ast::StmtKind::Semi(ref expr) => match expr.kind {
363 ast::ExprKind::While(..) | ast::ExprKind::Loop(..) | ast::ExprKind::ForLoop { .. } => {
364 false
365 }
366 ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
367 context.config.trailing_semicolon() || !is_last_expr
370 }
371 _ => true,
372 },
373 ast::StmtKind::Expr(..) => false,
374 _ => true,
375 }
376}
377
378#[inline]
379pub(crate) fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
380 match stmt.kind {
381 ast::StmtKind::Expr(ref expr) => Some(expr),
382 _ => None,
383 }
384}
385
386pub(crate) fn count_lf_crlf(input: &str) -> (usize, usize) {
388 let mut lf = 0;
389 let mut crlf = 0;
390 let mut is_crlf = false;
391 for c in input.as_bytes() {
392 match c {
393 b'\r' => is_crlf = true,
394 b'\n' if is_crlf => crlf += 1,
395 b'\n' => lf += 1,
396 _ => is_crlf = false,
397 }
398 }
399 (lf, crlf)
400}
401
402pub(crate) fn count_newlines(input: &str) -> usize {
403 bytecount::count(input.as_bytes(), b'\n')
405}
406
407macro_rules! source {
410 ($this:ident, $sp:expr) => {
411 $sp.source_callsite()
412 };
413}
414
415pub(crate) fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
416 Span::new(lo, hi, SyntaxContext::root(), None)
417}
418
419pub(crate) fn mk_sp_lo_plus_one(lo: BytePos) -> Span {
420 Span::new(lo, lo + BytePos(1), SyntaxContext::root(), None)
421}
422
423macro_rules! out_of_file_lines_range {
425 ($self:ident, $span:expr) => {
426 !$self.config.file_lines().is_all()
427 && !$self
428 .config
429 .file_lines()
430 .intersects(&$self.psess.lookup_line_range($span))
431 };
432}
433
434macro_rules! skip_out_of_file_lines_range_err {
435 ($self:ident, $span:expr) => {
436 if out_of_file_lines_range!($self, $span) {
437 return Err(RewriteError::SkipFormatting);
438 }
439 };
440}
441
442macro_rules! skip_out_of_file_lines_range_visitor {
443 ($self:ident, $span:expr) => {
444 if out_of_file_lines_range!($self, $span) {
445 $self.push_rewrite($span, None);
446 return;
447 }
448 };
449}
450
451pub(crate) fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
454 if filtered_str_fits(&s, max_width, shape) {
455 Some(s)
456 } else {
457 None
458 }
459}
460
461pub(crate) fn filtered_str_fits(snippet: &str, max_width: usize, shape: Shape) -> bool {
462 let snippet = &filter_normal_code(snippet);
463 if !snippet.is_empty() {
464 if first_line_width(snippet) > shape.width {
466 return false;
467 }
468 if is_single_line(snippet) {
470 return true;
471 }
472 if snippet
474 .lines()
475 .skip(1)
476 .any(|line| unicode_str_width(line) > max_width)
477 {
478 return false;
479 }
480 if last_line_width(snippet) > shape.used_width() + shape.width {
483 return false;
484 }
485 }
486 true
487}
488
489#[inline]
490pub(crate) fn colon_spaces(config: &Config) -> &'static str {
491 let before = config.space_before_colon();
492 let after = config.space_after_colon();
493 match (before, after) {
494 (true, true) => " : ",
495 (true, false) => " :",
496 (false, true) => ": ",
497 (false, false) => ":",
498 }
499}
500
501#[inline]
502pub(crate) fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
503 match e.kind {
504 ast::ExprKind::Call(ref e, _)
505 | ast::ExprKind::Binary(_, ref e, _)
506 | ast::ExprKind::Cast(ref e, _)
507 | ast::ExprKind::Type(ref e, _)
508 | ast::ExprKind::Assign(ref e, _, _)
509 | ast::ExprKind::AssignOp(_, ref e, _)
510 | ast::ExprKind::Field(ref e, _)
511 | ast::ExprKind::Index(ref e, _, _)
512 | ast::ExprKind::Range(Some(ref e), _, _)
513 | ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
514 _ => e,
515 }
516}
517
518#[inline]
519pub(crate) fn starts_with_newline(s: &str) -> bool {
520 s.starts_with('\n') || s.starts_with("\r\n")
521}
522
523#[inline]
524pub(crate) fn first_line_ends_with(s: &str, c: char) -> bool {
525 s.lines().next().map_or(false, |l| l.ends_with(c))
526}
527
528pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr: &str) -> bool {
531 match expr.kind {
532 ast::ExprKind::MacCall(..)
533 | ast::ExprKind::FormatArgs(..)
534 | ast::ExprKind::Call(..)
535 | ast::ExprKind::MethodCall(..)
536 | ast::ExprKind::Array(..)
537 | ast::ExprKind::Struct(..)
538 | ast::ExprKind::While(..)
539 | ast::ExprKind::If(..)
540 | ast::ExprKind::Block(..)
541 | ast::ExprKind::ConstBlock(..)
542 | ast::ExprKind::Gen(..)
543 | ast::ExprKind::Loop(..)
544 | ast::ExprKind::ForLoop { .. }
545 | ast::ExprKind::TryBlock(..)
546 | ast::ExprKind::Match(..) => repr.contains('\n'),
547 ast::ExprKind::Paren(ref expr)
548 | ast::ExprKind::Binary(_, _, ref expr)
549 | ast::ExprKind::Index(_, ref expr, _)
550 | ast::ExprKind::Unary(_, ref expr)
551 | ast::ExprKind::Try(ref expr)
552 | ast::ExprKind::Yield(YieldKind::Prefix(Some(ref expr)))
553 | ast::ExprKind::DirectConstArg(ref expr) => is_block_expr(context, expr, repr),
554 ast::ExprKind::Closure(ref closure) => is_block_expr(context, &closure.body, repr),
555 ast::ExprKind::Lit(_) => {
557 repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces()
558 }
559 ast::ExprKind::AddrOf(..)
560 | ast::ExprKind::Assign(..)
561 | ast::ExprKind::AssignOp(..)
562 | ast::ExprKind::Await(..)
563 | ast::ExprKind::Break(..)
564 | ast::ExprKind::Cast(..)
565 | ast::ExprKind::Continue(..)
566 | ast::ExprKind::Dummy
567 | ast::ExprKind::Err(_)
568 | ast::ExprKind::Field(..)
569 | ast::ExprKind::IncludedBytes(..)
570 | ast::ExprKind::InlineAsm(..)
571 | ast::ExprKind::Move(..)
572 | ast::ExprKind::OffsetOf(..)
573 | ast::ExprKind::UnsafeBinderCast(..)
574 | ast::ExprKind::Let(..)
575 | ast::ExprKind::Path(..)
576 | ast::ExprKind::Range(..)
577 | ast::ExprKind::Repeat(..)
578 | ast::ExprKind::Ret(..)
579 | ast::ExprKind::Become(..)
580 | ast::ExprKind::Yeet(..)
581 | ast::ExprKind::Tup(..)
582 | ast::ExprKind::Use(..)
583 | ast::ExprKind::Type(..)
584 | ast::ExprKind::Yield(..)
585 | ast::ExprKind::Underscore => false,
586 }
587}
588
589pub(crate) fn remove_trailing_white_spaces(text: &str) -> String {
592 let mut buffer = String::with_capacity(text.len());
593 let mut space_buffer = String::with_capacity(128);
594 for (char_kind, c) in CharClasses::new(text.chars()) {
595 match c {
596 '\n' => {
597 if char_kind == FullCodeCharKind::InString {
598 buffer.push_str(&space_buffer);
599 }
600 space_buffer.clear();
601 buffer.push('\n');
602 }
603 _ if c.is_whitespace() => {
604 space_buffer.push(c);
605 }
606 _ => {
607 if !space_buffer.is_empty() {
608 buffer.push_str(&space_buffer);
609 space_buffer.clear();
610 }
611 buffer.push(c);
612 }
613 }
614 }
615 buffer
616}
617
618pub(crate) fn trim_left_preserve_layout(
647 orig: &str,
648 indent: Indent,
649 config: &Config,
650) -> Option<String> {
651 let mut lines = LineClasses::new(orig);
652 let first_line = lines.next().map(|(_, s)| s.trim_end().to_owned())?;
653 let mut trimmed_lines = Vec::with_capacity(16);
654
655 let mut veto_trim = false;
656 let min_prefix_space_width = lines
657 .filter_map(|(kind, line)| {
658 let mut trimmed = true;
659 let prefix_space_width = if is_empty_line(&line) {
660 None
661 } else {
662 Some(get_prefix_space_width(config, &line))
663 };
664
665 let new_veto_trim_value = (kind == FullCodeCharKind::InString
667 || (config.style_edition() >= StyleEdition::Edition2024
668 && kind == FullCodeCharKind::InStringCommented))
669 && !line.ends_with('\\');
670 let line = if veto_trim || new_veto_trim_value {
671 veto_trim = new_veto_trim_value;
672 trimmed = false;
673 line
674 } else {
675 line.trim().to_owned()
676 };
677 trimmed_lines.push((trimmed, line, prefix_space_width));
678
679 match kind {
682 FullCodeCharKind::InStringCommented | FullCodeCharKind::EndStringCommented
683 if config.style_edition() >= StyleEdition::Edition2024 =>
684 {
685 None
686 }
687 FullCodeCharKind::InString | FullCodeCharKind::EndString => None,
688 _ => prefix_space_width,
689 }
690 })
691 .min()?;
692
693 Some(
694 first_line
695 + "\n"
696 + &trimmed_lines
697 .iter()
698 .map(
699 |&(trimmed, ref line, prefix_space_width)| match prefix_space_width {
700 _ if !trimmed => line.to_owned(),
701 Some(original_indent_width) => {
702 let new_indent_width = indent.width()
703 + original_indent_width.saturating_sub(min_prefix_space_width);
704 let new_indent = Indent::from_width(config, new_indent_width);
705 format!("{}{}", new_indent.to_string(config), line)
706 }
707 None => String::new(),
708 },
709 )
710 .collect::<Vec<_>>()
711 .join("\n"),
712 )
713}
714
715pub(crate) fn indent_next_line(kind: FullCodeCharKind, line: &str, config: &Config) -> bool {
720 if kind.is_string() {
721 config.format_strings() && line.ends_with('\\')
727 } else if config.style_edition() >= StyleEdition::Edition2024 {
728 !kind.is_commented_string()
729 } else {
730 true
731 }
732}
733
734pub(crate) fn is_empty_line(s: &str) -> bool {
735 s.is_empty() || s.chars().all(char::is_whitespace)
736}
737
738fn get_prefix_space_width(config: &Config, s: &str) -> usize {
739 let mut width = 0;
740 for c in s.chars() {
741 match c {
742 ' ' => width += 1,
743 '\t' => width += config.tab_spaces(),
744 _ => return width,
745 }
746 }
747 width
748}
749
750pub(crate) trait NodeIdExt {
751 fn root() -> Self;
752}
753
754impl NodeIdExt for NodeId {
755 fn root() -> NodeId {
756 NodeId::placeholder_from_expn_id(LocalExpnId::ROOT)
757 }
758}
759
760pub(crate) fn unicode_str_width(s: &str) -> usize {
761 s.width()
762}
763
764#[cfg(test)]
765mod test {
766 use super::*;
767
768 #[test]
769 fn test_remove_trailing_white_spaces() {
770 let s = " r#\"\n test\n \"#";
771 assert_eq!(remove_trailing_white_spaces(s), s);
772 }
773
774 #[test]
775 fn test_trim_left_preserve_layout() {
776 let s = "aaa\n\tbbb\n ccc";
777 let config = Config::default();
778 let indent = Indent::new(4, 0);
779 assert_eq!(
780 trim_left_preserve_layout(s, indent, &config),
781 Some("aaa\n bbb\n ccc".to_string())
782 );
783 }
784}