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_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
84pub(crate) fn format_mut_restriction(
85 context: &RewriteContext<'_>,
86 mut_restriction: &MutRestriction,
87) -> String {
88 format_restriction("mut", context, &mut_restriction.kind)
89}
90
91fn format_restriction(
92 kw: &'static str,
93 context: &RewriteContext<'_>,
94 restriction: &RestrictionKind,
95) -> String {
96 match restriction {
97 RestrictionKind::Unrestricted => String::new(),
98 RestrictionKind::Restricted {
99 ref path,
100 id: _,
101 shorthand,
102 } => {
103 let Path { ref segments, .. } = **path;
104 let mut segments_iter = segments.iter().map(|seg| rewrite_ident(context, seg.ident));
105 if path.is_global() && segments_iter.next().is_none() {
106 panic!("non-global path in {kw}(restricted)?");
107 }
108 let path = itertools::join(segments_iter, "::");
111 let in_str = if *shorthand { "" } else { "in " };
112
113 format!("{kw}({in_str}{path}) ")
114 }
115 }
116}
117
118#[inline]
119pub(crate) fn format_coro(coroutine_kind: &ast::CoroutineKind) -> &'static str {
120 match coroutine_kind {
121 ast::CoroutineKind::Async { .. } => "async ",
122 ast::CoroutineKind::Gen { .. } => "gen ",
123 ast::CoroutineKind::AsyncGen { .. } => "async gen ",
124 }
125}
126
127#[inline]
128pub(crate) fn format_constness(constness: ast::Const) -> &'static str {
129 match constness {
130 ast::Const::Yes(..) => "const ",
131 ast::Const::No => "",
132 }
133}
134
135#[inline]
136pub(crate) fn format_defaultness(defaultness: ast::Defaultness) -> &'static str {
137 match defaultness {
138 ast::Defaultness::Implicit => "",
139 ast::Defaultness::Default(..) => "default ",
140 ast::Defaultness::Final(..) => "final ",
141 }
142}
143
144#[inline]
145pub(crate) fn format_safety(unsafety: ast::Safety) -> &'static str {
146 match unsafety {
147 ast::Safety::Unsafe(..) => "unsafe ",
148 ast::Safety::Safe(..) => "safe ",
149 ast::Safety::Default => "",
150 }
151}
152
153#[inline]
154pub(crate) fn format_auto(is_auto: ast::IsAuto) -> &'static str {
155 match is_auto {
156 ast::IsAuto::Yes => "auto ",
157 ast::IsAuto::No => "",
158 }
159}
160
161#[inline]
162pub(crate) fn format_mutability(mutability: ast::Mutability) -> &'static str {
163 match mutability {
164 ast::Mutability::Mut => "mut ",
165 ast::Mutability::Not => "",
166 }
167}
168
169#[inline]
170pub(crate) fn format_pinnedness_and_mutability(
171 pinnedness: ast::Pinnedness,
172 mutability: ast::Mutability,
173) -> (&'static str, &'static str) {
174 match (pinnedness, mutability) {
175 (ast::Pinnedness::Pinned, ast::Mutability::Mut) => ("pin ", "mut "),
176 (ast::Pinnedness::Pinned, ast::Mutability::Not) => ("pin ", "const "),
177 (ast::Pinnedness::Not, ast::Mutability::Mut) => ("", "mut "),
178 (ast::Pinnedness::Not, ast::Mutability::Not) => ("", ""),
179 }
180}
181
182#[inline]
183pub(crate) fn format_extern(ext: ast::Extern, explicit_abi: bool) -> Cow<'static, str> {
184 match ext {
185 ast::Extern::None => Cow::from(""),
186 ast::Extern::Implicit(_) if explicit_abi => Cow::from("extern \"C\" "),
187 ast::Extern::Implicit(_) => Cow::from("extern "),
188 ast::Extern::Explicit(abi, _) if abi.symbol_unescaped == sym::C && !explicit_abi => {
190 Cow::from("extern ")
191 }
192 ast::Extern::Explicit(abi, _) => {
193 Cow::from(format!(r#"extern "{}" "#, abi.symbol_unescaped))
194 }
195 }
196}
197
198#[inline]
199pub(crate) fn ptr_vec_to_ref_vec<T>(vec: &[Box<T>]) -> Vec<&T> {
201 vec.iter().map(|x| &**x).collect::<Vec<_>>()
202}
203
204#[inline]
205pub(crate) fn filter_attributes(
206 attrs: &[ast::Attribute],
207 style: ast::AttrStyle,
208) -> Vec<ast::Attribute> {
209 attrs
210 .iter()
211 .filter(|a| a.style == style)
212 .cloned()
213 .collect::<Vec<_>>()
214}
215
216#[inline]
217pub(crate) fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
218 filter_attributes(attrs, ast::AttrStyle::Inner)
219}
220
221#[inline]
222pub(crate) fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
223 filter_attributes(attrs, ast::AttrStyle::Outer)
224}
225
226#[inline]
227pub(crate) fn is_single_line(s: &str) -> bool {
228 !s.chars().any(|c| c == '\n')
229}
230
231#[inline]
232pub(crate) fn first_line_contains_single_line_comment(s: &str) -> bool {
233 s.lines().next().map_or(false, |l| l.contains("//"))
234}
235
236#[inline]
237pub(crate) fn last_line_contains_single_line_comment(s: &str) -> bool {
238 s.lines().last().map_or(false, |l| l.contains("//"))
239}
240
241#[inline]
242pub(crate) fn is_attributes_extendable(attrs_str: &str) -> bool {
243 !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
244}
245
246#[inline]
248pub(crate) fn first_line_width(s: &str) -> usize {
249 unicode_str_width(s.splitn(2, '\n').next().unwrap_or(""))
250}
251
252#[inline]
254pub(crate) fn last_line_width(s: &str) -> usize {
255 unicode_str_width(s.rsplitn(2, '\n').next().unwrap_or(""))
256}
257
258#[inline]
260pub(crate) fn last_line_used_width(s: &str, offset: usize) -> usize {
261 if s.contains('\n') {
262 last_line_width(s)
263 } else {
264 offset + unicode_str_width(s)
265 }
266}
267
268#[inline]
269pub(crate) fn trimmed_last_line_width(s: &str) -> usize {
270 unicode_str_width(match s.rfind('\n') {
271 Some(n) => s[(n + 1)..].trim(),
272 None => s.trim(),
273 })
274}
275
276#[inline]
277pub(crate) fn last_line_extendable(s: &str) -> bool {
278 if s.ends_with("\"#") {
279 return true;
280 }
281 for c in s.chars().rev() {
282 match c {
283 '(' | ')' | ']' | '}' | '?' | '>' => continue,
284 '\n' => break,
285 _ if c.is_whitespace() => continue,
286 _ => return false,
287 }
288 }
289 true
290}
291
292#[inline]
293fn is_skip(meta_item: &MetaItem) -> bool {
294 match meta_item.kind {
295 MetaItemKind::Word => {
296 let path_str = pprust::path_to_string(&meta_item.path);
297 path_str == skip_annotation().as_str() || path_str == depr_skip_annotation().as_str()
298 }
299 MetaItemKind::List(ref l) => {
300 meta_item.has_name(sym::cfg_attr) && l.len() == 2 && is_skip_nested(&l[1])
301 }
302 _ => false,
303 }
304}
305
306#[inline]
307fn is_skip_nested(meta_item: &MetaItemInner) -> bool {
308 match meta_item {
309 MetaItemInner::MetaItem(ref mi) => is_skip(mi),
310 MetaItemInner::Lit(_) => false,
311 }
312}
313
314#[inline]
315pub(crate) fn contains_skip(attrs: &[Attribute]) -> bool {
316 attrs
317 .iter()
318 .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
319}
320
321#[inline]
322pub(crate) fn semicolon_for_expr(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
323 if context.is_macro_def {
327 return false;
328 }
329
330 match expr.kind {
331 ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
332 context.config.trailing_semicolon()
333 }
334 _ => false,
335 }
336}
337
338#[inline]
339pub(crate) fn semicolon_for_stmt(
340 context: &RewriteContext<'_>,
341 stmt: &ast::Stmt,
342 is_last_expr: bool,
343) -> bool {
344 match stmt.kind {
345 ast::StmtKind::Semi(ref expr) => match expr.kind {
346 ast::ExprKind::While(..) | ast::ExprKind::Loop(..) | ast::ExprKind::ForLoop { .. } => {
347 false
348 }
349 ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
350 context.config.trailing_semicolon() || !is_last_expr
353 }
354 _ => true,
355 },
356 ast::StmtKind::Expr(..) => false,
357 _ => true,
358 }
359}
360
361#[inline]
362pub(crate) fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
363 match stmt.kind {
364 ast::StmtKind::Expr(ref expr) => Some(expr),
365 _ => None,
366 }
367}
368
369pub(crate) fn count_lf_crlf(input: &str) -> (usize, usize) {
371 let mut lf = 0;
372 let mut crlf = 0;
373 let mut is_crlf = false;
374 for c in input.as_bytes() {
375 match c {
376 b'\r' => is_crlf = true,
377 b'\n' if is_crlf => crlf += 1,
378 b'\n' => lf += 1,
379 _ => is_crlf = false,
380 }
381 }
382 (lf, crlf)
383}
384
385pub(crate) fn count_newlines(input: &str) -> usize {
386 bytecount::count(input.as_bytes(), b'\n')
388}
389
390macro_rules! source {
393 ($this:ident, $sp:expr) => {
394 $sp.source_callsite()
395 };
396}
397
398pub(crate) fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
399 Span::new(lo, hi, SyntaxContext::root(), None)
400}
401
402pub(crate) fn mk_sp_lo_plus_one(lo: BytePos) -> Span {
403 Span::new(lo, lo + BytePos(1), SyntaxContext::root(), None)
404}
405
406macro_rules! out_of_file_lines_range {
408 ($self:ident, $span:expr) => {
409 !$self.config.file_lines().is_all()
410 && !$self
411 .config
412 .file_lines()
413 .intersects(&$self.psess.lookup_line_range($span))
414 };
415}
416
417macro_rules! skip_out_of_file_lines_range_err {
418 ($self:ident, $span:expr) => {
419 if out_of_file_lines_range!($self, $span) {
420 return Err(RewriteError::SkipFormatting);
421 }
422 };
423}
424
425macro_rules! skip_out_of_file_lines_range_visitor {
426 ($self:ident, $span:expr) => {
427 if out_of_file_lines_range!($self, $span) {
428 $self.push_rewrite($span, None);
429 return;
430 }
431 };
432}
433
434pub(crate) fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
437 if filtered_str_fits(&s, max_width, shape) {
438 Some(s)
439 } else {
440 None
441 }
442}
443
444pub(crate) fn filtered_str_fits(snippet: &str, max_width: usize, shape: Shape) -> bool {
445 let snippet = &filter_normal_code(snippet);
446 if !snippet.is_empty() {
447 if first_line_width(snippet) > shape.width {
449 return false;
450 }
451 if is_single_line(snippet) {
453 return true;
454 }
455 if snippet
457 .lines()
458 .skip(1)
459 .any(|line| unicode_str_width(line) > max_width)
460 {
461 return false;
462 }
463 if last_line_width(snippet) > shape.used_width() + shape.width {
466 return false;
467 }
468 }
469 true
470}
471
472#[inline]
473pub(crate) fn colon_spaces(config: &Config) -> &'static str {
474 let before = config.space_before_colon();
475 let after = config.space_after_colon();
476 match (before, after) {
477 (true, true) => " : ",
478 (true, false) => " :",
479 (false, true) => ": ",
480 (false, false) => ":",
481 }
482}
483
484#[inline]
485pub(crate) fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
486 match e.kind {
487 ast::ExprKind::Call(ref e, _)
488 | ast::ExprKind::Binary(_, ref e, _)
489 | ast::ExprKind::Cast(ref e, _)
490 | ast::ExprKind::Type(ref e, _)
491 | ast::ExprKind::Assign(ref e, _, _)
492 | ast::ExprKind::AssignOp(_, ref e, _)
493 | ast::ExprKind::Field(ref e, _)
494 | ast::ExprKind::Index(ref e, _, _)
495 | ast::ExprKind::Range(Some(ref e), _, _)
496 | ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
497 _ => e,
498 }
499}
500
501#[inline]
502pub(crate) fn starts_with_newline(s: &str) -> bool {
503 s.starts_with('\n') || s.starts_with("\r\n")
504}
505
506#[inline]
507pub(crate) fn first_line_ends_with(s: &str, c: char) -> bool {
508 s.lines().next().map_or(false, |l| l.ends_with(c))
509}
510
511pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr: &str) -> bool {
514 match expr.kind {
515 ast::ExprKind::MacCall(..)
516 | ast::ExprKind::FormatArgs(..)
517 | ast::ExprKind::Call(..)
518 | ast::ExprKind::MethodCall(..)
519 | ast::ExprKind::Array(..)
520 | ast::ExprKind::Struct(..)
521 | ast::ExprKind::While(..)
522 | ast::ExprKind::If(..)
523 | ast::ExprKind::Block(..)
524 | ast::ExprKind::ConstBlock(..)
525 | ast::ExprKind::Gen(..)
526 | ast::ExprKind::Loop(..)
527 | ast::ExprKind::ForLoop { .. }
528 | ast::ExprKind::TryBlock(..)
529 | ast::ExprKind::Match(..) => repr.contains('\n'),
530 ast::ExprKind::Paren(ref expr)
531 | ast::ExprKind::Binary(_, _, ref expr)
532 | ast::ExprKind::Index(_, ref expr, _)
533 | ast::ExprKind::Unary(_, ref expr)
534 | ast::ExprKind::Try(ref expr)
535 | ast::ExprKind::Yield(YieldKind::Prefix(Some(ref expr))) => {
536 is_block_expr(context, expr, repr)
537 }
538 ast::ExprKind::Closure(ref closure) => is_block_expr(context, &closure.body, repr),
539 ast::ExprKind::Lit(_) => {
541 repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces()
542 }
543 ast::ExprKind::AddrOf(..)
544 | ast::ExprKind::Assign(..)
545 | ast::ExprKind::AssignOp(..)
546 | ast::ExprKind::Await(..)
547 | ast::ExprKind::Break(..)
548 | ast::ExprKind::Cast(..)
549 | ast::ExprKind::Continue(..)
550 | ast::ExprKind::Dummy
551 | ast::ExprKind::Err(_)
552 | ast::ExprKind::Field(..)
553 | ast::ExprKind::IncludedBytes(..)
554 | ast::ExprKind::InlineAsm(..)
555 | ast::ExprKind::Move(..)
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}