1use std::borrow::Cow;
2
3use rustc_ast::YieldKind;
4use rustc_ast::ast::{
5 self, Attribute, MetaItem, MetaItemInner, MetaItemKind, NodeId, Path, Visibility,
6 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
77#[inline]
78pub(crate) fn format_coro(coroutine_kind: &ast::CoroutineKind) -> &'static str {
79 match coroutine_kind {
80 ast::CoroutineKind::Async { .. } => "async ",
81 ast::CoroutineKind::Gen { .. } => "gen ",
82 ast::CoroutineKind::AsyncGen { .. } => "async gen ",
83 }
84}
85
86#[inline]
87pub(crate) fn format_constness(constness: ast::Const) -> &'static str {
88 match constness {
89 ast::Const::Yes(..) => "const ",
90 ast::Const::No => "",
91 }
92}
93
94#[inline]
95pub(crate) fn format_constness_right(constness: ast::Const) -> &'static str {
96 match constness {
97 ast::Const::Yes(..) => " const",
98 ast::Const::No => "",
99 }
100}
101
102#[inline]
103pub(crate) fn format_defaultness(defaultness: ast::Defaultness) -> &'static str {
104 match defaultness {
105 ast::Defaultness::Implicit => "",
106 ast::Defaultness::Default(..) => "default ",
107 ast::Defaultness::Final(..) => "final ",
108 }
109}
110
111#[inline]
112pub(crate) fn format_safety(unsafety: ast::Safety) -> &'static str {
113 match unsafety {
114 ast::Safety::Unsafe(..) => "unsafe ",
115 ast::Safety::Safe(..) => "safe ",
116 ast::Safety::Default => "",
117 }
118}
119
120#[inline]
121pub(crate) fn format_auto(is_auto: ast::IsAuto) -> &'static str {
122 match is_auto {
123 ast::IsAuto::Yes => "auto ",
124 ast::IsAuto::No => "",
125 }
126}
127
128#[inline]
129pub(crate) fn format_mutability(mutability: ast::Mutability) -> &'static str {
130 match mutability {
131 ast::Mutability::Mut => "mut ",
132 ast::Mutability::Not => "",
133 }
134}
135
136#[inline]
137pub(crate) fn format_pinnedness_and_mutability(
138 pinnedness: ast::Pinnedness,
139 mutability: ast::Mutability,
140) -> (&'static str, &'static str) {
141 match (pinnedness, mutability) {
142 (ast::Pinnedness::Pinned, ast::Mutability::Mut) => ("pin ", "mut "),
143 (ast::Pinnedness::Pinned, ast::Mutability::Not) => ("pin ", "const "),
144 (ast::Pinnedness::Not, ast::Mutability::Mut) => ("", "mut "),
145 (ast::Pinnedness::Not, ast::Mutability::Not) => ("", ""),
146 }
147}
148
149#[inline]
150pub(crate) fn format_extern(ext: ast::Extern, explicit_abi: bool) -> Cow<'static, str> {
151 match ext {
152 ast::Extern::None => Cow::from(""),
153 ast::Extern::Implicit(_) if explicit_abi => Cow::from("extern \"C\" "),
154 ast::Extern::Implicit(_) => Cow::from("extern "),
155 ast::Extern::Explicit(abi, _) if abi.symbol_unescaped == sym::C && !explicit_abi => {
157 Cow::from("extern ")
158 }
159 ast::Extern::Explicit(abi, _) => {
160 Cow::from(format!(r#"extern "{}" "#, abi.symbol_unescaped))
161 }
162 }
163}
164
165#[inline]
166pub(crate) fn ptr_vec_to_ref_vec<T>(vec: &[Box<T>]) -> Vec<&T> {
168 vec.iter().map(|x| &**x).collect::<Vec<_>>()
169}
170
171#[inline]
172pub(crate) fn filter_attributes(
173 attrs: &[ast::Attribute],
174 style: ast::AttrStyle,
175) -> Vec<ast::Attribute> {
176 attrs
177 .iter()
178 .filter(|a| a.style == style)
179 .cloned()
180 .collect::<Vec<_>>()
181}
182
183#[inline]
184pub(crate) fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
185 filter_attributes(attrs, ast::AttrStyle::Inner)
186}
187
188#[inline]
189pub(crate) fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
190 filter_attributes(attrs, ast::AttrStyle::Outer)
191}
192
193#[inline]
194pub(crate) fn is_single_line(s: &str) -> bool {
195 !s.chars().any(|c| c == '\n')
196}
197
198#[inline]
199pub(crate) fn first_line_contains_single_line_comment(s: &str) -> bool {
200 s.lines().next().map_or(false, |l| l.contains("//"))
201}
202
203#[inline]
204pub(crate) fn last_line_contains_single_line_comment(s: &str) -> bool {
205 s.lines().last().map_or(false, |l| l.contains("//"))
206}
207
208#[inline]
209pub(crate) fn is_attributes_extendable(attrs_str: &str) -> bool {
210 !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
211}
212
213#[inline]
215pub(crate) fn first_line_width(s: &str) -> usize {
216 unicode_str_width(s.splitn(2, '\n').next().unwrap_or(""))
217}
218
219#[inline]
221pub(crate) fn last_line_width(s: &str) -> usize {
222 unicode_str_width(s.rsplitn(2, '\n').next().unwrap_or(""))
223}
224
225#[inline]
227pub(crate) fn last_line_used_width(s: &str, offset: usize) -> usize {
228 if s.contains('\n') {
229 last_line_width(s)
230 } else {
231 offset + unicode_str_width(s)
232 }
233}
234
235#[inline]
236pub(crate) fn trimmed_last_line_width(s: &str) -> usize {
237 unicode_str_width(match s.rfind('\n') {
238 Some(n) => s[(n + 1)..].trim(),
239 None => s.trim(),
240 })
241}
242
243#[inline]
244pub(crate) fn last_line_extendable(s: &str) -> bool {
245 if s.ends_with("\"#") {
246 return true;
247 }
248 for c in s.chars().rev() {
249 match c {
250 '(' | ')' | ']' | '}' | '?' | '>' => continue,
251 '\n' => break,
252 _ if c.is_whitespace() => continue,
253 _ => return false,
254 }
255 }
256 true
257}
258
259#[inline]
260fn is_skip(meta_item: &MetaItem) -> bool {
261 match meta_item.kind {
262 MetaItemKind::Word => {
263 let path_str = pprust::path_to_string(&meta_item.path);
264 path_str == skip_annotation().as_str() || path_str == depr_skip_annotation().as_str()
265 }
266 MetaItemKind::List(ref l) => {
267 meta_item.has_name(sym::cfg_attr) && l.len() == 2 && is_skip_nested(&l[1])
268 }
269 _ => false,
270 }
271}
272
273#[inline]
274fn is_skip_nested(meta_item: &MetaItemInner) -> bool {
275 match meta_item {
276 MetaItemInner::MetaItem(ref mi) => is_skip(mi),
277 MetaItemInner::Lit(_) => false,
278 }
279}
280
281#[inline]
282pub(crate) fn contains_skip(attrs: &[Attribute]) -> bool {
283 attrs
284 .iter()
285 .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
286}
287
288#[inline]
289pub(crate) fn semicolon_for_expr(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
290 if context.is_macro_def {
294 return false;
295 }
296
297 match expr.kind {
298 ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
299 context.config.trailing_semicolon()
300 }
301 _ => false,
302 }
303}
304
305#[inline]
306pub(crate) fn semicolon_for_stmt(
307 context: &RewriteContext<'_>,
308 stmt: &ast::Stmt,
309 is_last_expr: bool,
310) -> bool {
311 match stmt.kind {
312 ast::StmtKind::Semi(ref expr) => match expr.kind {
313 ast::ExprKind::While(..) | ast::ExprKind::Loop(..) | ast::ExprKind::ForLoop { .. } => {
314 false
315 }
316 ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
317 context.config.trailing_semicolon() || !is_last_expr
320 }
321 _ => true,
322 },
323 ast::StmtKind::Expr(..) => false,
324 _ => true,
325 }
326}
327
328#[inline]
329pub(crate) fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
330 match stmt.kind {
331 ast::StmtKind::Expr(ref expr) => Some(expr),
332 _ => None,
333 }
334}
335
336pub(crate) fn count_lf_crlf(input: &str) -> (usize, usize) {
338 let mut lf = 0;
339 let mut crlf = 0;
340 let mut is_crlf = false;
341 for c in input.as_bytes() {
342 match c {
343 b'\r' => is_crlf = true,
344 b'\n' if is_crlf => crlf += 1,
345 b'\n' => lf += 1,
346 _ => is_crlf = false,
347 }
348 }
349 (lf, crlf)
350}
351
352pub(crate) fn count_newlines(input: &str) -> usize {
353 bytecount::count(input.as_bytes(), b'\n')
355}
356
357macro_rules! source {
360 ($this:ident, $sp:expr) => {
361 $sp.source_callsite()
362 };
363}
364
365pub(crate) fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
366 Span::new(lo, hi, SyntaxContext::root(), None)
367}
368
369pub(crate) fn mk_sp_lo_plus_one(lo: BytePos) -> Span {
370 Span::new(lo, lo + BytePos(1), SyntaxContext::root(), None)
371}
372
373macro_rules! out_of_file_lines_range {
375 ($self:ident, $span:expr) => {
376 !$self.config.file_lines().is_all()
377 && !$self
378 .config
379 .file_lines()
380 .intersects(&$self.psess.lookup_line_range($span))
381 };
382}
383
384macro_rules! skip_out_of_file_lines_range_err {
385 ($self:ident, $span:expr) => {
386 if out_of_file_lines_range!($self, $span) {
387 return Err(RewriteError::SkipFormatting);
388 }
389 };
390}
391
392macro_rules! skip_out_of_file_lines_range_visitor {
393 ($self:ident, $span:expr) => {
394 if out_of_file_lines_range!($self, $span) {
395 $self.push_rewrite($span, None);
396 return;
397 }
398 };
399}
400
401pub(crate) fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
404 if filtered_str_fits(&s, max_width, shape) {
405 Some(s)
406 } else {
407 None
408 }
409}
410
411pub(crate) fn filtered_str_fits(snippet: &str, max_width: usize, shape: Shape) -> bool {
412 let snippet = &filter_normal_code(snippet);
413 if !snippet.is_empty() {
414 if first_line_width(snippet) > shape.width {
416 return false;
417 }
418 if is_single_line(snippet) {
420 return true;
421 }
422 if snippet
424 .lines()
425 .skip(1)
426 .any(|line| unicode_str_width(line) > max_width)
427 {
428 return false;
429 }
430 if last_line_width(snippet) > shape.used_width() + shape.width {
433 return false;
434 }
435 }
436 true
437}
438
439#[inline]
440pub(crate) fn colon_spaces(config: &Config) -> &'static str {
441 let before = config.space_before_colon();
442 let after = config.space_after_colon();
443 match (before, after) {
444 (true, true) => " : ",
445 (true, false) => " :",
446 (false, true) => ": ",
447 (false, false) => ":",
448 }
449}
450
451#[inline]
452pub(crate) fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
453 match e.kind {
454 ast::ExprKind::Call(ref e, _)
455 | ast::ExprKind::Binary(_, ref e, _)
456 | ast::ExprKind::Cast(ref e, _)
457 | ast::ExprKind::Type(ref e, _)
458 | ast::ExprKind::Assign(ref e, _, _)
459 | ast::ExprKind::AssignOp(_, ref e, _)
460 | ast::ExprKind::Field(ref e, _)
461 | ast::ExprKind::Index(ref e, _, _)
462 | ast::ExprKind::Range(Some(ref e), _, _)
463 | ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
464 _ => e,
465 }
466}
467
468#[inline]
469pub(crate) fn starts_with_newline(s: &str) -> bool {
470 s.starts_with('\n') || s.starts_with("\r\n")
471}
472
473#[inline]
474pub(crate) fn first_line_ends_with(s: &str, c: char) -> bool {
475 s.lines().next().map_or(false, |l| l.ends_with(c))
476}
477
478pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr: &str) -> bool {
481 match expr.kind {
482 ast::ExprKind::MacCall(..)
483 | ast::ExprKind::FormatArgs(..)
484 | ast::ExprKind::Call(..)
485 | ast::ExprKind::MethodCall(..)
486 | ast::ExprKind::Array(..)
487 | ast::ExprKind::Struct(..)
488 | ast::ExprKind::While(..)
489 | ast::ExprKind::If(..)
490 | ast::ExprKind::Block(..)
491 | ast::ExprKind::ConstBlock(..)
492 | ast::ExprKind::Gen(..)
493 | ast::ExprKind::Loop(..)
494 | ast::ExprKind::ForLoop { .. }
495 | ast::ExprKind::TryBlock(..)
496 | ast::ExprKind::Match(..) => repr.contains('\n'),
497 ast::ExprKind::Paren(ref expr)
498 | ast::ExprKind::Binary(_, _, ref expr)
499 | ast::ExprKind::Index(_, ref expr, _)
500 | ast::ExprKind::Unary(_, ref expr)
501 | ast::ExprKind::Try(ref expr)
502 | ast::ExprKind::Yield(YieldKind::Prefix(Some(ref expr))) => {
503 is_block_expr(context, expr, repr)
504 }
505 ast::ExprKind::Closure(ref closure) => is_block_expr(context, &closure.body, repr),
506 ast::ExprKind::Lit(_) => {
508 repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces()
509 }
510 ast::ExprKind::AddrOf(..)
511 | ast::ExprKind::Assign(..)
512 | ast::ExprKind::AssignOp(..)
513 | ast::ExprKind::Await(..)
514 | ast::ExprKind::Break(..)
515 | ast::ExprKind::Cast(..)
516 | ast::ExprKind::Continue(..)
517 | ast::ExprKind::Dummy
518 | ast::ExprKind::Err(_)
519 | ast::ExprKind::Field(..)
520 | ast::ExprKind::IncludedBytes(..)
521 | ast::ExprKind::InlineAsm(..)
522 | ast::ExprKind::OffsetOf(..)
523 | ast::ExprKind::UnsafeBinderCast(..)
524 | ast::ExprKind::Let(..)
525 | ast::ExprKind::Path(..)
526 | ast::ExprKind::Range(..)
527 | ast::ExprKind::Repeat(..)
528 | ast::ExprKind::Ret(..)
529 | ast::ExprKind::Become(..)
530 | ast::ExprKind::Yeet(..)
531 | ast::ExprKind::Tup(..)
532 | ast::ExprKind::Use(..)
533 | ast::ExprKind::Type(..)
534 | ast::ExprKind::Yield(..)
535 | ast::ExprKind::Underscore => false,
536 }
537}
538
539pub(crate) fn remove_trailing_white_spaces(text: &str) -> String {
542 let mut buffer = String::with_capacity(text.len());
543 let mut space_buffer = String::with_capacity(128);
544 for (char_kind, c) in CharClasses::new(text.chars()) {
545 match c {
546 '\n' => {
547 if char_kind == FullCodeCharKind::InString {
548 buffer.push_str(&space_buffer);
549 }
550 space_buffer.clear();
551 buffer.push('\n');
552 }
553 _ if c.is_whitespace() => {
554 space_buffer.push(c);
555 }
556 _ => {
557 if !space_buffer.is_empty() {
558 buffer.push_str(&space_buffer);
559 space_buffer.clear();
560 }
561 buffer.push(c);
562 }
563 }
564 }
565 buffer
566}
567
568pub(crate) fn trim_left_preserve_layout(
597 orig: &str,
598 indent: Indent,
599 config: &Config,
600) -> Option<String> {
601 let mut lines = LineClasses::new(orig);
602 let first_line = lines.next().map(|(_, s)| s.trim_end().to_owned())?;
603 let mut trimmed_lines = Vec::with_capacity(16);
604
605 let mut veto_trim = false;
606 let min_prefix_space_width = lines
607 .filter_map(|(kind, line)| {
608 let mut trimmed = true;
609 let prefix_space_width = if is_empty_line(&line) {
610 None
611 } else {
612 Some(get_prefix_space_width(config, &line))
613 };
614
615 let new_veto_trim_value = (kind == FullCodeCharKind::InString
617 || (config.style_edition() >= StyleEdition::Edition2024
618 && kind == FullCodeCharKind::InStringCommented))
619 && !line.ends_with('\\');
620 let line = if veto_trim || new_veto_trim_value {
621 veto_trim = new_veto_trim_value;
622 trimmed = false;
623 line
624 } else {
625 line.trim().to_owned()
626 };
627 trimmed_lines.push((trimmed, line, prefix_space_width));
628
629 match kind {
632 FullCodeCharKind::InStringCommented | FullCodeCharKind::EndStringCommented
633 if config.style_edition() >= StyleEdition::Edition2024 =>
634 {
635 None
636 }
637 FullCodeCharKind::InString | FullCodeCharKind::EndString => None,
638 _ => prefix_space_width,
639 }
640 })
641 .min()?;
642
643 Some(
644 first_line
645 + "\n"
646 + &trimmed_lines
647 .iter()
648 .map(
649 |&(trimmed, ref line, prefix_space_width)| match prefix_space_width {
650 _ if !trimmed => line.to_owned(),
651 Some(original_indent_width) => {
652 let new_indent_width = indent.width()
653 + original_indent_width.saturating_sub(min_prefix_space_width);
654 let new_indent = Indent::from_width(config, new_indent_width);
655 format!("{}{}", new_indent.to_string(config), line)
656 }
657 None => String::new(),
658 },
659 )
660 .collect::<Vec<_>>()
661 .join("\n"),
662 )
663}
664
665pub(crate) fn indent_next_line(kind: FullCodeCharKind, line: &str, config: &Config) -> bool {
670 if kind.is_string() {
671 config.format_strings() && line.ends_with('\\')
677 } else if config.style_edition() >= StyleEdition::Edition2024 {
678 !kind.is_commented_string()
679 } else {
680 true
681 }
682}
683
684pub(crate) fn is_empty_line(s: &str) -> bool {
685 s.is_empty() || s.chars().all(char::is_whitespace)
686}
687
688fn get_prefix_space_width(config: &Config, s: &str) -> usize {
689 let mut width = 0;
690 for c in s.chars() {
691 match c {
692 ' ' => width += 1,
693 '\t' => width += config.tab_spaces(),
694 _ => return width,
695 }
696 }
697 width
698}
699
700pub(crate) trait NodeIdExt {
701 fn root() -> Self;
702}
703
704impl NodeIdExt for NodeId {
705 fn root() -> NodeId {
706 NodeId::placeholder_from_expn_id(LocalExpnId::ROOT)
707 }
708}
709
710pub(crate) fn unicode_str_width(s: &str) -> usize {
711 s.width()
712}
713
714#[cfg(test)]
715mod test {
716 use super::*;
717
718 #[test]
719 fn test_remove_trailing_white_spaces() {
720 let s = " r#\"\n test\n \"#";
721 assert_eq!(remove_trailing_white_spaces(s), s);
722 }
723
724 #[test]
725 fn test_trim_left_preserve_layout() {
726 let s = "aaa\n\tbbb\n ccc";
727 let config = Config::default();
728 let indent = Indent::new(4, 0);
729 assert_eq!(
730 trim_left_preserve_layout(s, indent, &config),
731 Some("aaa\n bbb\n ccc".to_string())
732 );
733 }
734}