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.
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.
11 // A generic trait to abstract the rewriting of an element (of the AST).
13 use syntax::parse::ParseSess;
15 use syntax::source_map::{SourceMap, Span};
17 use config::{Config, IndentStyle};
19 use visitor::SnippetProvider;
22 use std::cell::RefCell;
25 /// Rewrite self into shape.
26 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String>;
29 impl<T: Rewrite> Rewrite for ptr::P<T> {
30 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
31 (**self).rewrite(context, shape)
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,
54 impl<'a> RewriteContext<'a> {
55 pub fn snippet(&self, span: Span) -> &str {
56 self.snippet_provider.span_to_snippet(span).unwrap()
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()
64 pub fn budget(&self, used_width: usize) -> usize {
65 self.config.max_width().saturating_sub(used_width)
68 pub fn inside_macro(&self) -> bool {
69 *self.inside_macro.borrow()
72 pub fn is_if_else_block(&self) -> bool {
73 *self.is_if_else_block.borrow()