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)]
17 #![feature(exit_status)]
20 // TODO we're going to allocate a whole bunch of temp Strings, is it worth
21 // keeping some scratch mem for this and running our own StrPool?
22 // TODO for lint violations of names, emit a refactor script
25 // Fix fns and methods properly - need visibility in visit
28 // Working on multiple files, inclding empty ones
29 // Smoke testing till we can use it
36 extern crate rustc_driver;
39 use rustc::session::Session;
40 use rustc::session::config::{self, Input};
41 use rustc_driver::{driver, CompilerCalls, Compilation};
43 use syntax::{ast, ptr, abi};
44 use syntax::codemap::{self, CodeMap, Span, Pos, BytePos};
45 use syntax::diagnostics;
46 use syntax::parse::token;
47 use syntax::print::pprust;
50 use std::path::PathBuf;
52 use changes::ChangeSet;
55 pub mod string_buffer;
58 const IDEAL_WIDTH: usize = 80;
59 const LEEWAY: usize = 5;
60 const MAX_WIDTH: usize = 100;
61 const MIN_STRING: usize = 10;
62 const TAB_SPACES: usize = 4;
64 // Formatting which depends on the AST.
65 fn fmt_ast<'a>(krate: &ast::Crate, codemap: &'a CodeMap) -> ChangeSet<'a> {
66 let mut visitor = FmtVisitor::from_codemap(codemap);
67 visit::walk_crate(&mut visitor, krate);
68 let files = codemap.files.borrow();
69 if let Some(last) = files.last() {
70 visitor.format_missing(last.end_pos);
76 // Formatting done on a char by char basis.
77 fn fmt_lines(changes: &mut ChangeSet) {
78 // Iterate over the chars in the change set.
79 for (f, text) in changes.text() {
80 let mut trims = vec![];
81 let mut last_wspace: Option<usize> = None;
84 for (c, b) in text.chars() {
85 if c == '\n' { // TOOD test for \r too
86 // Check for (and record) trailing whitespace.
87 if let Some(lw) = last_wspace {
88 trims.push((cur_line, lw, b));
91 // Check for any line width errors we couldn't correct.
92 if line_len > MAX_WIDTH {
93 // FIXME store the error rather than reporting immediately.
94 println!("Rustfmt couldn't fix (sorry). {}:{}: line longer than {} characters",
95 f, cur_line, MAX_WIDTH);
102 if c.is_whitespace() {
103 if last_wspace.is_none() {
104 last_wspace = Some(b);
112 for &(l, _, _) in trims.iter() {
113 // FIXME store the error rather than reporting immediately.
114 println!("Rustfmt left trailing whitespace at {}:{} (sorry)", f, l);
119 struct FmtVisitor<'a> {
120 codemap: &'a CodeMap,
121 changes: ChangeSet<'a>,
123 // TODO RAII util for indenting
127 impl<'a, 'v> visit::Visitor<'v> for FmtVisitor<'a> {
128 fn visit_expr(&mut self, ex: &'v ast::Expr) {
130 // debug!("visit_expr: {:?} {:?}",
131 // self.codemap.lookup_char_pos(ex.span.lo),
132 // self.codemap.lookup_char_pos(ex.span.hi));
133 self.format_missing(ex.span.lo);
134 let offset = self.changes.cur_offset_span(ex.span);
135 let new_str = self.rewrite_expr(ex, MAX_WIDTH - offset, offset);
136 self.changes.push_str_span(ex.span, &new_str);
137 self.last_pos = ex.span.hi;
140 fn visit_block(&mut self, b: &'v ast::Block) {
142 // debug!("visit_block: {:?} {:?}",
143 // self.codemap.lookup_char_pos(b.span.lo),
144 // self.codemap.lookup_char_pos(b.span.hi));
145 self.format_missing(b.span.lo);
147 self.changes.push_str_span(b.span, "{");
148 self.last_pos = self.last_pos + BytePos(1);
149 self.block_indent += TAB_SPACES;
151 for stmt in &b.stmts {
152 self.format_missing_with_indent(stmt.span.lo);
153 self.visit_stmt(&stmt)
157 self.format_missing_with_indent(e.span.lo);
163 self.block_indent -= TAB_SPACES;
164 // TODO we should compress any newlines here to just one
165 self.format_missing_with_indent(b.span.hi - BytePos(1));
166 self.changes.push_str_span(b.span, "}");
167 self.last_pos = b.span.hi;
170 fn visit_fn(&mut self,
171 fk: visit::FnKind<'v>,
176 // TODO need to get the visibility from somewhere
177 self.format_missing(s.lo);
178 self.last_pos = s.lo;
180 // TODO need to check against expected indent
181 let indent = self.codemap.lookup_char_pos(s.lo).col.0;
183 visit::FkItemFn(ident, ref generics, ref unsafety, ref abi) => {
184 let new_fn = self.rewrite_fn(indent,
191 ast::Visibility::Inherited);
192 self.changes.push_str_span(s, &new_fn);
194 visit::FkMethod(ident, ref sig) => {
195 let new_fn = self.rewrite_fn(indent,
198 Some(&sig.explicit_self),
202 ast::Visibility::Inherited);
203 self.changes.push_str_span(s, &new_fn);
205 visit::FkFnBlock(..) => {}
208 // FIXME we'll miss anything between the end of the signature and the start
209 // of the body, but we need more spans from the compiler to solve this.
210 self.changes.push_str_span(s, "\n");
211 self.changes.push_str_span(s, &make_indent(self.block_indent));
212 self.last_pos = b.span.lo;
216 fn visit_item(&mut self, item: &'v ast::Item) {
218 ast::Item_::ItemUse(ref vp) => {
220 ast::ViewPath_::ViewPathList(ref path, ref path_list) => {
221 self.format_missing(item.span.lo);
222 let new_str = self.rewrite_use_list(path, path_list, vp.span);
223 self.changes.push_str_span(item.span, &new_str);
224 self.last_pos = item.span.hi;
226 ast::ViewPath_::ViewPathGlob(_) => {
227 // FIXME convert to list?
231 visit::walk_item(self, item);
233 ast::Item_::ItemImpl(..) => {
234 self.block_indent += TAB_SPACES;
235 visit::walk_item(self, item);
236 self.block_indent -= TAB_SPACES;
239 visit::walk_item(self, item);
244 fn visit_mac(&mut self, mac: &'v ast::Mac) {
245 visit::walk_mac(self, mac)
249 fn make_indent(width: usize) -> String {
250 let mut indent = String::with_capacity(width);
257 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
261 // All items on one row.
263 // Try Horizontal layout, if that fails then vertical
265 // Pack as many items as possible per row over (possibly) many rows.
269 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
270 enum SeparatorTactic {
276 struct ListFormatting<'a> {
279 trailing_separator: SeparatorTactic,
281 // Available width if we layout horizontally.
283 // Available width if we layout vertically
287 // Format a list of strings into a string.
288 fn write_list<'b>(items:&[(String, String)], formatting: &ListFormatting<'b>) -> String {
289 if items.len() == 0 {
290 return String::new();
293 let mut tactic = formatting.tactic;
295 let h_width = formatting.h_width;
296 let v_width = formatting.v_width;
297 let sep_len = formatting.separator.len();
299 // Conservatively overestimates because of the changing separator tactic.
300 let sep_count = if formatting.trailing_separator != SeparatorTactic::Never {
306 // TODO count dead space too.
307 let total_width = items.iter().map(|&(ref s, _)| s.len()).fold(0, |a, l| a + l);
309 // Check if we need to fallback from horizontal listing, if possible.
310 if tactic == ListTactic::HorizontalVertical {
311 if (total_width + (sep_len + 1) * sep_count) > h_width {
312 tactic = ListTactic::Vertical;
314 tactic = ListTactic::Horizontal;
318 // Now that we know how we will layout, we can decide for sure if there
319 // will be a trailing separator.
320 let trailing_separator = match formatting.trailing_separator {
321 SeparatorTactic::Always => true,
322 SeparatorTactic::Vertical => tactic == ListTactic::Vertical,
323 SeparatorTactic::Never => false,
326 // Create a buffer for the result.
327 // TODO could use a StringBuffer or rope for this
328 let alloc_width = if tactic == ListTactic::Horizontal {
329 total_width + (sep_len + 1) * sep_count
331 total_width + items.len() * (formatting.indent + 1)
333 let mut result = String::with_capacity(alloc_width);
335 let mut line_len = 0;
336 let indent_str = &make_indent(formatting.indent);
337 for (i, &(ref item, _)) in items.iter().enumerate() {
339 let separate = i != items.len() - 1 || trailing_separator;
342 ListTactic::Horizontal if !first => {
345 ListTactic::Vertical if !first => {
347 result.push_str(indent_str);
349 ListTactic::Mixed => {
350 let mut item_width = item.len();
352 item_width += sep_len;
355 if line_len > 0 && line_len + item_width > v_width {
357 result.push_str(indent_str);
366 line_len += item_width;
371 result.push_str(item);
374 result.push_str(formatting.separator);
382 impl<'a> FmtVisitor<'a> {
383 fn from_codemap<'b>(codemap: &'b CodeMap) -> FmtVisitor<'b> {
386 changes: ChangeSet::from_codemap(codemap),
387 last_pos: BytePos(0),
392 // TODO these format_missing methods are ugly. Refactor and add unit tests
393 // for the central whitespace stripping loop.
394 fn format_missing(&mut self, end: BytePos) {
395 self.format_missing_inner(end, |this, last_snippet, span, _| {
396 this.changes.push_str_span(span, last_snippet)
400 fn format_missing_with_indent(&mut self, end: BytePos) {
401 self.format_missing_inner(end, |this, last_snippet, span, snippet| {
402 if last_snippet == snippet {
404 this.changes.push_str_span(span, last_snippet);
405 this.changes.push_str_span(span, "\n");
407 this.changes.push_str_span(span, last_snippet.trim_right());
409 let indent = make_indent(this.block_indent);
410 this.changes.push_str_span(span, &indent);
414 fn format_missing_inner<F: Fn(&mut FmtVisitor, &str, Span, &str)>(&mut self,
416 process_last_snippet: F)
418 let start = self.last_pos;
420 // debug!("format_missing_inner: {:?} to {:?}",
421 // self.codemap.lookup_char_pos(start),
422 // self.codemap.lookup_char_pos(end));
424 // TODO(#11) gets tricky if we're missing more than one file
425 // assert!(self.codemap.lookup_char_pos(start).file.name == self.codemap.lookup_char_pos(end).file.name,
426 // "not implemented: unformated span across files: {} and {}",
427 // self.codemap.lookup_char_pos(start).file.name,
428 // self.codemap.lookup_char_pos(end).file.name);
429 // assert!(start <= end,
430 // "Request to format inverted span: {:?} to {:?}",
431 // self.codemap.lookup_char_pos(start),
432 // self.codemap.lookup_char_pos(end));
439 let span = codemap::mk_sp(start, end);
440 let snippet = self.snippet(span);
442 // Trim whitespace from the right hand side of each line.
443 // Annoyingly, the library functions for splitting by lines etc. are not
444 // quite right, so we must do it ourselves.
445 let mut line_start = 0;
446 let mut last_wspace = None;
447 for (i, c) in snippet.char_indices() {
449 if let Some(lw) = last_wspace {
450 self.changes.push_str_span(span, &snippet[line_start..lw]);
451 self.changes.push_str_span(span, "\n");
453 self.changes.push_str_span(span, &snippet[line_start..i+1]);
459 if c.is_whitespace() {
460 if last_wspace.is_none() {
461 last_wspace = Some(i);
468 process_last_snippet(self, &snippet[line_start..], span, &snippet);
471 fn snippet(&self, span: Span) -> String {
472 match self.codemap.span_to_snippet(span) {
475 println!("Couldn't make snippet for span {:?}", span);
482 fn rewrite_string_lit(&mut self, s: &str, span: Span, width: usize, offset: usize) -> String {
483 // FIXME I bet this stomps unicode escapes in the source string
485 // Check if there is anything to fix: we always try to fixup multi-line
486 // strings, or if the string is too long for the line.
487 let l_loc = self.codemap.lookup_char_pos(span.lo);
488 let r_loc = self.codemap.lookup_char_pos(span.hi);
489 if l_loc.line == r_loc.line && r_loc.col.to_usize() <= MAX_WIDTH {
490 return self.snippet(span);
493 // TODO if lo.col > IDEAL - 10, start a new line (need cur indent for that)
495 let s = s.escape_default();
497 let offset = offset + 1;
498 let indent = make_indent(offset);
499 let indent = &indent;
501 let max_chars = width - 1;
503 let mut cur_start = 0;
504 let mut result = String::new();
507 let mut cur_end = cur_start + max_chars;
509 if cur_end >= s.len() {
510 result.push_str(&s[cur_start..]);
514 // Make sure we're on a char boundary.
515 cur_end = next_char(&s, cur_end);
517 // Push cur_end left until we reach whitespace
518 while !s.char_at(cur_end-1).is_whitespace() {
519 cur_end = prev_char(&s, cur_end);
521 if cur_end - cur_start < MIN_STRING {
522 // We can't break at whitespace, fall back to splitting
523 // anywhere that doesn't break an escape sequence
524 cur_end = next_char(&s, cur_start + max_chars);
525 while s.char_at(cur_end) == '\\' {
526 cur_end = prev_char(&s, cur_end);
530 // Make sure there is no whitespace to the right of the break.
531 while cur_end < s.len() && s.char_at(cur_end).is_whitespace() {
532 cur_end = next_char(&s, cur_end+1);
534 result.push_str(&s[cur_start..cur_end]);
535 result.push_str("\\\n");
536 result.push_str(indent);
545 // Basically just pretty prints a multi-item import.
546 fn rewrite_use_list(&mut self,
548 path_list: &[ast::PathListItem],
549 vp_span: Span) -> String {
550 // FIXME remove unused imports
552 // FIXME check indentation
553 let l_loc = self.codemap.lookup_char_pos(vp_span.lo);
555 let path_str = pprust::path_to_string(&path);
558 let indent = l_loc.col.0 + path_str.len() + 3;
559 let fmt = ListFormatting {
560 tactic: ListTactic::Mixed,
562 trailing_separator: SeparatorTactic::Never,
565 h_width: IDEAL_WIDTH - (indent + path_str.len() + 2),
566 v_width: IDEAL_WIDTH - (indent + path_str.len() + 2),
569 // TODO handle any comments inbetween items.
570 // If `self` is in the list, put it first.
571 let head = if path_list.iter().any(|vpi|
572 if let ast::PathListItem_::PathListMod{ .. } = vpi.node {
578 Some(("self".to_string(), String::new()))
583 let items: Vec<_> = head.into_iter().chain(path_list.iter().filter_map(|vpi| {
585 ast::PathListItem_::PathListIdent{ name, .. } => {
586 Some((token::get_ident(name).to_string(), String::new()))
588 // Skip `self`, because we added it above.
589 ast::PathListItem_::PathListMod{ .. } => None,
593 format!("use {}::{{{}}};", path_str, write_list(&items, &fmt))
596 fn rewrite_fn(&mut self,
600 explicit_self: Option<&ast::ExplicitSelf>,
601 generics: &ast::Generics,
602 unsafety: &ast::Unsafety,
604 vis: ast::Visibility)
607 // FIXME we'll lose any comments in between parts of the function decl, but anyone
608 // who comments there probably deserves what they get.
610 let mut result = String::with_capacity(1024);
612 if vis == ast::Visibility::Public {
613 result.push_str("pub ");
615 if let &ast::Unsafety::Unsafe = unsafety {
616 result.push_str("unsafe ");
618 if *abi != abi::Rust {
619 result.push_str("extern ");
620 result.push_str(&abi.to_string());
625 result.push_str("fn ");
626 result.push_str(&token::get_ident(ident));
629 // FIXME convert bounds to where clauses where they get too big or if
630 // there is a where clause at all.
631 let lifetimes: &[_] = &generics.lifetimes;
632 let tys: &[_] = &generics.ty_params;
633 let where_clause = &generics.where_clause;
634 if lifetimes.len() + tys.len() > 0 {
635 let budget = MAX_WIDTH - indent - result.len() - 2;
636 // TODO might need to insert a newline if the generics are really long
639 let lt_strs = lifetimes.iter().map(|l| self.rewrite_lifetime_def(l));
640 let ty_strs = tys.iter().map(|ty| self.rewrite_ty_param(ty));
641 let generics_strs: Vec<_> = lt_strs.chain(ty_strs).map(|s| (s, String::new())).collect();
642 let fmt = ListFormatting {
643 tactic: ListTactic::HorizontalVertical,
645 trailing_separator: SeparatorTactic::Never,
646 indent: indent + result.len() + 1,
650 result.push_str(&write_list(&generics_strs, &fmt));
655 let ret_str = match fd.output {
656 ast::FunctionRetTy::DefaultReturn(_) => String::new(),
657 ast::FunctionRetTy::NoReturn(_) => "-> !".to_string(),
658 ast::FunctionRetTy::Return(ref ty) => "-> ".to_string() + &pprust::ty_to_string(ty),
662 let args = &fd.inputs;
664 let mut budgets = None;
666 // Try keeping everything on the same line
667 if !result.contains("\n") {
668 // 3 = `() `, space is before ret_string
669 let used_space = indent + result.len() + 3 + ret_str.len();
670 let one_line_budget = if used_space > MAX_WIDTH {
673 MAX_WIDTH - used_space
676 let used_space = indent + result.len() + 2;
677 let max_space = IDEAL_WIDTH + LEEWAY;
678 if used_space < max_space {
679 budgets = Some((one_line_budget,
681 max_space - used_space,
682 indent + result.len() + 1));
686 // Didn't work. we must force vertical layout and put args on a newline.
687 if let None = budgets {
689 result.push_str(&make_indent(indent + 4));
690 // 6 = new indent + `()`
691 let used_space = indent + 6;
692 let max_space = IDEAL_WIDTH + LEEWAY;
693 if used_space > max_space {
695 // TODO take evasive action, perhaps kill the indent or something.
697 // 5 = new indent + `(`
698 budgets = Some((0, max_space - used_space, indent + 5));
702 let (one_line_budget, multi_line_budget, arg_indent) = budgets.unwrap();
705 let fmt = ListFormatting {
706 tactic: ListTactic::HorizontalVertical,
708 trailing_separator: SeparatorTactic::Never,
710 h_width: one_line_budget,
711 v_width: multi_line_budget,
714 let mut arg_strs: Vec<_> = args.iter().map(|a| (self.rewrite_fn_input(a), String::new())).collect();
715 // Account for sugary self.
716 if let Some(explicit_self) = explicit_self {
717 match explicit_self.node {
718 ast::ExplicitSelf_::SelfRegion(ref lt, ref m, _) => {
719 let lt_str = match lt {
720 &Some(ref l) => format!("{} ", pprust::lifetime_to_string(l)),
721 &None => String::new(),
723 let mut_str = match m {
724 &ast::Mutability::MutMutable => "mut ".to_string(),
725 &ast::Mutability::MutImmutable => String::new(),
727 arg_strs[0].0 = format!("&{}{}self", lt_str, mut_str)
729 ast::ExplicitSelf_::SelfExplicit(ref ty, _) => {
730 arg_strs[0].0 = format!("self: {}", pprust::ty_to_string(ty))
735 result.push_str(&write_list(&arg_strs, &fmt));
740 if where_clause.predicates.len() > 0 {
742 result.push_str(&make_indent(indent + 4));
743 result.push_str("where ");
745 let budget = IDEAL_WIDTH + LEEWAY - indent - 10;
746 let fmt = ListFormatting {
747 tactic: ListTactic::Vertical,
749 trailing_separator: SeparatorTactic::Always,
754 let where_strs: Vec<_> = where_clause.predicates.iter().map(|p| (self.rewrite_pred(p), String::new())).collect();
755 result.push_str(&write_list(&where_strs, &fmt));
759 if ret_str.len() > 0 {
760 // If we've already gone multi-line, or the return type would push
761 // over the max width, then put the return type on a new line.
762 if result.contains("\n") ||
763 result.len() + indent + ret_str.len() > MAX_WIDTH {
764 let indent = indent + 4;
766 result.push_str(&make_indent(indent));
770 result.push_str(&ret_str);
776 // TODO we farm this out, but this could spill over the column limit, so we ought to handle it properly
777 fn rewrite_fn_input(&self, arg: &ast::Arg) -> String {
779 pprust::pat_to_string(&arg.pat),
780 pprust::ty_to_string(&arg.ty))
783 fn rewrite_pred(&self, predicate: &ast::WherePredicate) -> String
786 // TODO assumes we'll always fit on one line...
788 &ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
792 if bound_lifetimes.len() > 0 {
793 format!("for<{}> {}: {}",
794 bound_lifetimes.iter().map(|l| self.rewrite_lifetime_def(l)).collect::<Vec<_>>().connect(", "),
795 pprust::ty_to_string(bounded_ty),
796 bounds.iter().map(|b| self.rewrite_ty_bound(b)).collect::<Vec<_>>().connect("+"))
800 pprust::ty_to_string(bounded_ty),
801 bounds.iter().map(|b| self.rewrite_ty_bound(b)).collect::<Vec<_>>().connect("+"))
804 &ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
808 pprust::lifetime_to_string(lifetime),
809 bounds.iter().map(|l| pprust::lifetime_to_string(l)).collect::<Vec<_>>().connect("+"))
811 &ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
812 format!("{} = {}", pprust::path_to_string(path), pprust::ty_to_string(ty))
817 fn rewrite_lifetime_def(&self, lifetime: &ast::LifetimeDef) -> String
819 if lifetime.bounds.len() == 0 {
820 return pprust::lifetime_to_string(&lifetime.lifetime);
824 pprust::lifetime_to_string(&lifetime.lifetime),
825 lifetime.bounds.iter().map(|l| pprust::lifetime_to_string(l)).collect::<Vec<_>>().connect("+"))
828 fn rewrite_ty_bound(&self, bound: &ast::TyParamBound) -> String
831 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
832 self.rewrite_poly_trait_ref(tref)
834 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
835 format!("?{}", self.rewrite_poly_trait_ref(tref))
837 ast::TyParamBound::RegionTyParamBound(ref l) => {
838 pprust::lifetime_to_string(l)
843 fn rewrite_ty_param(&self, ty_param: &ast::TyParam) -> String
845 let mut result = String::with_capacity(128);
846 result.push_str(&token::get_ident(ty_param.ident));
847 if ty_param.bounds.len() > 0 {
848 result.push_str(": ");
849 result.push_str(&ty_param.bounds.iter().map(|b| self.rewrite_ty_bound(b)).collect::<Vec<_>>().connect(", "));
851 if let Some(ref def) = ty_param.default {
852 result.push_str(" = ");
853 result.push_str(&pprust::ty_to_string(&def));
859 fn rewrite_poly_trait_ref(&self, t: &ast::PolyTraitRef) -> String
861 if t.bound_lifetimes.len() > 0 {
862 format!("for<{}> {}",
863 t.bound_lifetimes.iter().map(|l| self.rewrite_lifetime_def(l)).collect::<Vec<_>>().connect(", "),
864 pprust::path_to_string(&t.trait_ref.path))
867 pprust::path_to_string(&t.trait_ref.path)
871 fn rewrite_call(&mut self,
873 args: &[ptr::P<ast::Expr>],
878 debug!("rewrite_call, width: {}, offset: {}", width, offset);
880 // TODO using byte lens instead of char lens (and probably all over the place too)
881 let callee_str = self.rewrite_expr(callee, width, offset);
882 debug!("rewrite_call, callee_str: `{}`", callee_str);
884 let remaining_width = width - callee_str.len() - 2;
885 let offset = callee_str.len() + 1 + offset;
886 let arg_count = args.len();
888 let args_str = if arg_count > 0 {
889 let args: Vec<_> = args.iter().map(|e| (self.rewrite_expr(e,
891 offset), String::new())).collect();
892 // TODO move this into write_list
893 let tactics = if args.iter().any(|&(ref s, _)| s.contains('\n')) {
896 ListTactic::HorizontalVertical
898 let fmt = ListFormatting {
901 trailing_separator: SeparatorTactic::Never,
903 h_width: remaining_width,
904 v_width: remaining_width,
906 write_list(&args, &fmt)
911 format!("{}({})", callee_str, args_str)
914 fn rewrite_expr(&mut self, expr: &ast::Expr, width: usize, offset: usize) -> String {
916 ast::Expr_::ExprLit(ref l) => {
918 ast::Lit_::LitStr(ref is, _) => {
919 return self.rewrite_string_lit(&is, l.span, width, offset);
924 ast::Expr_::ExprCall(ref callee, ref args) => {
925 return self.rewrite_call(callee, args, width, offset);
930 let result = self.snippet(expr.span);
931 debug!("snippet: {}", result);
937 fn prev_char(s: &str, mut i: usize) -> usize {
938 if i == 0 { return 0; }
941 while !s.is_char_boundary(i) {
948 fn next_char(s: &str, mut i: usize) -> usize {
949 if i >= s.len() { return s.len(); }
951 while !s.is_char_boundary(i) {
957 struct RustFmtCalls {
958 input_path: Option<PathBuf>,
961 impl<'a> CompilerCalls<'a> for RustFmtCalls {
962 fn early_callback(&mut self,
963 _: &getopts::Matches,
964 _: &diagnostics::registry::Registry)
966 Compilation::Continue
969 fn some_input(&mut self, input: Input, input_path: Option<PathBuf>) -> (Input, Option<PathBuf>) {
971 Some(ref ip) => self.input_path = Some(ip.clone()),
973 // FIXME should handle string input and write to stdout or something
974 panic!("No input path");
980 fn no_input(&mut self,
981 _: &getopts::Matches,
985 _: &diagnostics::registry::Registry)
986 -> Option<(Input, Option<PathBuf>)> {
987 panic!("No input supplied to RustFmt");
990 fn late_callback(&mut self,
991 _: &getopts::Matches,
997 Compilation::Continue
1000 fn build_controller(&mut self, _: &Session) -> driver::CompileController<'a> {
1001 let mut control = driver::CompileController::basic();
1002 control.after_parse.stop = Compilation::Stop;
1003 control.after_parse.callback = box |state| {
1004 let krate = state.krate.unwrap();
1005 let codemap = state.session.codemap();
1006 let mut changes = fmt_ast(krate, codemap);
1007 fmt_lines(&mut changes);
1009 println!("{}", changes);
1010 // FIXME(#5) Should be user specified whether to show or replace.
1018 let args: Vec<_> = std::env::args().collect();
1019 let mut call_ctxt = RustFmtCalls { input_path: None };
1020 rustc_driver::run_compiler(&args, &mut call_ctxt);
1021 std::env::set_exit_status(0);
1024 // let fmt = ListFormatting {
1025 // tactic: ListTactic::Horizontal,
1027 // trailing_separator: SeparatorTactic::Vertical,
1032 // let inputs = vec![(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 // (format!("foo"), String::new()),
1038 // (format!("foo"), String::new()),
1039 // (format!("foo"), String::new())];
1040 // let s = write_list(&inputs, &fmt);
1041 // println!(" {}", s);
1045 // comments aren't in the AST, which makes processing them difficult, but then
1046 // comments are complicated anyway. I think I am happy putting off tackling them
1047 // for now. Long term the soluton is for comments to be in the AST, but that means
1048 // only the libsyntax AST, not the rustc one, which means waiting for the ASTs
1049 // to diverge one day....
1051 // Once we do have comments, we just have to implement a simple word wrapping
1052 // algorithm to keep the width under IDEAL_WIDTH. We should also convert multiline
1053 // /* ... */ comments to // and check doc comments are in the right place and of
1056 // Should also make sure comments have the right indent