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_range_end(end: ast::RangeEnd) -> &'static str {
184 match end {
185 ast::RangeEnd::Included(ast::RangeSyntax::DotDotDot) => "...",
186 ast::RangeEnd::Included(ast::RangeSyntax::DotDotEq) => "..=",
187 ast::RangeEnd::Excluded => "..",
188 }
189}
190
191#[inline]
192pub(crate) fn format_extern(ext: ast::Extern, explicit_abi: bool) -> Cow<'static, str> {
193 match ext {
194 ast::Extern::None => Cow::from(""),
195 ast::Extern::Implicit(_) if explicit_abi => Cow::from("extern \"C\" "),
196 ast::Extern::Implicit(_) => Cow::from("extern "),
197 ast::Extern::Explicit(abi, _) if abi.symbol_unescaped == sym::C && !explicit_abi => {
199 Cow::from("extern ")
200 }
201 ast::Extern::Explicit(abi, _) => {
202 Cow::from(format!(r#"extern "{}" "#, abi.symbol_unescaped))
203 }
204 }
205}
206
207#[inline]
208pub(crate) fn ptr_vec_to_ref_vec<T>(vec: &[Box<T>]) -> Vec<&T> {
210 vec.iter().map(|x| &**x).collect::<Vec<_>>()
211}
212
213#[inline]
214pub(crate) fn filter_attributes(
215 attrs: &[ast::Attribute],
216 style: ast::AttrStyle,
217) -> Vec<ast::Attribute> {
218 attrs
219 .iter()
220 .filter(|a| a.style == style)
221 .cloned()
222 .collect::<Vec<_>>()
223}
224
225#[inline]
226pub(crate) fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
227 filter_attributes(attrs, ast::AttrStyle::Inner)
228}
229
230#[inline]
231pub(crate) fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
232 filter_attributes(attrs, ast::AttrStyle::Outer)
233}
234
235#[inline]
236pub(crate) fn is_single_line(s: &str) -> bool {
237 !s.chars().any(|c| c == '\n')
238}
239
240#[inline]
241pub(crate) fn first_line_contains_single_line_comment(s: &str) -> bool {
242 s.lines().next().map_or(false, |l| l.contains("//"))
243}
244
245#[inline]
246pub(crate) fn last_line_contains_single_line_comment(s: &str) -> bool {
247 s.lines().last().map_or(false, |l| l.contains("//"))
248}
249
250#[inline]
251pub(crate) fn is_attributes_extendable(attrs_str: &str) -> bool {
252 !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
253}
254
255#[inline]
257pub(crate) fn first_line_width(s: &str) -> usize {
258 unicode_str_width(s.splitn(2, '\n').next().unwrap_or(""))
259}
260
261#[inline]
263pub(crate) fn last_line_width(s: &str) -> usize {
264 unicode_str_width(s.rsplitn(2, '\n').next().unwrap_or(""))
265}
266
267#[inline]
269pub(crate) fn last_line_used_width(s: &str, offset: usize) -> usize {
270 if s.contains('\n') {
271 last_line_width(s)
272 } else {
273 offset + unicode_str_width(s)
274 }
275}
276
277#[inline]
278pub(crate) fn trimmed_last_line_width(s: &str) -> usize {
279 unicode_str_width(match s.rfind('\n') {
280 Some(n) => s[(n + 1)..].trim(),
281 None => s.trim(),
282 })
283}
284
285#[inline]
286pub(crate) fn last_line_extendable(s: &str) -> bool {
287 if s.ends_with("\"#") {
288 return true;
289 }
290 for c in s.chars().rev() {
291 match c {
292 '(' | ')' | ']' | '}' | '?' | '>' => continue,
293 '\n' => break,
294 _ if c.is_whitespace() => continue,
295 _ => return false,
296 }
297 }
298 true
299}
300
301#[inline]
302fn is_skip(meta_item: &MetaItem) -> bool {
303 match meta_item.kind {
304 MetaItemKind::Word => {
305 let path_str = pprust::path_to_string(&meta_item.path);
306 path_str == skip_annotation().as_str() || path_str == depr_skip_annotation().as_str()
307 }
308 MetaItemKind::List(ref l) => {
309 meta_item.has_name(sym::cfg_attr) && l.len() == 2 && is_skip_nested(&l[1])
310 }
311 _ => false,
312 }
313}
314
315#[inline]
316fn is_skip_nested(meta_item: &MetaItemInner) -> bool {
317 match meta_item {
318 MetaItemInner::MetaItem(ref mi) => is_skip(mi),
319 MetaItemInner::Lit(_) => false,
320 }
321}
322
323#[inline]
324pub(crate) fn contains_skip(attrs: &[Attribute]) -> bool {
325 attrs
326 .iter()
327 .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
328}
329
330#[inline]
331pub(crate) fn semicolon_for_expr(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
332 if context.is_macro_def {
336 return false;
337 }
338
339 match expr.kind {
340 ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
341 context.config.trailing_semicolon()
342 }
343 _ => false,
344 }
345}
346
347#[inline]
348pub(crate) fn semicolon_for_stmt(
349 context: &RewriteContext<'_>,
350 stmt: &ast::Stmt,
351 is_last_expr: bool,
352) -> bool {
353 match stmt.kind {
354 ast::StmtKind::Semi(ref expr) => match expr.kind {
355 ast::ExprKind::While(..) | ast::ExprKind::Loop(..) | ast::ExprKind::ForLoop { .. } => {
356 false
357 }
358 ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
359 context.config.trailing_semicolon() || !is_last_expr
362 }
363 _ => true,
364 },
365 ast::StmtKind::Expr(..) => false,
366 _ => true,
367 }
368}
369
370#[inline]
371pub(crate) fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
372 match stmt.kind {
373 ast::StmtKind::Expr(ref expr) => Some(expr),
374 _ => None,
375 }
376}
377
378pub(crate) fn count_lf_crlf(input: &str) -> (usize, usize) {
380 let mut lf = 0;
381 let mut crlf = 0;
382 let mut is_crlf = false;
383 for c in input.as_bytes() {
384 match c {
385 b'\r' => is_crlf = true,
386 b'\n' if is_crlf => crlf += 1,
387 b'\n' => lf += 1,
388 _ => is_crlf = false,
389 }
390 }
391 (lf, crlf)
392}
393
394pub(crate) fn count_newlines(input: &str) -> usize {
395 bytecount::count(input.as_bytes(), b'\n')
397}
398
399macro_rules! source {
402 ($this:ident, $sp:expr) => {
403 $sp.source_callsite()
404 };
405}
406
407pub(crate) fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
408 Span::new(lo, hi, SyntaxContext::root(), None)
409}
410
411pub(crate) fn mk_sp_lo_plus_one(lo: BytePos) -> Span {
412 Span::new(lo, lo + BytePos(1), SyntaxContext::root(), None)
413}
414
415macro_rules! out_of_file_lines_range {
417 ($self:ident, $span:expr) => {
418 !$self.config.file_lines().is_all()
419 && !$self
420 .config
421 .file_lines()
422 .intersects(&$self.psess.lookup_line_range($span))
423 };
424}
425
426macro_rules! skip_out_of_file_lines_range_err {
427 ($self:ident, $span:expr) => {
428 if out_of_file_lines_range!($self, $span) {
429 return Err(RewriteError::SkipFormatting);
430 }
431 };
432}
433
434macro_rules! skip_out_of_file_lines_range_visitor {
435 ($self:ident, $span:expr) => {
436 if out_of_file_lines_range!($self, $span) {
437 $self.push_rewrite($span, None);
438 return;
439 }
440 };
441}
442
443pub(crate) fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
446 if filtered_str_fits(&s, max_width, shape) {
447 Some(s)
448 } else {
449 None
450 }
451}
452
453pub(crate) fn filtered_str_fits(snippet: &str, max_width: usize, shape: Shape) -> bool {
454 let snippet = &filter_normal_code(snippet);
455 if !snippet.is_empty() {
456 if first_line_width(snippet) > shape.width {
458 return false;
459 }
460 if is_single_line(snippet) {
462 return true;
463 }
464 if snippet
466 .lines()
467 .skip(1)
468 .any(|line| unicode_str_width(line) > max_width)
469 {
470 return false;
471 }
472 if last_line_width(snippet) > shape.used_width() + shape.width {
475 return false;
476 }
477 }
478 true
479}
480
481#[inline]
482pub(crate) fn colon_spaces(config: &Config) -> &'static str {
483 let before = config.space_before_colon();
484 let after = config.space_after_colon();
485 match (before, after) {
486 (true, true) => " : ",
487 (true, false) => " :",
488 (false, true) => ": ",
489 (false, false) => ":",
490 }
491}
492
493#[inline]
494pub(crate) fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
495 match e.kind {
496 ast::ExprKind::Call(ref e, _)
497 | ast::ExprKind::Binary(_, ref e, _)
498 | ast::ExprKind::Cast(ref e, _)
499 | ast::ExprKind::Type(ref e, _)
500 | ast::ExprKind::Assign(ref e, _, _)
501 | ast::ExprKind::AssignOp(_, ref e, _)
502 | ast::ExprKind::Field(ref e, _)
503 | ast::ExprKind::Index(ref e, _, _)
504 | ast::ExprKind::Range(Some(ref e), _, _)
505 | ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
506 _ => e,
507 }
508}
509
510#[inline]
511pub(crate) fn starts_with_newline(s: &str) -> bool {
512 s.starts_with('\n') || s.starts_with("\r\n")
513}
514
515#[inline]
516pub(crate) fn first_line_ends_with(s: &str, c: char) -> bool {
517 s.lines().next().map_or(false, |l| l.ends_with(c))
518}
519
520pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr: &str) -> bool {
523 match expr.kind {
524 ast::ExprKind::MacCall(..)
525 | ast::ExprKind::FormatArgs(..)
526 | ast::ExprKind::Call(..)
527 | ast::ExprKind::MethodCall(..)
528 | ast::ExprKind::Array(..)
529 | ast::ExprKind::Struct(..)
530 | ast::ExprKind::While(..)
531 | ast::ExprKind::If(..)
532 | ast::ExprKind::Block(..)
533 | ast::ExprKind::ConstBlock(..)
534 | ast::ExprKind::Gen(..)
535 | ast::ExprKind::Loop(..)
536 | ast::ExprKind::ForLoop { .. }
537 | ast::ExprKind::TryBlock(..)
538 | ast::ExprKind::Match(..) => repr.contains('\n'),
539 ast::ExprKind::Paren(ref expr)
540 | ast::ExprKind::Binary(_, _, ref expr)
541 | ast::ExprKind::Index(_, ref expr, _)
542 | ast::ExprKind::Unary(_, ref expr)
543 | ast::ExprKind::Try(ref expr)
544 | ast::ExprKind::Yield(YieldKind::Prefix(Some(ref expr)))
545 | ast::ExprKind::DirectConstArg(ref expr) => is_block_expr(context, expr, repr),
546 ast::ExprKind::Closure(ref closure) => is_block_expr(context, &closure.body, repr),
547 ast::ExprKind::Lit(_) => {
549 repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces()
550 }
551 ast::ExprKind::AddrOf(..)
552 | ast::ExprKind::Assign(..)
553 | ast::ExprKind::AssignOp(..)
554 | ast::ExprKind::Await(..)
555 | ast::ExprKind::Break(..)
556 | ast::ExprKind::Cast(..)
557 | ast::ExprKind::Continue(..)
558 | ast::ExprKind::Dummy
559 | ast::ExprKind::Err(_)
560 | ast::ExprKind::Field(..)
561 | ast::ExprKind::IncludedBytes(..)
562 | ast::ExprKind::InlineAsm(..)
563 | ast::ExprKind::Move(..)
564 | ast::ExprKind::OffsetOf(..)
565 | ast::ExprKind::UnsafeBinderCast(..)
566 | ast::ExprKind::Let(..)
567 | ast::ExprKind::Path(..)
568 | ast::ExprKind::Range(..)
569 | ast::ExprKind::Repeat(..)
570 | ast::ExprKind::Ret(..)
571 | ast::ExprKind::Become(..)
572 | ast::ExprKind::Yeet(..)
573 | ast::ExprKind::Tup(..)
574 | ast::ExprKind::Use(..)
575 | ast::ExprKind::Type(..)
576 | ast::ExprKind::Yield(..)
577 | ast::ExprKind::Underscore => false,
578 }
579}
580
581pub(crate) fn remove_trailing_white_spaces(text: &str) -> String {
584 let mut buffer = String::with_capacity(text.len());
585 let mut space_buffer = String::with_capacity(128);
586 for (char_kind, c) in CharClasses::new(text.chars()) {
587 match c {
588 '\n' => {
589 if char_kind == FullCodeCharKind::InString {
590 buffer.push_str(&space_buffer);
591 }
592 space_buffer.clear();
593 buffer.push('\n');
594 }
595 _ if c.is_whitespace() => {
596 space_buffer.push(c);
597 }
598 _ => {
599 if !space_buffer.is_empty() {
600 buffer.push_str(&space_buffer);
601 space_buffer.clear();
602 }
603 buffer.push(c);
604 }
605 }
606 }
607 buffer
608}
609
610pub(crate) fn trim_left_preserve_layout(
639 orig: &str,
640 indent: Indent,
641 config: &Config,
642) -> Option<String> {
643 let mut lines = LineClasses::new(orig);
644 let first_line = lines.next().map(|(_, s)| s.trim_end().to_owned())?;
645 let mut trimmed_lines = Vec::with_capacity(16);
646
647 let mut veto_trim = false;
648 let min_prefix_space_width = lines
649 .filter_map(|(kind, line)| {
650 let mut trimmed = true;
651 let prefix_space_width = if is_empty_line(&line) {
652 None
653 } else {
654 Some(get_prefix_space_width(config, &line))
655 };
656
657 let new_veto_trim_value = (kind == FullCodeCharKind::InString
659 || (config.style_edition() >= StyleEdition::Edition2024
660 && kind == FullCodeCharKind::InStringCommented))
661 && !line.ends_with('\\');
662 let line = if veto_trim || new_veto_trim_value {
663 veto_trim = new_veto_trim_value;
664 trimmed = false;
665 line
666 } else {
667 line.trim().to_owned()
668 };
669 trimmed_lines.push((trimmed, line, prefix_space_width));
670
671 match kind {
674 FullCodeCharKind::InStringCommented | FullCodeCharKind::EndStringCommented
675 if config.style_edition() >= StyleEdition::Edition2024 =>
676 {
677 None
678 }
679 FullCodeCharKind::InString | FullCodeCharKind::EndString => None,
680 _ => prefix_space_width,
681 }
682 })
683 .min()?;
684
685 Some(
686 first_line
687 + "\n"
688 + &trimmed_lines
689 .iter()
690 .map(
691 |&(trimmed, ref line, prefix_space_width)| match prefix_space_width {
692 _ if !trimmed => line.to_owned(),
693 Some(original_indent_width) => {
694 let new_indent_width = indent.width()
695 + original_indent_width.saturating_sub(min_prefix_space_width);
696 let new_indent = Indent::from_width(config, new_indent_width);
697 format!("{}{}", new_indent.to_string(config), line)
698 }
699 None => String::new(),
700 },
701 )
702 .collect::<Vec<_>>()
703 .join("\n"),
704 )
705}
706
707pub(crate) fn indent_next_line(kind: FullCodeCharKind, line: &str, config: &Config) -> bool {
712 if kind.is_string() {
713 config.format_strings() && line.ends_with('\\')
719 } else if config.style_edition() >= StyleEdition::Edition2024 {
720 !kind.is_commented_string()
721 } else {
722 true
723 }
724}
725
726pub(crate) fn is_empty_line(s: &str) -> bool {
727 s.is_empty() || s.chars().all(char::is_whitespace)
728}
729
730fn get_prefix_space_width(config: &Config, s: &str) -> usize {
731 let mut width = 0;
732 for c in s.chars() {
733 match c {
734 ' ' => width += 1,
735 '\t' => width += config.tab_spaces(),
736 _ => return width,
737 }
738 }
739 width
740}
741
742pub(crate) trait NodeIdExt {
743 fn root() -> Self;
744}
745
746impl NodeIdExt for NodeId {
747 fn root() -> NodeId {
748 NodeId::placeholder_from_expn_id(LocalExpnId::ROOT)
749 }
750}
751
752pub(crate) fn unicode_str_width(s: &str) -> usize {
753 s.width()
754}
755
756#[cfg(test)]
757mod test {
758 use super::*;
759
760 #[test]
761 fn test_remove_trailing_white_spaces() {
762 let s = " r#\"\n test\n \"#";
763 assert_eq!(remove_trailing_white_spaces(s), s);
764 }
765
766 #[test]
767 fn test_trim_left_preserve_layout() {
768 let s = "aaa\n\tbbb\n ccc";
769 let config = Config::default();
770 let indent = Indent::new(4, 0);
771 assert_eq!(
772 trim_left_preserve_layout(s, indent, &config),
773 Some("aaa\n bbb\n ccc".to_string())
774 );
775 }
776}