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