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