]> git.lizzy.rs Git - rust.git/blob - src/mod.rs
New reformatting of fns
[rust.git] / src / mod.rs
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.
4 //
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.
10
11 #![feature(box_syntax)]
12 #![feature(box_patterns)]
13 #![feature(rustc_private)]
14 #![feature(collections)]
15 #![feature(core)]
16 #![feature(unicode)]
17 #![feature(exit_status)]
18 #![feature(str_char)]
19
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
23
24 // TODO priorities
25 // Fix fns and methods properly - need visibility in visit
26 // Use strings crate
27 // Writing output
28 // Working on multiple files, inclding empty ones
29 // Smoke testing till we can use it
30
31 #[macro_use]
32 extern crate log;
33
34 extern crate getopts;
35 extern crate rustc;
36 extern crate rustc_driver;
37 extern crate syntax;
38
39 use rustc::session::Session;
40 use rustc::session::config::{self, Input};
41 use rustc_driver::{driver, CompilerCalls, Compilation};
42
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;
48 use syntax::visit;
49
50 use std::path::PathBuf;
51
52 use changes::ChangeSet;
53
54 pub mod rope;
55 pub mod string_buffer;
56 mod changes;
57
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;
63
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);
71     }
72
73     visitor.changes
74 }
75
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;
82         let mut line_len = 0;
83         let mut cur_line = 1;
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));
89                     line_len -= b - lw;
90                 }
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);
96                 }
97                 line_len = 0;
98                 cur_line += 1;
99                 last_wspace = None;
100             } else {
101                 line_len += 1;
102                 if c.is_whitespace() {
103                     if last_wspace.is_none() {
104                         last_wspace = Some(b);
105                     }
106                 } else {
107                     last_wspace = None;
108                 }
109             }
110         }
111
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);
115         }
116     }
117 }
118
119 struct FmtVisitor<'a> {
120     codemap: &'a CodeMap,
121     changes: ChangeSet<'a>,
122     last_pos: BytePos,
123     // TODO RAII util for indenting
124     block_indent: usize,
125 }
126
127 impl<'a, 'v> visit::Visitor<'v> for FmtVisitor<'a> {
128     fn visit_expr(&mut self, ex: &'v ast::Expr) {
129         // TODO uncomment
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;
138     }
139
140     fn visit_block(&mut self, b: &'v ast::Block) {
141         // TODO uncomment
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);
146
147         self.changes.push_str_span(b.span, "{");
148         self.last_pos = self.last_pos + BytePos(1);
149         self.block_indent += TAB_SPACES;
150
151         for stmt in &b.stmts {
152             self.format_missing_with_indent(stmt.span.lo);
153             self.visit_stmt(&stmt)
154         }
155         match b.expr {
156             Some(ref e) => {
157                 self.format_missing_with_indent(e.span.lo);
158                 self.visit_expr(e);
159             }
160             None => {}
161         }
162
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;
168     }
169
170     fn visit_fn(&mut self,
171                 fk: visit::FnKind<'v>,
172                 fd: &'v ast::FnDecl,
173                 b: &'v ast::Block,
174                 s: Span,
175                 _: ast::NodeId) {
176         // TODO need to get the visibility from somewhere
177         self.format_missing(s.lo);
178         self.last_pos = s.lo;
179
180         // TODO need to check against expected indent
181         let indent = self.codemap.lookup_char_pos(s.lo).col.0;
182         match fk {
183             visit::FkItemFn(ident, ref generics, ref unsafety, ref abi) => {
184                 let new_fn = self.rewrite_fn(indent,
185                                              ident,
186                                              fd,
187                                              None,
188                                              generics,
189                                              unsafety,
190                                              abi,
191                                              ast::Visibility::Inherited);
192                 self.changes.push_str_span(s, &new_fn);
193             }
194             visit::FkMethod(ident, ref sig) => {
195                 let new_fn = self.rewrite_fn(indent,
196                                              ident,
197                                              fd,
198                                              Some(&sig.explicit_self),
199                                              &sig.generics,
200                                              &sig.unsafety,
201                                              &sig.abi,
202                                              ast::Visibility::Inherited);
203                 self.changes.push_str_span(s, &new_fn);
204             }
205             visit::FkFnBlock(..) => {}
206         }
207
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;
213         self.visit_block(b)
214     }
215
216     fn visit_item(&mut self, item: &'v ast::Item) {
217         match item.node {
218             ast::Item_::ItemUse(ref vp) => {
219                 match vp.node {
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;
225                     }
226                     ast::ViewPath_::ViewPathGlob(_) => {
227                         // FIXME convert to list?
228                     }
229                     _ => {}
230                 }
231                 visit::walk_item(self, item);
232             }
233             ast::Item_::ItemImpl(..) => {
234                 self.block_indent += TAB_SPACES;
235                 visit::walk_item(self, item);
236                 self.block_indent -= TAB_SPACES;
237             }
238             _ => {
239                 visit::walk_item(self, item);
240             }
241         }
242     }
243
244     fn visit_mac(&mut self, mac: &'v ast::Mac) {
245         visit::walk_mac(self, mac)
246     }
247 }
248
249 fn make_indent(width: usize) -> String {
250     let mut indent = String::with_capacity(width);
251     for _ in 0..width {
252         indent.push(' ')
253     }
254     indent
255 }
256
257 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
258 enum ListTactic {
259     // One item per row.
260     Vertical,
261     // All items on one row.
262     Horizontal,
263     // Try Horizontal layout, if that fails then vertical
264     HorizontalVertical,
265     // Pack as many items as possible per row over (possibly) many rows.
266     Mixed,
267 }
268
269 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
270 enum SeparatorTactic {
271     Always,
272     Never,
273     Vertical,
274 }
275
276 struct ListFormatting<'a> {
277     tactic: ListTactic,
278     separator: &'a str,
279     trailing_separator: SeparatorTactic,
280     indent: usize,
281     // Available width if we layout horizontally.
282     h_width: usize,
283     // Available width if we layout vertically
284     v_width: usize,
285 }
286
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();
291     }
292
293     let mut tactic = formatting.tactic;
294
295     let h_width = formatting.h_width;
296     let v_width = formatting.v_width;
297     let sep_len = formatting.separator.len();
298
299     // Conservatively overestimates because of the changing separator tactic.
300     let sep_count = if formatting.trailing_separator != SeparatorTactic::Never {
301         items.len()
302     } else {
303         items.len() - 1
304     };
305
306     // TODO count dead space too.
307     let total_width = items.iter().map(|&(ref s, _)| s.len()).fold(0, |a, l| a + l);
308
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;
313         } else {
314             tactic = ListTactic::Horizontal;
315         }
316     }
317
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,
324     };
325
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
330     } else {
331         total_width + items.len() * (formatting.indent + 1)
332     };
333     let mut result = String::with_capacity(alloc_width);
334
335     let mut line_len = 0;
336     let indent_str = &make_indent(formatting.indent);
337     for (i, &(ref item, _)) in items.iter().enumerate() {
338         let first = i == 0;
339         let separate = i != items.len() - 1 || trailing_separator;
340
341         match tactic {
342             ListTactic::Horizontal if !first => {
343                 result.push(' ');
344             }
345             ListTactic::Vertical if !first => {
346                 result.push('\n');
347                 result.push_str(indent_str);
348             }
349             ListTactic::Mixed => {
350                 let mut item_width = item.len();
351                 if separate {
352                     item_width += sep_len;
353                 }
354
355                 if line_len > 0 && line_len + item_width > v_width {
356                     result.push('\n');
357                     result.push_str(indent_str);
358                     line_len = 0;
359                 }
360
361                 if line_len > 0 {
362                     result.push(' ');
363                     line_len += 1;
364                 }
365
366                 line_len += item_width;
367             }
368             _ => {}
369         }
370
371         result.push_str(item);
372         
373         if separate {
374             result.push_str(formatting.separator);
375         }
376         // TODO dead spans
377     }
378
379     result
380 }
381
382 impl<'a> FmtVisitor<'a> {
383     fn from_codemap<'b>(codemap: &'b CodeMap) -> FmtVisitor<'b> {
384         FmtVisitor {
385             codemap: codemap,
386             changes: ChangeSet::from_codemap(codemap),
387             last_pos: BytePos(0),
388             block_indent: 0,
389         }
390     }
391
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)
397         })
398     }
399
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 {
403                 // No new lines
404                 this.changes.push_str_span(span, last_snippet);
405                 this.changes.push_str_span(span, "\n");
406             } else {
407                 this.changes.push_str_span(span, last_snippet.trim_right());
408             }
409             let indent = make_indent(this.block_indent);
410             this.changes.push_str_span(span, &indent);
411         })
412     }
413
414     fn format_missing_inner<F: Fn(&mut FmtVisitor, &str, Span, &str)>(&mut self,
415                                                                       end: BytePos,
416                                                                       process_last_snippet: F)
417     {
418         let start = self.last_pos;
419         // TODO uncomment
420         // debug!("format_missing_inner: {:?} to {:?}",
421         //        self.codemap.lookup_char_pos(start),
422         //        self.codemap.lookup_char_pos(end));
423
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));
433
434         if start == end {
435             return;
436         }
437
438         self.last_pos = end;
439         let span = codemap::mk_sp(start, end);
440         let snippet = self.snippet(span);
441
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() {
448             if c == '\n' {
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");
452                 } else {
453                     self.changes.push_str_span(span, &snippet[line_start..i+1]);
454                 }
455
456                 line_start = i + 1;
457                 last_wspace = None;
458             } else {
459                 if c.is_whitespace() {
460                     if last_wspace.is_none() {
461                         last_wspace = Some(i);
462                     }
463                 } else {
464                     last_wspace = None;
465                 }
466             }
467         }
468         process_last_snippet(self, &snippet[line_start..], span, &snippet);
469     }
470
471     fn snippet(&self, span: Span) -> String {
472         match self.codemap.span_to_snippet(span) {
473             Ok(s) => s,
474             Err(_) => {
475                 println!("Couldn't make snippet for span {:?}", span);
476                 "".to_string()
477             }
478         }
479     }
480
481     // TODO NEEDS TESTS
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
484
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);
491         }
492
493         // TODO if lo.col > IDEAL - 10, start a new line (need cur indent for that)
494
495         let s = s.escape_default();
496
497         let offset = offset + 1;
498         let indent = make_indent(offset);
499         let indent = &indent;
500
501         let max_chars = width - 1;
502
503         let mut cur_start = 0;
504         let mut result = String::new();
505         result.push('"');
506         loop {
507             let mut cur_end = cur_start + max_chars;
508
509             if cur_end >= s.len() {
510                 result.push_str(&s[cur_start..]);
511                 break;
512             }
513
514             // Make sure we're on a char boundary.
515             cur_end = next_char(&s, cur_end);
516
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);
520
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);
527                     }
528                 }
529             }
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);
533             }
534             result.push_str(&s[cur_start..cur_end]);
535             result.push_str("\\\n");
536             result.push_str(indent);
537
538             cur_start = cur_end;
539         }
540         result.push('"');
541
542         result
543     }
544
545     // Basically just pretty prints a multi-item import.
546     fn rewrite_use_list(&mut self,
547                         path: &ast::Path,
548                         path_list: &[ast::PathListItem],
549                         vp_span: Span) -> String {
550         // FIXME remove unused imports
551
552         // FIXME check indentation
553         let l_loc = self.codemap.lookup_char_pos(vp_span.lo);
554
555         let path_str = pprust::path_to_string(&path);
556
557         // 3 = :: + {
558         let indent = l_loc.col.0 + path_str.len() + 3;
559         let fmt = ListFormatting {
560             tactic: ListTactic::Mixed,
561             separator: ",",
562             trailing_separator: SeparatorTactic::Never,
563             indent: indent,
564             // 2 = } + ;
565             h_width: IDEAL_WIDTH - (indent + path_str.len() + 2),
566             v_width: IDEAL_WIDTH - (indent + path_str.len() + 2),
567         };
568
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 {
573                 true
574             } else {
575                 false
576             }
577         ) {
578             Some(("self".to_string(), String::new()))
579         } else {
580             None
581         };
582
583         let items: Vec<_> = head.into_iter().chain(path_list.iter().filter_map(|vpi| {
584             match vpi.node {
585                 ast::PathListItem_::PathListIdent{ name, .. } => {
586                     Some((token::get_ident(name).to_string(), String::new()))
587                 }
588                 // Skip `self`, because we added it above.
589                 ast::PathListItem_::PathListMod{ .. } => None,
590             }
591         })).collect();
592
593         format!("use {}::{{{}}};", path_str, write_list(&items, &fmt))
594     }
595
596     fn rewrite_fn(&mut self,
597                   indent: usize,
598                   ident: ast::Ident,
599                   fd: &ast::FnDecl,
600                   explicit_self: Option<&ast::ExplicitSelf>,
601                   generics: &ast::Generics,
602                   unsafety: &ast::Unsafety,
603                   abi: &abi::Abi,
604                   vis: ast::Visibility)
605         -> String
606     {
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.
609
610         let mut result = String::with_capacity(1024);
611         // Vis unsafety abi.
612         if vis == ast::Visibility::Public {
613             result.push_str("pub ");
614         }
615         if let &ast::Unsafety::Unsafe = unsafety {
616             result.push_str("unsafe ");
617         }
618         if *abi != abi::Rust {
619             result.push_str("extern ");
620             result.push_str(&abi.to_string());
621             result.push(' ');
622         }
623
624         // fn foo
625         result.push_str("fn ");
626         result.push_str(&token::get_ident(ident));
627
628         // Generics.
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
637             result.push('<');
638
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,
644                 separator: ",",
645                 trailing_separator: SeparatorTactic::Never,
646                 indent: indent + result.len() + 1,
647                 h_width: budget,
648                 v_width: budget,
649             };
650             result.push_str(&write_list(&generics_strs, &fmt));
651
652             result.push('>');
653         }
654
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),
659         };
660
661         // Args.
662         let args = &fd.inputs;
663
664         let mut budgets = None;
665
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 {
671                 0
672             } else {
673                 MAX_WIDTH - used_space
674             };
675
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,
680                                 // 2 = `()`
681                                 max_space - used_space,
682                                 indent + result.len() + 1));
683             }
684         }
685
686         // Didn't work. we must force vertical layout and put args on a newline.
687         if let None = budgets {
688             result.push('\n');
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 {
694                 // Whoops! bankrupt.
695                 // TODO take evasive action, perhaps kill the indent or something.
696             } else {
697                 // 5 = new indent + `(`
698                 budgets = Some((0, max_space - used_space, indent + 5));
699             }
700         }
701
702         let (one_line_budget, multi_line_budget, arg_indent) = budgets.unwrap();
703         result.push('(');
704
705         let fmt = ListFormatting {
706             tactic: ListTactic::HorizontalVertical,
707             separator: ",",
708             trailing_separator: SeparatorTactic::Never,
709             indent: arg_indent,
710             h_width: one_line_budget,
711             v_width: multi_line_budget,
712         };
713         // TODO dead spans
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(),
722                     };
723                     let mut_str = match m {
724                         &ast::Mutability::MutMutable => "mut ".to_string(),
725                         &ast::Mutability::MutImmutable => String::new(),
726                     };
727                     arg_strs[0].0 = format!("&{}{}self", lt_str, mut_str)
728                 }
729                 ast::ExplicitSelf_::SelfExplicit(ref ty, _) => {
730                     arg_strs[0].0 = format!("self: {}", pprust::ty_to_string(ty))
731                 }
732                 _ => {}
733             }
734         }
735         result.push_str(&write_list(&arg_strs, &fmt));
736
737         result.push(')');
738
739         // Where clause.
740         if where_clause.predicates.len() > 0 {
741             result.push('\n');
742             result.push_str(&make_indent(indent + 4));
743             result.push_str("where ");
744
745             let budget = IDEAL_WIDTH + LEEWAY - indent - 10;
746             let fmt = ListFormatting {
747                 tactic: ListTactic::Vertical,
748                 separator: ",",
749                 trailing_separator: SeparatorTactic::Always,
750                 indent: indent + 10,
751                 h_width: budget,
752                 v_width: budget,
753             };
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));
756         }
757
758         // Return type.
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;
765                 result.push('\n');
766                 result.push_str(&make_indent(indent));
767             } else {
768                 result.push(' ');
769             }
770             result.push_str(&ret_str);
771         }
772
773         result
774     }
775
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 {
778         format!("{}: {}",
779                 pprust::pat_to_string(&arg.pat),
780                 pprust::ty_to_string(&arg.ty))
781     }
782
783     fn rewrite_pred(&self, predicate: &ast::WherePredicate) -> String
784     {
785         // TODO dead spans
786         // TODO assumes we'll always fit on one line...
787         match predicate {
788             &ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
789                                                                           ref bounded_ty,
790                                                                           ref bounds,
791                                                                           ..}) => {
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("+"))
797
798                 } else {
799                     format!("{}: {}",
800                             pprust::ty_to_string(bounded_ty),
801                             bounds.iter().map(|b| self.rewrite_ty_bound(b)).collect::<Vec<_>>().connect("+"))
802                 }
803             }
804             &ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
805                                                                             ref bounds,
806                                                                             ..}) => {
807                 format!("{}: {}",
808                         pprust::lifetime_to_string(lifetime),
809                         bounds.iter().map(|l| pprust::lifetime_to_string(l)).collect::<Vec<_>>().connect("+"))
810             }
811             &ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
812                 format!("{} = {}", pprust::path_to_string(path), pprust::ty_to_string(ty))
813             }
814         }
815     }
816
817     fn rewrite_lifetime_def(&self, lifetime: &ast::LifetimeDef) -> String
818     {
819         if lifetime.bounds.len() == 0 {
820             return pprust::lifetime_to_string(&lifetime.lifetime);
821         }
822
823         format!("{}: {}",
824                 pprust::lifetime_to_string(&lifetime.lifetime),
825                 lifetime.bounds.iter().map(|l| pprust::lifetime_to_string(l)).collect::<Vec<_>>().connect("+"))
826     }
827
828     fn rewrite_ty_bound(&self, bound: &ast::TyParamBound) -> String
829     {
830         match *bound {
831             ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
832                 self.rewrite_poly_trait_ref(tref)
833             }
834             ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
835                 format!("?{}", self.rewrite_poly_trait_ref(tref))
836             }
837             ast::TyParamBound::RegionTyParamBound(ref l) => {
838                 pprust::lifetime_to_string(l)
839             }
840         }
841     }
842
843     fn rewrite_ty_param(&self, ty_param: &ast::TyParam) -> String
844     {
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(", "));
850         }
851         if let Some(ref def) = ty_param.default {
852             result.push_str(" = ");
853             result.push_str(&pprust::ty_to_string(&def));
854         }
855
856         result
857     }
858
859     fn rewrite_poly_trait_ref(&self, t: &ast::PolyTraitRef) -> String
860     {
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))
865
866         } else {
867             pprust::path_to_string(&t.trait_ref.path)
868         }
869     }
870
871     fn rewrite_call(&mut self,
872                     callee: &ast::Expr,
873                     args: &[ptr::P<ast::Expr>],
874                     width: usize,
875                     offset: usize)
876         -> String
877     {
878         debug!("rewrite_call, width: {}, offset: {}", width, offset);
879
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);
883         // 2 is for parens.
884         let remaining_width = width - callee_str.len() - 2;
885         let offset = callee_str.len() + 1 + offset;
886         let arg_count = args.len();
887
888         let args_str = if arg_count > 0 {
889             let args: Vec<_> = args.iter().map(|e| (self.rewrite_expr(e,
890                                                                       remaining_width,
891                                                                       offset), String::new())).collect();
892             // TODO move this into write_list
893             let tactics = if args.iter().any(|&(ref s, _)| s.contains('\n')) {
894                 ListTactic::Vertical
895             } else {
896                 ListTactic::HorizontalVertical
897             };
898             let fmt = ListFormatting {
899                 tactic: tactics,
900                 separator: ",",
901                 trailing_separator: SeparatorTactic::Never,
902                 indent: offset,
903                 h_width: remaining_width,
904                 v_width: remaining_width,
905             };
906             write_list(&args, &fmt)
907         } else {
908             String::new()
909         };
910
911         format!("{}({})", callee_str, args_str)
912     }
913
914     fn rewrite_expr(&mut self, expr: &ast::Expr, width: usize, offset: usize) -> String {
915         match expr.node {
916             ast::Expr_::ExprLit(ref l) => {
917                 match l.node {
918                     ast::Lit_::LitStr(ref is, _) => {
919                         return self.rewrite_string_lit(&is, l.span, width, offset);
920                     }
921                     _ => {}
922                 }
923             }
924             ast::Expr_::ExprCall(ref callee, ref args) => {
925                 return self.rewrite_call(callee, args, width, offset);
926             }
927             _ => {}
928         }
929
930         let result = self.snippet(expr.span);
931         debug!("snippet: {}", result);
932         result
933     }
934 }
935
936 #[inline]
937 fn prev_char(s: &str, mut i: usize) -> usize {
938     if i == 0 { return 0; }
939
940     i -= 1;
941     while !s.is_char_boundary(i) {
942         i -= 1;
943     }
944     i
945 }
946
947 #[inline]
948 fn next_char(s: &str, mut i: usize) -> usize {
949     if i >= s.len() { return s.len(); }
950
951     while !s.is_char_boundary(i) {
952         i += 1;
953     }
954     i
955 }
956
957 struct RustFmtCalls {
958     input_path: Option<PathBuf>,
959 }
960
961 impl<'a> CompilerCalls<'a> for RustFmtCalls {
962     fn early_callback(&mut self,
963                       _: &getopts::Matches,
964                       _: &diagnostics::registry::Registry)
965                       -> Compilation {
966         Compilation::Continue
967     }
968
969     fn some_input(&mut self, input: Input, input_path: Option<PathBuf>) -> (Input, Option<PathBuf>) {
970         match input_path {
971             Some(ref ip) => self.input_path = Some(ip.clone()),
972             _ => {
973                 // FIXME should handle string input and write to stdout or something
974                 panic!("No input path");
975             }
976         }
977         (input, input_path)
978     }
979
980     fn no_input(&mut self,
981                 _: &getopts::Matches,
982                 _: &config::Options,
983                 _: &Option<PathBuf>,
984                 _: &Option<PathBuf>,
985                 _: &diagnostics::registry::Registry)
986                 -> Option<(Input, Option<PathBuf>)> {
987         panic!("No input supplied to RustFmt");
988     }
989
990     fn late_callback(&mut self,
991                      _: &getopts::Matches,
992                      _: &Session,
993                      _: &Input,
994                      _: &Option<PathBuf>,
995                      _: &Option<PathBuf>)
996                      -> Compilation {
997         Compilation::Continue
998     }
999
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);
1008
1009             println!("{}", changes);
1010             // FIXME(#5) Should be user specified whether to show or replace.
1011         };
1012
1013         control
1014     }
1015 }
1016
1017 fn main() {
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);
1022
1023     // TODO unit tests
1024     // let fmt = ListFormatting {
1025     //     tactic: ListTactic::Horizontal,
1026     //     separator: ",",
1027     //     trailing_separator: SeparatorTactic::Vertical,
1028     //     indent: 2,
1029     //     h_width: 80,
1030     //     v_width: 100,
1031     // };
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);
1042 }
1043
1044 // FIXME comments
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....
1050
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
1054 // the right kind.
1055
1056 // Should also make sure comments have the right indent