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
// 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.
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),
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();
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));
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);
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))
}
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)
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
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);
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))
// }
}
-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);
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)))
}
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);
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(),
",",
"}",
pub enum ReportTactic {
Always,
Unnumbered,
- Never
+ Never,
}
impl ReportTactic {
enum Seeking {
Issue {
todo_idx: usize,
- fixme_idx: usize
+ fixme_idx: usize,
},
Number {
issue: Issue,
- part: NumberPart
- }
+ part: NumberPart,
+ },
}
#[derive(Clone, Copy)]
OpenParen,
Pound,
Number,
- CloseParen
+ CloseParen,
}
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
enum IssueType {
Todo,
- Fixme
+ Fixme,
}
enum IssueClassification {
Good,
Bad(Issue),
- None
+ None,
}
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
c: char,
issue: Issue,
mut part: NumberPart)
- -> IssueClassification
- {
+ -> IssueClassification {
if ! issue.missing_number || c == '\n' {
return IssueClassification::Bad(issue);
} else if c == ')' {
#[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()
.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()
abi: &abi::Abi,
vis: ast::Visibility,
span: Span)
- -> String
- {
+ -> String {
let newline_brace = self.newline_for_brace(&generics.where_clause);
let mut result = self.rewrite_fn_base(indent,
ident: ast::Ident,
sig: &ast::MethodSig,
span: Span)
- -> String
- {
+ -> String {
// Drop semicolon or it will be interpreted as comment
let span = codemap::mk_sp(span.lo, span.hi - BytePos(1));
vis: ast::Visibility,
span: Span,
newline_brace: bool)
- -> String
- {
+ -> String {
// FIXME we'll lose any comments in between parts of the function decl, but anyone
// who comments there probably deserves what they get.
.last()
.map(|tp| end_typaram(tp))
.unwrap_or(span.lo);
- let args_span = codemap::mk_sp(
- span_after(codemap::mk_sp(args_start, span.hi), "(", self.codemap),
- span_for_return(&fd.output).lo);
+ let args_span = codemap::mk_sp(span_after(codemap::mk_sp(args_start, span.hi),
+ "(",
+ self.codemap),
+ span_for_return(&fd.output).lo);
result.push_str(&self.rewrite_args(&fd.inputs,
explicit_self,
one_line_budget,
multi_line_budget: usize,
arg_indent: usize,
span: Span)
- -> String
- {
+ -> String {
let mut arg_item_strs: Vec<_> = args.iter().map(|a| self.rewrite_fn_input(a)).collect();
// Account for sugary self.
let mut min_args = 1;
item.item = arg;
}
- let fmt = ListFormatting {
- tactic: ListTactic::HorizontalVertical,
- separator: ",",
- trailing_separator: SeparatorTactic::Never,
- indent: arg_indent,
- h_width: one_line_budget,
- v_width: multi_line_budget,
- ends_with_newline: true,
- };
+ let fmt = ListFormatting { tactic: ListTactic::HorizontalVertical,
+ separator: ",",
+ trailing_separator: SeparatorTactic::Never,
+ indent: arg_indent,
+ h_width: one_line_budget,
+ v_width: multi_line_budget,
+ ends_with_newline: true, };
write_list(&arg_items, &fmt)
}
indent: usize,
ret_str_len: usize,
newline_brace: bool)
- -> (usize, usize, usize)
- {
+ -> (usize, usize, usize) {
let mut budgets = None;
// Try keeping everything on the same line
vis: ast::Visibility,
enum_def: &ast::EnumDef,
generics: &ast::Generics,
- span: Span)
- {
+ span: Span) {
let header_str = self.format_header("enum ", ident, vis);
self.changes.push_str_span(span, &header_str);
}
// Variant of an enum
- fn visit_variant(&mut self,
- field: &ast::Variant,
- last_field: bool,
- next_span_start: BytePos)
- {
+ fn visit_variant(&mut self, field: &ast::Variant, last_field: bool, next_span_start: BytePos) {
if self.visit_attrs(&field.node.attrs) {
return;
}
struct_def: &ast::StructDef,
generics: Option<&ast::Generics>,
span: Span,
- offset: usize) -> String
- {
+ offset: usize)
+ -> String {
let mut result = String::with_capacity(1024);
let header_str = self.format_header(item_name, ident, vis);
// Conservative approximation
let single_line_cost = (span.hi - struct_def.fields[0].span.lo).0;
- let break_line = !is_tuple ||
- generics_str.contains('\n') ||
+ let break_line = !is_tuple || generics_str.contains('\n') ||
single_line_cost as usize + used_budget > self.config.max_width;
if break_line {
// 1 = ,
let budget = self.config.ideal_width - offset + self.config.tab_spaces - 1;
- let fmt = ListFormatting {
- tactic: tactic,
- separator: ",",
- trailing_separator: self.config.struct_trailing_comma,
- indent: offset + self.config.tab_spaces,
- h_width: self.config.max_width,
- v_width: budget,
- ends_with_newline: false,
- };
+ let fmt = ListFormatting { tactic: tactic,
+ separator: ",",
+ trailing_separator: self.config.struct_trailing_comma,
+ indent: offset + self.config.tab_spaces,
+ h_width: self.config.max_width,
+ v_width: budget,
+ ends_with_newline: false, };
result.push_str(&write_list(&items, &fmt));
vis: ast::Visibility,
struct_def: &ast::StructDef,
generics: &ast::Generics,
- span: Span)
- {
+ span: Span) {
let indent = self.block_indent;
let result = self.format_struct("struct ",
ident,
self.last_pos = span.hi;
}
- fn format_header(&self,
- item_name: &str,
- ident: ast::Ident,
- vis: ast::Visibility)
- -> String
- {
+ fn format_header(&self, item_name: &str, ident: ast::Ident, vis: ast::Visibility) -> String {
format!("{}{}{}", format_visibility(vis), item_name, &token::get_ident(ident))
}
opener: &str,
offset: usize,
span: Span)
- -> String
- {
+ -> String {
let mut result = self.rewrite_generics(generics, offset, span);
if generics.where_clause.predicates.len() > 0 || result.contains('\n') {
item.item = ty;
}
- let fmt = ListFormatting {
- tactic: ListTactic::HorizontalVertical,
- separator: ",",
- trailing_separator: SeparatorTactic::Never,
- indent: offset + 1,
- h_width: budget,
- v_width: budget,
- ends_with_newline: true,
- };
+ let fmt = ListFormatting { tactic: ListTactic::HorizontalVertical,
+ separator: ",",
+ trailing_separator: SeparatorTactic::Never,
+ indent: offset + 1,
+ h_width: budget,
+ v_width: budget,
+ ends_with_newline: true, };
result.push_str(&write_list(&items, &fmt));
result.push('>');
where_clause: &ast::WhereClause,
indent: usize,
span_end: BytePos)
- -> String
- {
+ -> String {
let mut result = String::new();
if where_clause.predicates.len() == 0 {
return result;
span_end);
let budget = self.config.ideal_width + self.config.leeway - indent - 10;
- let fmt = ListFormatting {
- tactic: ListTactic::Vertical,
- separator: ",",
- trailing_separator: SeparatorTactic::Never,
- indent: indent + 10,
- h_width: budget,
- v_width: budget,
- ends_with_newline: true,
- };
+ let fmt = ListFormatting { tactic: ListTactic::Vertical,
+ separator: ",",
+ trailing_separator: SeparatorTactic::Never,
+ indent: indent + 10,
+ h_width: budget,
+ v_width: budget,
+ ends_with_newline: true, };
result.push_str(&write_list(&items, &fmt));
result
pub v_width: usize,
// Non-expressions, e.g. items, will have a new line at the end of the list.
// Important for comment styles.
- pub ends_with_newline: bool
+ pub ends_with_newline: bool,
}
pub struct ListItem {
pub pre_comment: Option<String>,
// Item should include attributes and doc comments
pub item: String,
- pub post_comment: Option<String>
+ pub post_comment: Option<String>,
}
impl ListItem {
pub fn is_multiline(&self) -> bool {
- self.item.contains('\n') ||
- self.pre_comment.is_some() ||
+ self.item.contains('\n') || self.pre_comment.is_some() ||
self.post_comment.as_ref().map(|s| s.contains('\n')).unwrap_or(false)
}
}
pub fn from_str<S: Into<String>>(s: S) -> ListItem {
- ListItem {
- pre_comment: None,
- item: s.into(),
- post_comment: None
- }
+ ListItem { pre_comment: None, item: s.into(), post_comment: None }
}
}
get_item_string: F3,
mut prev_span_end: BytePos,
next_span_start: BytePos)
- -> Vec<ListItem>
- where I: Iterator<Item=T>,
+ -> Vec<ListItem>
+ where I: Iterator<Item = T>,
F1: Fn(&T) -> BytePos,
F2: Fn(&T) -> BytePos,
F3: Fn(&T) -> String
fn format_missing_inner<F: Fn(&mut FmtVisitor, &str, &str, &str)>(&mut self,
end: BytePos,
- process_last_snippet: F)
- {
+ process_last_snippet: F) {
let start = self.last_pos;
debug!("format_missing_inner: {:?} to {:?}",
self.codemap.lookup_char_pos(start),
use syntax::print::pprust;
impl<'a> FmtVisitor<'a> {
- pub fn rewrite_pred(&self, predicate: &ast::WherePredicate) -> String
- {
+ pub fn rewrite_pred(&self, predicate: &ast::WherePredicate) -> String {
// TODO dead spans
// TODO assumes we'll always fit on one line...
match predicate {
}
}
- pub fn rewrite_lifetime_def(&self, lifetime: &ast::LifetimeDef) -> String
- {
+ pub fn rewrite_lifetime_def(&self, lifetime: &ast::LifetimeDef) -> String {
if lifetime.bounds.len() == 0 {
return pprust::lifetime_to_string(&lifetime.lifetime);
}
lifetime.bounds.iter().map(|l| pprust::lifetime_to_string(l)).collect::<Vec<_>>().connect(" + "))
}
- pub fn rewrite_ty_bound(&self, bound: &ast::TyParamBound) -> String
- {
+ pub fn rewrite_ty_bound(&self, bound: &ast::TyParamBound) -> String {
match *bound {
ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
self.rewrite_poly_trait_ref(tref)
}
}
- pub fn rewrite_ty_param(&self, ty_param: &ast::TyParam) -> String
- {
+ pub fn rewrite_ty_param(&self, ty_param: &ast::TyParam) -> String {
let mut result = String::with_capacity(128);
result.push_str(&token::get_ident(ty_param.ident));
if ty_param.bounds.len() > 0 {
result
}
- fn rewrite_poly_trait_ref(&self, t: &ast::PolyTraitRef) -> String
- {
+ fn rewrite_poly_trait_ref(&self, t: &ast::PolyTraitRef) -> String {
if t.bound_lifetimes.len() > 0 {
format!("for<{}> {}",
t.bound_lifetimes.iter().map(|l| self.rewrite_lifetime_def(l)).collect::<Vec<_>>().connect(", "),
impl<'a> FmtVisitor<'a> {
pub fn from_codemap<'b>(codemap: &'b CodeMap, config: &'b Config) -> FmtVisitor<'b> {
- FmtVisitor {
- codemap: codemap,
- changes: ChangeSet::from_codemap(codemap),
- last_pos: BytePos(0),
- block_indent: 0,
- config: config
- }
+ FmtVisitor { codemap: codemap,
+ changes: ChangeSet::from_codemap(codemap),
+ last_pos: BytePos(0),
+ block_indent: 0,
+ config: config, }
}
pub fn snippet(&self, span: Span) -> String {