Skip to content
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

Reformat modules in external files #122

Merged
merged 4 commits into from
Jul 5, 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
29 changes: 13 additions & 16 deletions src/changes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,9 @@ pub struct ChangeSet<'a> {
impl<'a> ChangeSet<'a> {
// Create a new ChangeSet for a given libsyntax CodeMap.
pub fn from_codemap(codemap: &'a CodeMap) -> ChangeSet<'a> {
let mut result = ChangeSet {
file_map: HashMap::new(),
codemap: codemap,
file_spans: Vec::with_capacity(codemap.files.borrow().len()),
};
let mut result = ChangeSet { file_map: HashMap::new(),
codemap: codemap,
file_spans: Vec::with_capacity(codemap.files.borrow().len()), };

for f in codemap.files.borrow().iter() {
// Use the length of the file as a heuristic for how much space we
Expand Down Expand Up @@ -116,11 +114,7 @@ impl<'a> ChangeSet<'a> {

// Return an iterator over the entire changed text.
pub fn text<'c>(&'c self) -> FileIterator<'c, 'a> {
FileIterator {
change_set: self,
keys: self.file_map.keys().collect(),
cur_key: 0,
}
FileIterator { change_set: self, keys: self.file_map.keys().collect(), cur_key: 0 }
}

// Append a newline to the end of each file.
Expand Down Expand Up @@ -153,12 +147,11 @@ impl<'a> ChangeSet<'a> {
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,
config: &Config)
-> Result<(), ::std::io::Error>
where T: Write,
fn write_system_newlines<T>(mut writer: T,
text: &StringBuffer,
config: &Config)
-> Result<(), ::std::io::Error>
where T: Write
{
match config.newline_style {
NewlineStyle::Unix => write!(writer, "{}", text),
Expand Down Expand Up @@ -213,6 +206,10 @@ impl<'a> ChangeSet<'a> {

Ok(None)
}

pub fn is_changed(&self, filename: &str) -> bool {
self.file_map.get(filename).expect("Unknown filename").len != 0
}
}

// Iterates over each file in the ChangSet. Yields the filename and the changed
Expand Down
20 changes: 9 additions & 11 deletions src/comment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,13 @@ pub fn rewrite_comment(orig: &str, block_style: bool, width: usize, offset: usiz
let max_chars = width.checked_sub(closer.len()).unwrap_or(1)
.checked_sub(opener.len()).unwrap_or(1);

let fmt = StringFormat {
opener: "",
closer: "",
line_start: line_start,
line_end: "",
width: max_chars,
offset: offset + opener.len() - line_start.len(),
trim_end: true
};
let fmt = StringFormat { opener: "",
closer: "",
line_start: line_start,
line_end: "",
width: max_chars,
offset: offset + opener.len() - line_start.len(),
trim_end: true, };

let indent_str = make_indent(offset);
let line_breaks = s.chars().filter(|&c| c == '\n').count();
Expand Down Expand Up @@ -102,8 +100,8 @@ fn format_comments() {

let input = "// comment";
let expected_output = "/* com\n \
* men\n \
* t */";
* men\n \
* t */";
assert_eq!(expected_output, rewrite_comment(input, true, 9, 69));

assert_eq!("/* trimmed */", rewrite_comment("/* trimmed */", true, 100, 100));
Expand Down
85 changes: 42 additions & 43 deletions src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,23 +63,21 @@ fn rewrite_string_lit(context: &RewriteContext,
span: Span,
width: usize,
offset: usize)
-> Option<String> {
-> Option<String> {
// Check if there is anything to fix: we always try to fixup multi-line
// 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() <= context.config.max_width {
return context.codemap.span_to_snippet(span).ok();
}
let fmt = StringFormat {
opener: "\"",
closer: "\"",
line_start: " ",
line_end: "\\",
width: width,
offset: offset,
trim_end: false
};
let fmt = StringFormat { opener: "\"",
closer: "\"",
line_start: " ",
line_end: "\\",
width: width,
offset: offset,
trim_end: false, };

Some(rewrite_string(&s.escape_default(), &fmt))
}
Expand All @@ -90,7 +88,7 @@ fn rewrite_call(context: &RewriteContext,
span: Span,
width: usize,
offset: usize)
-> Option<String> {
-> Option<String> {
debug!("rewrite_call, width: {}, offset: {}", width, offset);

// TODO using byte lens instead of char lens (and probably all over the place too)
Expand Down Expand Up @@ -119,20 +117,22 @@ fn rewrite_call(context: &RewriteContext,
callee.span.hi + BytePos(1),
span.hi);

let fmt = ListFormatting {
tactic: ListTactic::HorizontalVertical,
separator: ",",
trailing_separator: SeparatorTactic::Never,
indent: offset,
h_width: remaining_width,
v_width: remaining_width,
ends_with_newline: true,
};
let fmt = ListFormatting { tactic: ListTactic::HorizontalVertical,
separator: ",",
trailing_separator: SeparatorTactic::Never,
indent: offset,
h_width: remaining_width,
v_width: remaining_width,
ends_with_newline: true, };

Some(format!("{}({})", callee_str, write_list(&items, &fmt)))
}

fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, width: usize, offset: usize) -> Option<String> {
fn rewrite_paren(context: &RewriteContext,
subexpr: &ast::Expr,
width: usize,
offset: usize)
-> Option<String> {
debug!("rewrite_paren, width: {}, offset: {}", width, offset);
// 1 is for opening paren, 2 is for opening+closing, we want to keep the closing
// paren on the same line as the subexpr
Expand All @@ -148,14 +148,13 @@ fn rewrite_struct_lit<'a>(context: &RewriteContext,
span: Span,
width: usize,
offset: usize)
-> Option<String>
{
-> Option<String> {
debug!("rewrite_struct_lit: width {}, offset {}", width, offset);
assert!(fields.len() > 0 || base.is_some());

enum StructLitField<'a> {
Regular(&'a ast::Field),
Base(&'a ast::Expr)
Base(&'a ast::Expr),
}

let path_str = pprust::path_to_string(path);
Expand Down Expand Up @@ -203,19 +202,17 @@ fn rewrite_struct_lit<'a>(context: &RewriteContext,
span_after(span, "{", context.codemap),
span.hi);

let fmt = ListFormatting {
tactic: ListTactic::HorizontalVertical,
separator: ",",
trailing_separator: if base.is_some() {
let fmt = ListFormatting { tactic: ListTactic::HorizontalVertical,
separator: ",",
trailing_separator: if base.is_some() {
SeparatorTactic::Never
} else {
context.config.struct_lit_trailing_comma
},
indent: indent,
h_width: budget,
v_width: budget,
ends_with_newline: true,
};
indent: indent,
h_width: budget,
v_width: budget,
ends_with_newline: true, };
let fields_str = write_list(&items, &fmt);
Some(format!("{} {{ {} }}", path_str, fields_str))

Expand All @@ -225,7 +222,11 @@ fn rewrite_struct_lit<'a>(context: &RewriteContext,
// }
}

fn rewrite_field(context: &RewriteContext, field: &ast::Field, width: usize, offset: usize) -> Option<String> {
fn rewrite_field(context: &RewriteContext,
field: &ast::Field,
width: usize,
offset: usize)
-> Option<String> {
let name = &token::get_ident(field.ident.node);
let overhead = name.len() + 2;
let expr = field.expr.rewrite(context, width - overhead, offset + overhead);
Expand Down Expand Up @@ -262,15 +263,13 @@ fn rewrite_tuple_lit(context: &RewriteContext,
SeparatorTactic::Never
};

let fmt = ListFormatting {
tactic: ListTactic::HorizontalVertical,
separator: ",",
trailing_separator: trailing_separator_tactic,
indent: indent,
h_width: width - 2,
v_width: width - 2,
ends_with_newline: true,
};
let fmt = ListFormatting { tactic: ListTactic::HorizontalVertical,
separator: ",",
trailing_separator: trailing_separator_tactic,
indent: indent,
h_width: width - 2,
v_width: width - 2,
ends_with_newline: true, };

Some(format!("({})", write_list(&items, &fmt)))
}
Expand Down
22 changes: 11 additions & 11 deletions src/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ impl<'a> FmtVisitor<'a> {
path: &ast::Path,
path_list: &[ast::PathListItem],
visibility: ast::Visibility,
span: Span) -> Option<String> {
span: Span)
-> Option<String> {
let path_str = pprust::path_to_string(path);
let vis = format_visibility(visibility);

Expand All @@ -70,18 +71,17 @@ impl<'a> FmtVisitor<'a> {
let remaining_line_budget = one_line_budget.checked_sub(used_width).unwrap_or(0);
let remaining_multi_budget = multi_line_budget.checked_sub(used_width).unwrap_or(0);

let fmt = ListFormatting {
tactic: ListTactic::Mixed,
separator: ",",
trailing_separator: SeparatorTactic::Never,
indent: block_indent + indent,
h_width: remaining_line_budget,
v_width: remaining_multi_budget,
ends_with_newline: true,
};
let fmt = ListFormatting { tactic: ListTactic::Mixed,
separator: ",",
trailing_separator: SeparatorTactic::Never,
indent: block_indent + indent,
h_width: remaining_line_budget,
v_width: remaining_multi_budget,
ends_with_newline: true, };

let mut items = itemize_list(self.codemap,
vec![ListItem::from_str("")], // Dummy value, explanation below
vec![ListItem::from_str("")], /* Dummy value, explanation
* below */
path_list.iter(),
",",
"}",
Expand Down
35 changes: 13 additions & 22 deletions src/issues.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ static FIX_ME_CHARS: &'static [char] = &['F', 'I', 'X', 'M', 'E'];
pub enum ReportTactic {
Always,
Unnumbered,
Never
Never,
}

impl ReportTactic {
Expand All @@ -40,20 +40,20 @@ impl_enum_decodable!(ReportTactic, Always, Unnumbered, Never);
enum Seeking {
Issue {
todo_idx: usize,
fixme_idx: usize
fixme_idx: usize,
},
Number {
issue: Issue,
part: NumberPart
}
part: NumberPart,
},
}

#[derive(Clone, Copy)]
enum NumberPart {
OpenParen,
Pound,
Number,
CloseParen
CloseParen,
}

#[derive(PartialEq, Eq, Debug, Clone, Copy)]
Expand All @@ -79,13 +79,13 @@ impl fmt::Display for Issue {
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
enum IssueType {
Todo,
Fixme
Fixme,
}

enum IssueClassification {
Good,
Bad(Issue),
None
None,
}

pub struct BadIssueSeeker {
Expand All @@ -96,11 +96,9 @@ pub struct BadIssueSeeker {

impl BadIssueSeeker {
pub fn new(report_todo: ReportTactic, report_fixme: ReportTactic) -> BadIssueSeeker {
BadIssueSeeker {
state: Seeking::Issue { todo_idx: 0, fixme_idx: 0 },
report_todo: report_todo,
report_fixme: report_fixme,
}
BadIssueSeeker { state: Seeking::Issue { todo_idx: 0, fixme_idx: 0 },
report_todo: report_todo,
report_fixme: report_fixme, }
}

// Check whether or not the current char is conclusive evidence for an
Expand Down Expand Up @@ -176,8 +174,7 @@ impl BadIssueSeeker {
c: char,
issue: Issue,
mut part: NumberPart)
-> IssueClassification
{
-> IssueClassification {
if ! issue.missing_number || c == '\n' {
return IssueClassification::Bad(issue);
} else if c == ')' {
Expand Down Expand Up @@ -272,10 +269,7 @@ fn find_issue() {
#[test]
fn issue_type() {
let mut seeker = BadIssueSeeker::new(ReportTactic::Always, ReportTactic::Never);
let expected = Some(Issue {
issue_type: IssueType::Todo,
missing_number: false
});
let expected = Some(Issue { issue_type: IssueType::Todo, missing_number: false });

assert_eq!(expected,
"TODO(#100): more awesomeness".chars()
Expand All @@ -284,10 +278,7 @@ fn issue_type() {
.unwrap());

let mut seeker = BadIssueSeeker::new(ReportTactic::Never, ReportTactic::Unnumbered);
let expected = Some(Issue {
issue_type: IssueType::Fixme,
missing_number: true
});
let expected = Some(Issue { issue_type: IssueType::Fixme, missing_number: true });

assert_eq!(expected,
"Test. FIXME: bad, bad, not good".chars()
Expand Down
Loading