1 // A generic trait to abstract the rewriting of an element (of the AST).
3 use std::cell::{Cell, RefCell};
9 use crate::config::{Config, IndentStyle};
10 use crate::shape::Shape;
11 use crate::skip::SkipContext;
12 use crate::syntux::session::ParseSess;
13 use crate::visitor::SnippetProvider;
14 use crate::FormatReport;
16 pub(crate) trait Rewrite {
17 /// Rewrite self into shape.
18 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>;
21 impl<T: Rewrite> Rewrite for ptr::P<T> {
22 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
23 (**self).rewrite(context, shape)
28 pub(crate) struct RewriteContext<'a> {
29 pub(crate) parse_sess: &'a ParseSess,
30 pub(crate) config: &'a Config,
31 pub(crate) inside_macro: Rc<Cell<bool>>,
32 // Force block indent style even if we are using visual indent style.
33 pub(crate) use_block: Cell<bool>,
34 // When `is_if_else_block` is true, unindent the comment on top
35 // of the `else` or `else if`.
36 pub(crate) is_if_else_block: Cell<bool>,
37 // When rewriting chain, veto going multi line except the last element
38 pub(crate) force_one_line_chain: Cell<bool>,
39 pub(crate) snippet_provider: &'a SnippetProvider,
40 // Used for `format_snippet`
41 pub(crate) macro_rewrite_failure: Cell<bool>,
42 pub(crate) is_macro_def: bool,
43 pub(crate) report: FormatReport,
44 pub(crate) skip_context: SkipContext,
45 pub(crate) skipped_range: Rc<RefCell<Vec<(usize, usize)>>>,
48 pub(crate) struct InsideMacroGuard {
49 is_nested_macro_context: bool,
50 inside_macro_ref: Rc<Cell<bool>>,
53 impl InsideMacroGuard {
54 pub(crate) fn is_nested(&self) -> bool {
55 self.is_nested_macro_context
59 impl Drop for InsideMacroGuard {
61 self.inside_macro_ref.replace(self.is_nested_macro_context);
65 impl<'a> RewriteContext<'a> {
66 pub(crate) fn snippet(&self, span: Span) -> &str {
67 self.snippet_provider.span_to_snippet(span).unwrap()
70 /// Returns `true` if we should use block indent style for rewriting function call.
71 pub(crate) fn use_block_indent(&self) -> bool {
72 self.config.indent_style() == IndentStyle::Block || self.use_block.get()
75 pub(crate) fn budget(&self, used_width: usize) -> usize {
76 self.config.max_width().saturating_sub(used_width)
79 pub(crate) fn inside_macro(&self) -> bool {
80 self.inside_macro.get()
83 pub(crate) fn enter_macro(&self) -> InsideMacroGuard {
84 let is_nested_macro_context = self.inside_macro.replace(true);
86 is_nested_macro_context,
87 inside_macro_ref: self.inside_macro.clone(),
91 pub(crate) fn leave_macro(&self) {
92 self.inside_macro.replace(false);
95 pub(crate) fn is_if_else_block(&self) -> bool {
96 self.is_if_else_block.get()