]> git.lizzy.rs Git - rust.git/blob - src/rewrite.rs
rewrite_string: retain blank lines that are trailing
[rust.git] / src / rewrite.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // A generic trait to abstract the rewriting of an element (of the AST).
12
13 use syntax::parse::ParseSess;
14 use syntax::ptr;
15 use syntax::source_map::{SourceMap, Span};
16
17 use config::{Config, IndentStyle};
18 use shape::Shape;
19 use visitor::SnippetProvider;
20 use FormatReport;
21
22 use std::cell::RefCell;
23
24 pub trait Rewrite {
25     /// Rewrite self into shape.
26     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String>;
27 }
28
29 impl<T: Rewrite> Rewrite for ptr::P<T> {
30     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
31         (**self).rewrite(context, shape)
32     }
33 }
34
35 #[derive(Clone)]
36 pub struct RewriteContext<'a> {
37     pub parse_session: &'a ParseSess,
38     pub source_map: &'a SourceMap,
39     pub config: &'a Config,
40     pub inside_macro: RefCell<bool>,
41     // Force block indent style even if we are using visual indent style.
42     pub use_block: RefCell<bool>,
43     // When `format_if_else_cond_comment` is true, unindent the comment on top
44     // of the `else` or `else if`.
45     pub is_if_else_block: RefCell<bool>,
46     // When rewriting chain, veto going multi line except the last element
47     pub force_one_line_chain: RefCell<bool>,
48     pub snippet_provider: &'a SnippetProvider<'a>,
49     // Used for `format_snippet`
50     pub(crate) macro_rewrite_failure: RefCell<bool>,
51     pub(crate) report: FormatReport,
52 }
53
54 impl<'a> RewriteContext<'a> {
55     pub fn snippet(&self, span: Span) -> &str {
56         self.snippet_provider.span_to_snippet(span).unwrap()
57     }
58
59     /// Return true if we should use block indent style for rewriting function call.
60     pub fn use_block_indent(&self) -> bool {
61         self.config.indent_style() == IndentStyle::Block || *self.use_block.borrow()
62     }
63
64     pub fn budget(&self, used_width: usize) -> usize {
65         self.config.max_width().saturating_sub(used_width)
66     }
67
68     pub fn inside_macro(&self) -> bool {
69         *self.inside_macro.borrow()
70     }
71
72     pub fn is_if_else_block(&self) -> bool {
73         *self.is_if_else_block.borrow()
74     }
75 }