1 // A generic trait to abstract the rewriting of an element (of the AST).
3 use std::cell::RefCell;
5 use syntax::parse::ParseSess;
7 use syntax::source_map::{SourceMap, Span};
9 use crate::config::{Config, IndentStyle};
10 use crate::shape::Shape;
11 use crate::visitor::SnippetProvider;
12 use crate::FormatReport;
15 /// Rewrite self into shape.
16 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>;
19 impl<T: Rewrite> Rewrite for ptr::P<T> {
20 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
21 (**self).rewrite(context, shape)
26 pub struct RewriteContext<'a> {
27 pub parse_session: &'a ParseSess,
28 pub source_map: &'a SourceMap,
29 pub config: &'a Config,
30 pub inside_macro: RefCell<bool>,
31 // Force block indent style even if we are using visual indent style.
32 pub use_block: RefCell<bool>,
33 // When `is_if_else_block` is true, unindent the comment on top
34 // of the `else` or `else if`.
35 pub is_if_else_block: RefCell<bool>,
36 // When rewriting chain, veto going multi line except the last element
37 pub force_one_line_chain: RefCell<bool>,
38 pub snippet_provider: &'a SnippetProvider<'a>,
39 // Used for `format_snippet`
40 pub(crate) macro_rewrite_failure: RefCell<bool>,
41 pub(crate) report: FormatReport,
42 pub skip_macro_names: RefCell<Vec<String>>,
45 impl<'a> RewriteContext<'a> {
46 pub fn snippet(&self, span: Span) -> &str {
47 self.snippet_provider.span_to_snippet(span).unwrap()
50 /// Returns `true` if we should use block indent style for rewriting function call.
51 pub fn use_block_indent(&self) -> bool {
52 self.config.indent_style() == IndentStyle::Block || *self.use_block.borrow()
55 pub fn budget(&self, used_width: usize) -> usize {
56 self.config.max_width().saturating_sub(used_width)
59 pub fn inside_macro(&self) -> bool {
60 *self.inside_macro.borrow()
63 pub fn is_if_else_block(&self) -> bool {
64 *self.is_if_else_block.borrow()