]> git.lizzy.rs Git - rust.git/blob - src/rewrite.rs
Release 1.4.0
[rust.git] / src / rewrite.rs
1 // A generic trait to abstract the rewriting of an element (of the AST).
2
3 use std::cell::RefCell;
4
5 use syntax::parse::ParseSess;
6 use syntax::ptr;
7 use syntax::source_map::{SourceMap, Span};
8
9 use crate::config::{Config, IndentStyle};
10 use crate::shape::Shape;
11 use crate::skip::SkipContext;
12 use crate::visitor::SnippetProvider;
13 use crate::FormatReport;
14
15 pub(crate) trait Rewrite {
16     /// Rewrite self into shape.
17     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>;
18 }
19
20 impl<T: Rewrite> Rewrite for ptr::P<T> {
21     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
22         (**self).rewrite(context, shape)
23     }
24 }
25
26 #[derive(Clone)]
27 pub(crate) struct RewriteContext<'a> {
28     pub(crate) parse_session: &'a ParseSess,
29     pub(crate) source_map: &'a SourceMap,
30     pub(crate) config: &'a Config,
31     pub(crate) inside_macro: RefCell<bool>,
32     // Force block indent style even if we are using visual indent style.
33     pub(crate) use_block: RefCell<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: RefCell<bool>,
37     // When rewriting chain, veto going multi line except the last element
38     pub(crate) force_one_line_chain: RefCell<bool>,
39     pub(crate) snippet_provider: &'a SnippetProvider<'a>,
40     // Used for `format_snippet`
41     pub(crate) macro_rewrite_failure: RefCell<bool>,
42     pub(crate) report: FormatReport,
43     pub(crate) skip_context: SkipContext,
44 }
45
46 impl<'a> RewriteContext<'a> {
47     pub(crate) fn snippet(&self, span: Span) -> &str {
48         self.snippet_provider.span_to_snippet(span).unwrap()
49     }
50
51     /// Returns `true` if we should use block indent style for rewriting function call.
52     pub(crate) fn use_block_indent(&self) -> bool {
53         self.config.indent_style() == IndentStyle::Block || *self.use_block.borrow()
54     }
55
56     pub(crate) fn budget(&self, used_width: usize) -> usize {
57         self.config.max_width().saturating_sub(used_width)
58     }
59
60     pub(crate) fn inside_macro(&self) -> bool {
61         *self.inside_macro.borrow()
62     }
63
64     pub(crate) fn is_if_else_block(&self) -> bool {
65         *self.is_if_else_block.borrow()
66     }
67 }