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 | ast::ExprKind::DirectConstArg(ref expr) => is_block_expr(context, expr, repr),
537 ast::ExprKind::Closure(ref closure) => is_block_expr(context, &closure.body, repr),
538 ast::ExprKind::Lit(_) => {
540 repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces()
541 }
542 ast::ExprKind::AddrOf(..)
543 | ast::ExprKind::Assign(..)
544 | ast::ExprKind::AssignOp(..)
545 | ast::ExprKind::Await(..)
546 | ast::ExprKind::Break(..)
547 | ast::ExprKind::Cast(..)
548 | ast::ExprKind::Continue(..)
549 | ast::ExprKind::Dummy
550 | ast::ExprKind::Err(_)
551 | ast::ExprKind::Field(..)
552 | ast::ExprKind::IncludedBytes(..)
553 | ast::ExprKind::InlineAsm(..)
554 | ast::ExprKind::Move(..)
555 | ast::ExprKind::OffsetOf(..)
556 | ast::ExprKind::UnsafeBinderCast(..)
557 | ast::ExprKind::Let(..)
558 | ast::ExprKind::Path(..)
559 | ast::ExprKind::Range(..)
560 | ast::ExprKind::Repeat(..)
561 | ast::ExprKind::Ret(..)
562 | ast::ExprKind::Become(..)
563 | ast::ExprKind::Yeet(..)
564 | ast::ExprKind::Tup(..)
565 | ast::ExprKind::Use(..)
566 | ast::ExprKind::Type(..)
567 | ast::ExprKind::Yield(..)
568 | ast::ExprKind::Underscore => false,
569 }
570}
571
572pub(crate) fn remove_trailing_white_spaces(text: &str) -> String {
575 let mut buffer = String::with_capacity(text.len());
576 let mut space_buffer = String::with_capacity(128);
577 for (char_kind, c) in CharClasses::new(text.chars()) {
578 match c {
579 '\n' => {
580 if char_kind == FullCodeCharKind::InString {
581 buffer.push_str(&space_buffer);
582 }
583 space_buffer.clear();
584 buffer.push('\n');
585 }
586 _ if c.is_whitespace() => {
587 space_buffer.push(c);
588 }
589 _ => {
590 if !space_buffer.is_empty() {
591 buffer.push_str(&space_buffer);
592 space_buffer.clear();
593 }
594 buffer.push(c);
595 }
596 }
597 }
598 buffer
599}
600
601pub(crate) fn trim_left_preserve_layout(
630 orig: &str,
631 indent: Indent,
632 config: &Config,
633) -> Option<String> {
634 let mut lines = LineClasses::new(orig);
635 let first_line = lines.next().map(|(_, s)| s.trim_end().to_owned())?;
636 let mut trimmed_lines = Vec::with_capacity(16);
637
638 let mut veto_trim = false;
639 let min_prefix_space_width = lines
640 .filter_map(|(kind, line)| {
641 let mut trimmed = true;
642 let prefix_space_width = if is_empty_line(&line) {
643 None
644 } else {
645 Some(get_prefix_space_width(config, &line))
646 };
647
648 let new_veto_trim_value = (kind == FullCodeCharKind::InString
650 || (config.style_edition() >= StyleEdition::Edition2024
651 && kind == FullCodeCharKind::InStringCommented))
652 && !line.ends_with('\\');
653 let line = if veto_trim || new_veto_trim_value {
654 veto_trim = new_veto_trim_value;
655 trimmed = false;
656 line
657 } else {
658 line.trim().to_owned()
659 };
660 trimmed_lines.push((trimmed, line, prefix_space_width));
661
662 match kind {
665 FullCodeCharKind::InStringCommented | FullCodeCharKind::EndStringCommented
666 if config.style_edition() >= StyleEdition::Edition2024 =>
667 {
668 None
669 }
670 FullCodeCharKind::InString | FullCodeCharKind::EndString => None,
671 _ => prefix_space_width,
672 }
673 })
674 .min()?;
675
676 Some(
677 first_line
678 + "\n"
679 + &trimmed_lines
680 .iter()
681 .map(
682 |&(trimmed, ref line, prefix_space_width)| match prefix_space_width {
683 _ if !trimmed => line.to_owned(),
684 Some(original_indent_width) => {
685 let new_indent_width = indent.width()
686 + original_indent_width.saturating_sub(min_prefix_space_width);
687 let new_indent = Indent::from_width(config, new_indent_width);
688 format!("{}{}", new_indent.to_string(config), line)
689 }
690 None => String::new(),
691 },
692 )
693 .collect::<Vec<_>>()
694 .join("\n"),
695 )
696}
697
698pub(crate) fn indent_next_line(kind: FullCodeCharKind, line: &str, config: &Config) -> bool {
703 if kind.is_string() {
704 config.format_strings() && line.ends_with('\\')
710 } else if config.style_edition() >= StyleEdition::Edition2024 {
711 !kind.is_commented_string()
712 } else {
713 true
714 }
715}
716
717pub(crate) fn is_empty_line(s: &str) -> bool {
718 s.is_empty() || s.chars().all(char::is_whitespace)
719}
720
721fn get_prefix_space_width(config: &Config, s: &str) -> usize {
722 let mut width = 0;
723 for c in s.chars() {
724 match c {
725 ' ' => width += 1,
726 '\t' => width += config.tab_spaces(),
727 _ => return width,
728 }
729 }
730 width
731}
732
733pub(crate) trait NodeIdExt {
734 fn root() -> Self;
735}
736
737impl NodeIdExt for NodeId {
738 fn root() -> NodeId {
739 NodeId::placeholder_from_expn_id(LocalExpnId::ROOT)
740 }
741}
742
743pub(crate) fn unicode_str_width(s: &str) -> usize {
744 s.width()
745}
746
747#[cfg(test)]
748mod test {
749 use super::*;
750
751 #[test]
752 fn test_remove_trailing_white_spaces() {
753 let s = " r#\"\n test\n \"#";
754 assert_eq!(remove_trailing_white_spaces(s), s);
755 }
756
757 #[test]
758 fn test_trim_left_preserve_layout() {
759 let s = "aaa\n\tbbb\n ccc";
760 let config = Config::default();
761 let indent = Indent::new(4, 0);
762 assert_eq!(
763 trim_left_preserve_layout(s, indent, &config),
764 Some("aaa\n bbb\n ccc".to_string())
765 );
766 }
767}