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 #![feature(box_syntax)]
12 #![feature(box_patterns)]
13 #![feature(rustc_private)]
14 #![feature(collections)]
15 #![feature(exit_status)]
18 // TODO we're going to allocate a whole bunch of temp Strings, is it worth
19 // keeping some scratch mem for this and running our own StrPool?
20 // TODO for lint violations of names, emit a refactor script
23 // Fix fns and methods properly - need visibility in visit
25 // Working on multiple files, inclding empty ones
26 // Smoke testing till we can use it
33 extern crate rustc_driver;
38 use rustc::session::Session;
39 use rustc::session::config::{self, Input};
40 use rustc_driver::{driver, CompilerCalls, Compilation};
42 use syntax::{ast, ptr, abi};
43 use syntax::codemap::{self, CodeMap, Span, Pos, BytePos};
44 use syntax::diagnostics;
45 use syntax::parse::token;
46 use syntax::print::pprust;
49 use std::path::PathBuf;
51 use changes::ChangeSet;
55 const IDEAL_WIDTH: usize = 80;
56 const LEEWAY: usize = 5;
57 const MAX_WIDTH: usize = 100;
58 const MIN_STRING: usize = 10;
59 const TAB_SPACES: usize = 4;
61 // Formatting which depends on the AST.
62 fn fmt_ast<'a>(krate: &ast::Crate, codemap: &'a CodeMap) -> ChangeSet<'a> {
63 let mut visitor = FmtVisitor::from_codemap(codemap);
64 visit::walk_crate(&mut visitor, krate);
65 let files = codemap.files.borrow();
66 if let Some(last) = files.last() {
67 visitor.format_missing(last.end_pos);
73 // Formatting done on a char by char basis.
74 fn fmt_lines(changes: &mut ChangeSet) {
75 // Iterate over the chars in the change set.
76 for (f, text) in changes.text() {
77 let mut trims = vec![];
78 let mut last_wspace: Option<usize> = None;
81 for (c, b) in text.chars() {
82 if c == '\n' { // TOOD test for \r too
83 // Check for (and record) trailing whitespace.
84 if let Some(lw) = last_wspace {
85 trims.push((cur_line, lw, b));
88 // Check for any line width errors we couldn't correct.
89 if line_len > MAX_WIDTH {
90 // FIXME store the error rather than reporting immediately.
91 println!("Rustfmt couldn't fix (sorry). {}:{}: line longer than {} characters",
92 f, cur_line, MAX_WIDTH);
99 if c.is_whitespace() {
100 if last_wspace.is_none() {
101 last_wspace = Some(b);
109 for &(l, _, _) in trims.iter() {
110 // FIXME store the error rather than reporting immediately.
111 println!("Rustfmt left trailing whitespace at {}:{} (sorry)", f, l);
116 struct FmtVisitor<'a> {
117 codemap: &'a CodeMap,
118 changes: ChangeSet<'a>,
120 // TODO RAII util for indenting
124 impl<'a, 'v> visit::Visitor<'v> for FmtVisitor<'a> {
125 fn visit_expr(&mut self, ex: &'v ast::Expr) {
127 // debug!("visit_expr: {:?} {:?}",
128 // self.codemap.lookup_char_pos(ex.span.lo),
129 // self.codemap.lookup_char_pos(ex.span.hi));
130 self.format_missing(ex.span.lo);
131 let offset = self.changes.cur_offset_span(ex.span);
132 let new_str = self.rewrite_expr(ex, MAX_WIDTH - offset, offset);
133 self.changes.push_str_span(ex.span, &new_str);
134 self.last_pos = ex.span.hi;
137 fn visit_block(&mut self, b: &'v ast::Block) {
139 // debug!("visit_block: {:?} {:?}",
140 // self.codemap.lookup_char_pos(b.span.lo),
141 // self.codemap.lookup_char_pos(b.span.hi));
142 self.format_missing(b.span.lo);
144 self.changes.push_str_span(b.span, "{");
145 self.last_pos = self.last_pos + BytePos(1);
146 self.block_indent += TAB_SPACES;
148 for stmt in &b.stmts {
149 self.format_missing_with_indent(stmt.span.lo);
150 self.visit_stmt(&stmt)
154 self.format_missing_with_indent(e.span.lo);
160 self.block_indent -= TAB_SPACES;
161 // TODO we should compress any newlines here to just one
162 self.format_missing_with_indent(b.span.hi - BytePos(1));
163 self.changes.push_str_span(b.span, "}");
164 self.last_pos = b.span.hi;
167 fn visit_fn(&mut self,
168 fk: visit::FnKind<'v>,
173 // TODO need to get the visibility from somewhere
174 self.format_missing(s.lo);
175 self.last_pos = s.lo;
177 // TODO need to check against expected indent
178 let indent = self.codemap.lookup_char_pos(s.lo).col.0;
180 visit::FkItemFn(ident, ref generics, ref unsafety, ref abi) => {
181 let new_fn = self.rewrite_fn(indent,
188 ast::Visibility::Inherited);
189 self.changes.push_str_span(s, &new_fn);
191 visit::FkMethod(ident, ref sig) => {
192 let new_fn = self.rewrite_fn(indent,
195 Some(&sig.explicit_self),
199 ast::Visibility::Inherited);
200 self.changes.push_str_span(s, &new_fn);
202 visit::FkFnBlock(..) => {}
205 // FIXME we'll miss anything between the end of the signature and the start
206 // of the body, but we need more spans from the compiler to solve this.
207 self.changes.push_str_span(s, "\n");
208 self.changes.push_str_span(s, &make_indent(self.block_indent));
209 self.last_pos = b.span.lo;
213 fn visit_item(&mut self, item: &'v ast::Item) {
215 ast::Item_::ItemUse(ref vp) => {
217 ast::ViewPath_::ViewPathList(ref path, ref path_list) => {
218 self.format_missing(item.span.lo);
219 let new_str = self.rewrite_use_list(path, path_list, vp.span);
220 self.changes.push_str_span(item.span, &new_str);
221 self.last_pos = item.span.hi;
223 ast::ViewPath_::ViewPathGlob(_) => {
224 // FIXME convert to list?
228 visit::walk_item(self, item);
230 ast::Item_::ItemImpl(..) => {
231 self.block_indent += TAB_SPACES;
232 visit::walk_item(self, item);
233 self.block_indent -= TAB_SPACES;
236 visit::walk_item(self, item);
241 fn visit_mac(&mut self, mac: &'v ast::Mac) {
242 visit::walk_mac(self, mac)
246 fn make_indent(width: usize) -> String {
247 let mut indent = String::with_capacity(width);
254 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
258 // All items on one row.
260 // Try Horizontal layout, if that fails then vertical
262 // Pack as many items as possible per row over (possibly) many rows.
266 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
267 enum SeparatorTactic {
273 struct ListFormatting<'a> {
276 trailing_separator: SeparatorTactic,
278 // Available width if we layout horizontally.
280 // Available width if we layout vertically
284 // Format a list of strings into a string.
285 fn write_list<'b>(items:&[(String, String)], formatting: &ListFormatting<'b>) -> String {
286 if items.len() == 0 {
287 return String::new();
290 let mut tactic = formatting.tactic;
292 let h_width = formatting.h_width;
293 let v_width = formatting.v_width;
294 let sep_len = formatting.separator.len();
296 // Conservatively overestimates because of the changing separator tactic.
297 let sep_count = if formatting.trailing_separator != SeparatorTactic::Never {
303 // TODO count dead space too.
304 let total_width = items.iter().map(|&(ref s, _)| s.len()).fold(0, |a, l| a + l);
306 // Check if we need to fallback from horizontal listing, if possible.
307 if tactic == ListTactic::HorizontalVertical {
308 if (total_width + (sep_len + 1) * sep_count) > h_width {
309 tactic = ListTactic::Vertical;
311 tactic = ListTactic::Horizontal;
315 // Now that we know how we will layout, we can decide for sure if there
316 // will be a trailing separator.
317 let trailing_separator = match formatting.trailing_separator {
318 SeparatorTactic::Always => true,
319 SeparatorTactic::Vertical => tactic == ListTactic::Vertical,
320 SeparatorTactic::Never => false,
323 // Create a buffer for the result.
324 // TODO could use a StringBuffer or rope for this
325 let alloc_width = if tactic == ListTactic::Horizontal {
326 total_width + (sep_len + 1) * sep_count
328 total_width + items.len() * (formatting.indent + 1)
330 let mut result = String::with_capacity(alloc_width);
332 let mut line_len = 0;
333 let indent_str = &make_indent(formatting.indent);
334 for (i, &(ref item, _)) in items.iter().enumerate() {
336 let separate = i != items.len() - 1 || trailing_separator;
339 ListTactic::Horizontal if !first => {
342 ListTactic::Vertical if !first => {
344 result.push_str(indent_str);
346 ListTactic::Mixed => {
347 let mut item_width = item.len();
349 item_width += sep_len;
352 if line_len > 0 && line_len + item_width > v_width {
354 result.push_str(indent_str);
363 line_len += item_width;
368 result.push_str(item);
371 result.push_str(formatting.separator);
379 impl<'a> FmtVisitor<'a> {
380 fn from_codemap<'b>(codemap: &'b CodeMap) -> FmtVisitor<'b> {
383 changes: ChangeSet::from_codemap(codemap),
384 last_pos: BytePos(0),
389 // TODO these format_missing methods are ugly. Refactor and add unit tests
390 // for the central whitespace stripping loop.
391 fn format_missing(&mut self, end: BytePos) {
392 self.format_missing_inner(end, |this, last_snippet, span, _| {
393 this.changes.push_str_span(span, last_snippet)
397 fn format_missing_with_indent(&mut self, end: BytePos) {
398 self.format_missing_inner(end, |this, last_snippet, span, snippet| {
399 if last_snippet == snippet {
401 this.changes.push_str_span(span, last_snippet);
402 this.changes.push_str_span(span, "\n");
404 this.changes.push_str_span(span, last_snippet.trim_right());
406 let indent = make_indent(this.block_indent);
407 this.changes.push_str_span(span, &indent);
411 fn format_missing_inner<F: Fn(&mut FmtVisitor, &str, Span, &str)>(&mut self,
413 process_last_snippet: F)
415 let start = self.last_pos;
417 // debug!("format_missing_inner: {:?} to {:?}",
418 // self.codemap.lookup_char_pos(start),
419 // self.codemap.lookup_char_pos(end));
421 // TODO(#11) gets tricky if we're missing more than one file
422 // assert!(self.codemap.lookup_char_pos(start).file.name == self.codemap.lookup_char_pos(end).file.name,
423 // "not implemented: unformated span across files: {} and {}",
424 // self.codemap.lookup_char_pos(start).file.name,
425 // self.codemap.lookup_char_pos(end).file.name);
426 // assert!(start <= end,
427 // "Request to format inverted span: {:?} to {:?}",
428 // self.codemap.lookup_char_pos(start),
429 // self.codemap.lookup_char_pos(end));
436 let span = codemap::mk_sp(start, end);
437 let snippet = self.snippet(span);
439 // Trim whitespace from the right hand side of each line.
440 // Annoyingly, the library functions for splitting by lines etc. are not
441 // quite right, so we must do it ourselves.
442 let mut line_start = 0;
443 let mut last_wspace = None;
444 for (i, c) in snippet.char_indices() {
446 if let Some(lw) = last_wspace {
447 self.changes.push_str_span(span, &snippet[line_start..lw]);
448 self.changes.push_str_span(span, "\n");
450 self.changes.push_str_span(span, &snippet[line_start..i+1]);
456 if c.is_whitespace() {
457 if last_wspace.is_none() {
458 last_wspace = Some(i);
465 process_last_snippet(self, &snippet[line_start..], span, &snippet);
468 fn snippet(&self, span: Span) -> String {
469 match self.codemap.span_to_snippet(span) {
472 println!("Couldn't make snippet for span {:?}", span);
479 fn rewrite_string_lit(&mut self, s: &str, span: Span, width: usize, offset: usize) -> String {
480 // FIXME I bet this stomps unicode escapes in the source string
482 // Check if there is anything to fix: we always try to fixup multi-line
483 // strings, or if the string is too long for the line.
484 let l_loc = self.codemap.lookup_char_pos(span.lo);
485 let r_loc = self.codemap.lookup_char_pos(span.hi);
486 if l_loc.line == r_loc.line && r_loc.col.to_usize() <= MAX_WIDTH {
487 return self.snippet(span);
490 // TODO if lo.col > IDEAL - 10, start a new line (need cur indent for that)
492 let s = s.escape_default();
494 let offset = offset + 1;
495 let indent = make_indent(offset);
496 let indent = &indent;
498 let max_chars = width - 1;
500 let mut cur_start = 0;
501 let mut result = String::new();
504 let mut cur_end = cur_start + max_chars;
506 if cur_end >= s.len() {
507 result.push_str(&s[cur_start..]);
511 // Make sure we're on a char boundary.
512 cur_end = next_char(&s, cur_end);
514 // Push cur_end left until we reach whitespace
515 while !s.char_at(cur_end-1).is_whitespace() {
516 cur_end = prev_char(&s, cur_end);
518 if cur_end - cur_start < MIN_STRING {
519 // We can't break at whitespace, fall back to splitting
520 // anywhere that doesn't break an escape sequence
521 cur_end = next_char(&s, cur_start + max_chars);
522 while s.char_at(cur_end) == '\\' {
523 cur_end = prev_char(&s, cur_end);
527 // Make sure there is no whitespace to the right of the break.
528 while cur_end < s.len() && s.char_at(cur_end).is_whitespace() {
529 cur_end = next_char(&s, cur_end+1);
531 result.push_str(&s[cur_start..cur_end]);
532 result.push_str("\\\n");
533 result.push_str(indent);
542 // Basically just pretty prints a multi-item import.
543 fn rewrite_use_list(&mut self,
545 path_list: &[ast::PathListItem],
546 vp_span: Span) -> String {
547 // FIXME remove unused imports
549 // FIXME check indentation
550 let l_loc = self.codemap.lookup_char_pos(vp_span.lo);
552 let path_str = pprust::path_to_string(&path);
555 let indent = l_loc.col.0 + path_str.len() + 3;
556 let fmt = ListFormatting {
557 tactic: ListTactic::Mixed,
559 trailing_separator: SeparatorTactic::Never,
562 h_width: IDEAL_WIDTH - (indent + path_str.len() + 2),
563 v_width: IDEAL_WIDTH - (indent + path_str.len() + 2),
566 // TODO handle any comments inbetween items.
567 // If `self` is in the list, put it first.
568 let head = if path_list.iter().any(|vpi|
569 if let ast::PathListItem_::PathListMod{ .. } = vpi.node {
575 Some(("self".to_string(), String::new()))
580 let items: Vec<_> = head.into_iter().chain(path_list.iter().filter_map(|vpi| {
582 ast::PathListItem_::PathListIdent{ name, .. } => {
583 Some((token::get_ident(name).to_string(), String::new()))
585 // Skip `self`, because we added it above.
586 ast::PathListItem_::PathListMod{ .. } => None,
590 format!("use {}::{{{}}};", path_str, write_list(&items, &fmt))
593 fn rewrite_fn(&mut self,
597 explicit_self: Option<&ast::ExplicitSelf>,
598 generics: &ast::Generics,
599 unsafety: &ast::Unsafety,
601 vis: ast::Visibility)
604 // FIXME we'll lose any comments in between parts of the function decl, but anyone
605 // who comments there probably deserves what they get.
607 let mut result = String::with_capacity(1024);
609 if vis == ast::Visibility::Public {
610 result.push_str("pub ");
612 if let &ast::Unsafety::Unsafe = unsafety {
613 result.push_str("unsafe ");
615 if *abi != abi::Rust {
616 result.push_str("extern ");
617 result.push_str(&abi.to_string());
622 result.push_str("fn ");
623 result.push_str(&token::get_ident(ident));
626 // FIXME convert bounds to where clauses where they get too big or if
627 // there is a where clause at all.
628 let lifetimes: &[_] = &generics.lifetimes;
629 let tys: &[_] = &generics.ty_params;
630 let where_clause = &generics.where_clause;
631 if lifetimes.len() + tys.len() > 0 {
632 let budget = MAX_WIDTH - indent - result.len() - 2;
633 // TODO might need to insert a newline if the generics are really long
636 let lt_strs = lifetimes.iter().map(|l| self.rewrite_lifetime_def(l));
637 let ty_strs = tys.iter().map(|ty| self.rewrite_ty_param(ty));
638 let generics_strs: Vec<_> = lt_strs.chain(ty_strs).map(|s| (s, String::new())).collect();
639 let fmt = ListFormatting {
640 tactic: ListTactic::HorizontalVertical,
642 trailing_separator: SeparatorTactic::Never,
643 indent: indent + result.len() + 1,
647 result.push_str(&write_list(&generics_strs, &fmt));
652 let ret_str = match fd.output {
653 ast::FunctionRetTy::DefaultReturn(_) => String::new(),
654 ast::FunctionRetTy::NoReturn(_) => "-> !".to_string(),
655 ast::FunctionRetTy::Return(ref ty) => "-> ".to_string() + &pprust::ty_to_string(ty),
659 let args = &fd.inputs;
661 let mut budgets = None;
663 // Try keeping everything on the same line
664 if !result.contains("\n") {
665 // 3 = `() `, space is before ret_string
666 let used_space = indent + result.len() + 3 + ret_str.len();
667 let one_line_budget = if used_space > MAX_WIDTH {
670 MAX_WIDTH - used_space
673 let used_space = indent + result.len() + 2;
674 let max_space = IDEAL_WIDTH + LEEWAY;
675 if used_space < max_space {
676 budgets = Some((one_line_budget,
678 max_space - used_space,
679 indent + result.len() + 1));
683 // Didn't work. we must force vertical layout and put args on a newline.
684 if let None = budgets {
686 result.push_str(&make_indent(indent + 4));
687 // 6 = new indent + `()`
688 let used_space = indent + 6;
689 let max_space = IDEAL_WIDTH + LEEWAY;
690 if used_space > max_space {
692 // TODO take evasive action, perhaps kill the indent or something.
694 // 5 = new indent + `(`
695 budgets = Some((0, max_space - used_space, indent + 5));
699 let (one_line_budget, multi_line_budget, arg_indent) = budgets.unwrap();
702 let fmt = ListFormatting {
703 tactic: ListTactic::HorizontalVertical,
705 trailing_separator: SeparatorTactic::Never,
707 h_width: one_line_budget,
708 v_width: multi_line_budget,
711 let mut arg_strs: Vec<_> = args.iter().map(|a| (self.rewrite_fn_input(a), String::new())).collect();
712 // Account for sugary self.
713 if let Some(explicit_self) = explicit_self {
714 match explicit_self.node {
715 ast::ExplicitSelf_::SelfRegion(ref lt, ref m, _) => {
716 let lt_str = match lt {
717 &Some(ref l) => format!("{} ", pprust::lifetime_to_string(l)),
718 &None => String::new(),
720 let mut_str = match m {
721 &ast::Mutability::MutMutable => "mut ".to_string(),
722 &ast::Mutability::MutImmutable => String::new(),
724 arg_strs[0].0 = format!("&{}{}self", lt_str, mut_str)
726 ast::ExplicitSelf_::SelfExplicit(ref ty, _) => {
727 arg_strs[0].0 = format!("self: {}", pprust::ty_to_string(ty))
732 result.push_str(&write_list(&arg_strs, &fmt));
737 if where_clause.predicates.len() > 0 {
739 result.push_str(&make_indent(indent + 4));
740 result.push_str("where ");
742 let budget = IDEAL_WIDTH + LEEWAY - indent - 10;
743 let fmt = ListFormatting {
744 tactic: ListTactic::Vertical,
746 trailing_separator: SeparatorTactic::Always,
751 let where_strs: Vec<_> = where_clause.predicates.iter().map(|p| (self.rewrite_pred(p), String::new())).collect();
752 result.push_str(&write_list(&where_strs, &fmt));
756 if ret_str.len() > 0 {
757 // If we've already gone multi-line, or the return type would push
758 // over the max width, then put the return type on a new line.
759 if result.contains("\n") ||
760 result.len() + indent + ret_str.len() > MAX_WIDTH {
761 let indent = indent + 4;
763 result.push_str(&make_indent(indent));
767 result.push_str(&ret_str);
773 // TODO we farm this out, but this could spill over the column limit, so we ought to handle it properly
774 fn rewrite_fn_input(&self, arg: &ast::Arg) -> String {
776 pprust::pat_to_string(&arg.pat),
777 pprust::ty_to_string(&arg.ty))
780 fn rewrite_pred(&self, predicate: &ast::WherePredicate) -> String
783 // TODO assumes we'll always fit on one line...
785 &ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
789 if bound_lifetimes.len() > 0 {
790 format!("for<{}> {}: {}",
791 bound_lifetimes.iter().map(|l| self.rewrite_lifetime_def(l)).collect::<Vec<_>>().connect(", "),
792 pprust::ty_to_string(bounded_ty),
793 bounds.iter().map(|b| self.rewrite_ty_bound(b)).collect::<Vec<_>>().connect("+"))
797 pprust::ty_to_string(bounded_ty),
798 bounds.iter().map(|b| self.rewrite_ty_bound(b)).collect::<Vec<_>>().connect("+"))
801 &ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
805 pprust::lifetime_to_string(lifetime),
806 bounds.iter().map(|l| pprust::lifetime_to_string(l)).collect::<Vec<_>>().connect("+"))
808 &ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
809 format!("{} = {}", pprust::path_to_string(path), pprust::ty_to_string(ty))
814 fn rewrite_lifetime_def(&self, lifetime: &ast::LifetimeDef) -> String
816 if lifetime.bounds.len() == 0 {
817 return pprust::lifetime_to_string(&lifetime.lifetime);
821 pprust::lifetime_to_string(&lifetime.lifetime),
822 lifetime.bounds.iter().map(|l| pprust::lifetime_to_string(l)).collect::<Vec<_>>().connect("+"))
825 fn rewrite_ty_bound(&self, bound: &ast::TyParamBound) -> String
828 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
829 self.rewrite_poly_trait_ref(tref)
831 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
832 format!("?{}", self.rewrite_poly_trait_ref(tref))
834 ast::TyParamBound::RegionTyParamBound(ref l) => {
835 pprust::lifetime_to_string(l)
840 fn rewrite_ty_param(&self, ty_param: &ast::TyParam) -> String
842 let mut result = String::with_capacity(128);
843 result.push_str(&token::get_ident(ty_param.ident));
844 if ty_param.bounds.len() > 0 {
845 result.push_str(": ");
846 result.push_str(&ty_param.bounds.iter().map(|b| self.rewrite_ty_bound(b)).collect::<Vec<_>>().connect(", "));
848 if let Some(ref def) = ty_param.default {
849 result.push_str(" = ");
850 result.push_str(&pprust::ty_to_string(&def));
856 fn rewrite_poly_trait_ref(&self, t: &ast::PolyTraitRef) -> String
858 if t.bound_lifetimes.len() > 0 {
859 format!("for<{}> {}",
860 t.bound_lifetimes.iter().map(|l| self.rewrite_lifetime_def(l)).collect::<Vec<_>>().connect(", "),
861 pprust::path_to_string(&t.trait_ref.path))
864 pprust::path_to_string(&t.trait_ref.path)
868 fn rewrite_call(&mut self,
870 args: &[ptr::P<ast::Expr>],
875 debug!("rewrite_call, width: {}, offset: {}", width, offset);
877 // TODO using byte lens instead of char lens (and probably all over the place too)
878 let callee_str = self.rewrite_expr(callee, width, offset);
879 debug!("rewrite_call, callee_str: `{}`", callee_str);
881 let remaining_width = width - callee_str.len() - 2;
882 let offset = callee_str.len() + 1 + offset;
883 let arg_count = args.len();
885 let args_str = if arg_count > 0 {
886 let args: Vec<_> = args.iter().map(|e| (self.rewrite_expr(e,
888 offset), String::new())).collect();
889 // TODO move this into write_list
890 let tactics = if args.iter().any(|&(ref s, _)| s.contains('\n')) {
893 ListTactic::HorizontalVertical
895 let fmt = ListFormatting {
898 trailing_separator: SeparatorTactic::Never,
900 h_width: remaining_width,
901 v_width: remaining_width,
903 write_list(&args, &fmt)
908 format!("{}({})", callee_str, args_str)
911 fn rewrite_expr(&mut self, expr: &ast::Expr, width: usize, offset: usize) -> String {
913 ast::Expr_::ExprLit(ref l) => {
915 ast::Lit_::LitStr(ref is, _) => {
916 return self.rewrite_string_lit(&is, l.span, width, offset);
921 ast::Expr_::ExprCall(ref callee, ref args) => {
922 return self.rewrite_call(callee, args, width, offset);
927 let result = self.snippet(expr.span);
928 debug!("snippet: {}", result);
934 fn prev_char(s: &str, mut i: usize) -> usize {
935 if i == 0 { return 0; }
938 while !s.is_char_boundary(i) {
945 fn next_char(s: &str, mut i: usize) -> usize {
946 if i >= s.len() { return s.len(); }
948 while !s.is_char_boundary(i) {
954 struct RustFmtCalls {
955 input_path: Option<PathBuf>,
958 impl<'a> CompilerCalls<'a> for RustFmtCalls {
959 fn early_callback(&mut self,
960 _: &getopts::Matches,
961 _: &diagnostics::registry::Registry)
963 Compilation::Continue
966 fn some_input(&mut self, input: Input, input_path: Option<PathBuf>) -> (Input, Option<PathBuf>) {
968 Some(ref ip) => self.input_path = Some(ip.clone()),
970 // FIXME should handle string input and write to stdout or something
971 panic!("No input path");
977 fn no_input(&mut self,
978 _: &getopts::Matches,
982 _: &diagnostics::registry::Registry)
983 -> Option<(Input, Option<PathBuf>)> {
984 panic!("No input supplied to RustFmt");
987 fn late_callback(&mut self,
988 _: &getopts::Matches,
994 Compilation::Continue
997 fn build_controller(&mut self, _: &Session) -> driver::CompileController<'a> {
998 let mut control = driver::CompileController::basic();
999 control.after_parse.stop = Compilation::Stop;
1000 control.after_parse.callback = box |state| {
1001 let krate = state.krate.unwrap();
1002 let codemap = state.session.codemap();
1003 let mut changes = fmt_ast(krate, codemap);
1004 fmt_lines(&mut changes);
1006 println!("{}", changes);
1007 // FIXME(#5) Should be user specified whether to show or replace.
1015 let args: Vec<_> = std::env::args().collect();
1016 let mut call_ctxt = RustFmtCalls { input_path: None };
1017 rustc_driver::run_compiler(&args, &mut call_ctxt);
1018 std::env::set_exit_status(0);
1021 // let fmt = ListFormatting {
1022 // tactic: ListTactic::Horizontal,
1024 // trailing_separator: SeparatorTactic::Vertical,
1029 // let inputs = vec![(format!("foo"), String::new()),
1030 // (format!("foo"), String::new()),
1031 // (format!("foo"), String::new()),
1032 // (format!("foo"), String::new()),
1033 // (format!("foo"), String::new()),
1034 // (format!("foo"), String::new()),
1035 // (format!("foo"), String::new()),
1036 // (format!("foo"), String::new())];
1037 // let s = write_list(&inputs, &fmt);
1038 // println!(" {}", s);
1042 // comments aren't in the AST, which makes processing them difficult, but then
1043 // comments are complicated anyway. I think I am happy putting off tackling them
1044 // for now. Long term the soluton is for comments to be in the AST, but that means
1045 // only the libsyntax AST, not the rustc one, which means waiting for the ASTs
1046 // to diverge one day....
1048 // Once we do have comments, we just have to implement a simple word wrapping
1049 // algorithm to keep the width under IDEAL_WIDTH. We should also convert multiline
1050 // /* ... */ comments to // and check doc comments are in the right place and of
1053 // Should also make sure comments have the right indent