Skip to content

Remove global mutable config to allow for concurrency #112

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 23, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions src/changes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use std::fs::File;
use std::io::{Write, stdout};
use WriteMode;
use NewlineStyle;
use config::Config;
use utils::round_up_to_power_of_two;

// This is basically a wrapper around a bunch of Ropes which makes it convenient
Expand Down Expand Up @@ -130,11 +131,12 @@ impl<'a> ChangeSet<'a> {
}

pub fn write_all_files(&self,
mode: WriteMode)
mode: WriteMode,
config: &Config)
-> Result<(HashMap<String, String>), ::std::io::Error> {
let mut result = HashMap::new();
for filename in self.file_map.keys() {
let one_result = try!(self.write_file(filename, mode));
let one_result = try!(self.write_file(filename, mode, config));
if let Some(r) = one_result {
result.insert(filename.clone(), r);
}
Expand All @@ -145,18 +147,20 @@ impl<'a> ChangeSet<'a> {

pub fn write_file(&self,
filename: &str,
mode: WriteMode)
mode: WriteMode,
config: &Config)
-> Result<Option<String>, ::std::io::Error> {
let text = &self.file_map[filename];

// prints all newlines either as `\n` or as `\r\n`
fn write_system_newlines<T>(
mut writer: T,
text: &StringBuffer)
text: &StringBuffer,
config: &Config)
-> Result<(), ::std::io::Error>
where T: Write,
{
match config!(newline_style) {
match config.newline_style {
NewlineStyle::Unix => write!(writer, "{}", text),
NewlineStyle::Windows => {
for (c, _) in text.chars() {
Expand All @@ -181,7 +185,7 @@ impl<'a> ChangeSet<'a> {
{
// Write text to temp file
let tmp_file = try!(File::create(&tmp_name));
try!(write_system_newlines(tmp_file, text));
try!(write_system_newlines(tmp_file, text, config));
}

try!(::std::fs::rename(filename, bk_name));
Expand All @@ -190,18 +194,18 @@ impl<'a> ChangeSet<'a> {
WriteMode::NewFile(extn) => {
let filename = filename.to_owned() + "." + extn;
let file = try!(File::create(&filename));
try!(write_system_newlines(file, text));
try!(write_system_newlines(file, text, config));
}
WriteMode::Display => {
println!("{}:\n", filename);
let stdout = stdout();
let stdout_lock = stdout.lock();
try!(write_system_newlines(stdout_lock, text));
try!(write_system_newlines(stdout_lock, text, config));
}
WriteMode::Return(_) => {
// io::Write is not implemented for String, working around with Vec<u8>
let mut v = Vec::new();
try!(write_system_newlines(&mut v, text));
try!(write_system_newlines(&mut v, text, config));
// won't panic, we are writing correct utf8
return Ok(Some(String::from_utf8(v).unwrap()));
}
Expand Down
16 changes: 2 additions & 14 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use {NewlineStyle, BraceStyle, ReturnIndent};
use lists::SeparatorTactic;
use issues::ReportTactic;

#[derive(RustcDecodable)]
#[derive(RustcDecodable, Clone)]
pub struct Config {
pub max_width: usize,
pub ideal_width: usize,
Expand All @@ -32,20 +32,8 @@ pub struct Config {
}

impl Config {
fn from_toml(toml: &str) -> Config {
pub fn from_toml(toml: &str) -> Config {
let parsed = toml.parse().unwrap();
toml::decode(parsed).unwrap()
}
}

pub fn set_config(toml: &str) {
unsafe {
::CONFIG = Some(Config::from_toml(toml));
}
}

macro_rules! config {
($name: ident) => {
unsafe { ::CONFIG.as_ref().unwrap().$name }
};
}
8 changes: 4 additions & 4 deletions src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ fn rewrite_string_lit(context: &RewriteContext, s: &str, span: Span, width: usiz
// strings, or if the string is too long for the line.
let l_loc = context.codemap.lookup_char_pos(span.lo);
let r_loc = context.codemap.lookup_char_pos(span.hi);
if l_loc.line == r_loc.line && r_loc.col.to_usize() <= config!(max_width) {
if l_loc.line == r_loc.line && r_loc.col.to_usize() <= context.config.max_width {
return context.codemap.span_to_snippet(span).ok();
}

Expand All @@ -82,7 +82,7 @@ fn rewrite_string_lit(context: &RewriteContext, s: &str, span: Span, width: usiz
// First line.
width - 2 // 2 = " + \
} else {
config!(max_width) - offset - 1 // 1 = either \ or ;
context.config.max_width - offset - 1 // 1 = either \ or ;
};

let mut cur_end = cur_start + max_chars;
Expand Down Expand Up @@ -206,7 +206,7 @@ fn rewrite_struct_lit(context: &RewriteContext,
trailing_separator: if base.is_some() {
SeparatorTactic::Never
} else {
config!(struct_lit_trailing_comma)
context.config.struct_lit_trailing_comma
},
indent: indent,
h_width: budget,
Expand Down Expand Up @@ -247,7 +247,7 @@ fn rewrite_tuple_lit(context: &RewriteContext,
let rem_width = if i == items.len() - 1 {
width - 2
} else {
config!(max_width) - indent - 2
context.config.max_width - indent - 2
};
item.rewrite(context, rem_width, indent)
})
Expand Down
44 changes: 22 additions & 22 deletions src/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ impl<'a> FmtVisitor<'a> {

// Check if vertical layout was forced by compute_budget_for_args.
if one_line_budget <= 0 {
if config!(fn_args_paren_newline) {
if self.config.fn_args_paren_newline {
result.push('\n');
result.push_str(&make_indent(arg_indent));
arg_indent = arg_indent + 1; // extra space for `(`
Expand All @@ -170,8 +170,8 @@ impl<'a> FmtVisitor<'a> {
// If we've already gone multi-line, or the return type would push
// over the max width, then put the return type on a new line.
if result.contains("\n") ||
result.len() + indent + ret_str.len() > config!(max_width) {
let indent = match config!(fn_return_indent) {
result.len() + indent + ret_str.len() > self.config.max_width {
let indent = match self.config.fn_return_indent {
ReturnIndent::WithWhereClause => indent + 4,
// TODO we might want to check that using the arg indent doesn't
// blow our budget, and if it does, then fallback to the where
Expand Down Expand Up @@ -363,15 +363,15 @@ impl<'a> FmtVisitor<'a> {
if !newline_brace {
used_space += 2;
}
let one_line_budget = if used_space > config!(max_width) {
let one_line_budget = if used_space > self.config.max_width {
0
} else {
config!(max_width) - used_space
self.config.max_width - used_space
};

// 2 = `()`
let used_space = indent + result.len() + 2;
let max_space = config!(ideal_width) + config!(leeway);
let max_space = self.config.ideal_width + self.config.leeway;
debug!("compute_budgets_for_args: used_space: {}, max_space: {}",
used_space, max_space);
if used_space < max_space {
Expand All @@ -383,9 +383,9 @@ impl<'a> FmtVisitor<'a> {

// Didn't work. we must force vertical layout and put args on a newline.
if let None = budgets {
let new_indent = indent + config!(tab_spaces);
let new_indent = indent + self.config.tab_spaces;
let used_space = new_indent + 2; // account for `(` and `)`
let max_space = config!(ideal_width) + config!(leeway);
let max_space = self.config.ideal_width + self.config.leeway;
if used_space > max_space {
// Whoops! bankrupt.
// TODO take evasive action, perhaps kill the indent or something.
Expand All @@ -398,7 +398,7 @@ impl<'a> FmtVisitor<'a> {
}

fn newline_for_brace(&self, where_clause: &ast::WhereClause) -> bool {
match config!(fn_brace_style) {
match self.config.fn_brace_style {
BraceStyle::AlwaysNextLine => true,
BraceStyle::SameLineWhere if where_clause.predicates.len() > 0 => true,
_ => false,
Expand All @@ -421,7 +421,7 @@ impl<'a> FmtVisitor<'a> {
self.changes.push_str_span(span, &generics_str);

self.last_pos = body_start;
self.block_indent += config!(tab_spaces);
self.block_indent += self.config.tab_spaces;
for (i, f) in enum_def.variants.iter().enumerate() {
let next_span_start: BytePos = if i == enum_def.variants.len() - 1 {
span.hi
Expand All @@ -431,7 +431,7 @@ impl<'a> FmtVisitor<'a> {

self.visit_variant(f, i == enum_def.variants.len() - 1, next_span_start);
}
self.block_indent -= config!(tab_spaces);
self.block_indent -= self.config.tab_spaces;

self.format_missing_with_indent(span.lo + BytePos(enum_snippet.rfind('}').unwrap() as u32));
self.changes.push_str_span(span, "}");
Expand Down Expand Up @@ -478,8 +478,8 @@ impl<'a> FmtVisitor<'a> {
+ field.node.name.to_string().len()
+ 1; // 1 = (

let comma_cost = if config!(enum_trailing_comma) { 1 } else { 0 };
let budget = config!(ideal_width) - indent - comma_cost - 1; // 1 = )
let comma_cost = if self.config.enum_trailing_comma { 1 } else { 0 };
let budget = self.config.ideal_width - indent - comma_cost - 1; // 1 = )

let fmt = ListFormatting {
tactic: ListTactic::HorizontalVertical,
Expand All @@ -500,13 +500,13 @@ impl<'a> FmtVisitor<'a> {

// Make sure we do not exceed column limit
// 4 = " = ,"
assert!(config!(max_width) >= vis.len() + name.len() + expr_snippet.len() + 4,
assert!(self.config.max_width >= vis.len() + name.len() + expr_snippet.len() + 4,
"Enum variant exceeded column limit");
}

self.changes.push_str_span(field.span, &result);

if !last_field || config!(enum_trailing_comma) {
if !last_field || self.config.enum_trailing_comma {
self.changes.push_str_span(field.span, ",");
}
}
Expand Down Expand Up @@ -543,11 +543,11 @@ impl<'a> FmtVisitor<'a> {
// This will drop the comment in between the header and body.
self.last_pos = span.lo + BytePos(struct_snippet.find_uncommented("{").unwrap() as u32 + 1);

self.block_indent += config!(tab_spaces);
self.block_indent += self.config.tab_spaces;
for (i, f) in struct_def.fields.iter().enumerate() {
self.visit_field(f, i == struct_def.fields.len() - 1, span.lo, &struct_snippet);
}
self.block_indent -= config!(tab_spaces);
self.block_indent -= self.config.tab_spaces;

self.format_missing_with_indent(span.lo + BytePos(struct_snippet.rfind('}').unwrap() as u32));
self.changes.push_str_span(span, "}");
Expand Down Expand Up @@ -608,21 +608,21 @@ impl<'a> FmtVisitor<'a> {

let mut field_str = match name {
Some(name) => {
let budget = config!(ideal_width) - self.block_indent;
let budget = self.config.ideal_width - self.block_indent;
// 3 is being conservative and assuming that there will be a trailing comma.
if self.block_indent + vis.len() + name.len() + typ.len() + 3 > budget {
format!("{}{}:\n{}{}",
vis,
name,
&make_indent(self.block_indent + config!(tab_spaces)),
&make_indent(self.block_indent + self.config.tab_spaces),
typ)
} else {
format!("{}{}: {}", vis, name, typ)
}
}
None => format!("{}{}", vis, typ),
};
if !last_field || config!(struct_trailing_comma) {
if !last_field || self.config.struct_trailing_comma {
field_str.push(',');
}
self.changes.push_str_span(field.span, &field_str);
Expand All @@ -647,7 +647,7 @@ impl<'a> FmtVisitor<'a> {
return result;
}

let budget = config!(max_width) - indent - 2;
let budget = self.config.max_width - indent - 2;
// TODO might need to insert a newline if the generics are really long
result.push('<');

Expand Down Expand Up @@ -723,7 +723,7 @@ impl<'a> FmtVisitor<'a> {
.zip(comments.into_iter())
.collect();

let budget = config!(ideal_width) + config!(leeway) - indent - 10;
let budget = self.config.ideal_width + self.config.leeway - indent - 10;
let fmt = ListFormatting {
tactic: ListTactic::Vertical,
separator: ",",
Expand Down
Loading