]> git.lizzy.rs Git - rust.git/blob - src/lib.rs
Merge pull request #60 from oli-obk/master
[rust.git] / src / lib.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(str_char)]
16
17 // TODO we're going to allocate a whole bunch of temp Strings, is it worth
18 // keeping some scratch mem for this and running our own StrPool?
19 // TODO for lint violations of names, emit a refactor script
20
21
22 #[macro_use]
23 extern crate log;
24
25 extern crate getopts;
26 extern crate rustc;
27 extern crate rustc_driver;
28 extern crate syntax;
29
30 extern crate strings;
31
32 use rustc::session::Session;
33 use rustc::session::config::{self, Input};
34 use rustc_driver::{driver, CompilerCalls, Compilation};
35
36 use syntax::ast;
37 use syntax::codemap::CodeMap;
38 use syntax::diagnostics;
39 use syntax::visit;
40
41 use std::path::PathBuf;
42 use std::collections::HashMap;
43
44 use changes::ChangeSet;
45 use visitor::FmtVisitor;
46
47 mod changes;
48 mod visitor;
49 mod functions;
50 mod missed_spans;
51 mod lists;
52 mod utils;
53 mod types;
54 mod expr;
55 mod imports;
56
57 const IDEAL_WIDTH: usize = 80;
58 const LEEWAY: usize = 5;
59 const MAX_WIDTH: usize = 100;
60 const MIN_STRING: usize = 10;
61 const TAB_SPACES: usize = 4;
62 const FN_BRACE_STYLE: BraceStyle = BraceStyle::SameLineWhere;
63 const FN_RETURN_INDENT: ReturnIndent = ReturnIndent::WithArgs;
64 // When we get scoped annotations, we should have rustfmt::skip.
65 const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
66
67 #[derive(Copy, Clone)]
68 pub enum WriteMode {
69     Overwrite,
70     // str is the extension of the new file
71     NewFile(&'static str),
72     // Write the output to stdout.
73     Display,
74     // Return the result as a mapping from filenames to StringBuffers.
75     Return(&'static Fn(HashMap<String, String>)),
76 }
77
78 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
79 enum BraceStyle {
80     AlwaysNextLine,
81     PreferSameLine,
82     // Prefer same line except where there is a where clause, in which case force
83     // the brace to the next line.
84     SameLineWhere,
85 }
86
87 // How to indent a function's return type.
88 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
89 enum ReturnIndent {
90     // Aligned with the arguments
91     WithArgs,
92     // Aligned with the where clause
93     WithWhereClause,
94 }
95
96 // Formatting which depends on the AST.
97 fn fmt_ast<'a>(krate: &ast::Crate, codemap: &'a CodeMap) -> ChangeSet<'a> {
98     let mut visitor = FmtVisitor::from_codemap(codemap);
99     visit::walk_crate(&mut visitor, krate);
100     let files = codemap.files.borrow();
101     if let Some(last) = files.last() {
102         visitor.format_missing(last.end_pos);
103     }
104
105     visitor.changes
106 }
107
108 // Formatting done on a char by char or line by line basis.
109 // TODO warn on TODOs and FIXMEs without an issue number
110 // TODO warn on bad license
111 // TODO other stuff for parity with make tidy
112 fn fmt_lines(changes: &mut ChangeSet) {
113     let mut truncate_todo = Vec::new();
114
115     // Iterate over the chars in the change set.
116     for (f, text) in changes.text() {
117         let mut trims = vec![];
118         let mut last_wspace: Option<usize> = None;
119         let mut line_len = 0;
120         let mut cur_line = 1;
121         let mut newline_count = 0;
122         for (c, b) in text.chars() {
123             if c == '\n' { // TOOD test for \r too
124                 // Check for (and record) trailing whitespace.
125                 if let Some(lw) = last_wspace {
126                     trims.push((cur_line, lw, b));
127                     line_len -= b - lw;
128                 }
129                 // Check for any line width errors we couldn't correct.
130                 if line_len > MAX_WIDTH {
131                     // TODO store the error rather than reporting immediately.
132                     println!("Rustfmt couldn't fix (sorry). {}:{}: line longer than {} characters",
133                              f, cur_line, MAX_WIDTH);
134                 }
135                 line_len = 0;
136                 cur_line += 1;
137                 newline_count += 1;
138                 last_wspace = None;
139             } else {
140                 newline_count = 0;
141                 line_len += 1;
142                 if c.is_whitespace() {
143                     if last_wspace.is_none() {
144                         last_wspace = Some(b);
145                     }
146                 } else {
147                     last_wspace = None;
148                 }
149             }
150         }
151
152         if newline_count > 1 {
153             debug!("track truncate: {} {} {}", f, text.len, newline_count);
154             truncate_todo.push((f.to_string(), text.len - newline_count + 1))
155         }
156
157         for &(l, _, _) in trims.iter() {
158             // TODO store the error rather than reporting immediately.
159             println!("Rustfmt left trailing whitespace at {}:{} (sorry)", f, l);
160         }
161     }
162
163     for (f, l) in truncate_todo {
164         changes.get_mut(&f).truncate(l);
165     }
166 }
167
168 struct RustFmtCalls {
169     input_path: Option<PathBuf>,
170     write_mode: WriteMode,
171 }
172
173 impl<'a> CompilerCalls<'a> for RustFmtCalls {
174     fn early_callback(&mut self,
175                       _: &getopts::Matches,
176                       _: &diagnostics::registry::Registry)
177                       -> Compilation {
178         Compilation::Continue
179     }
180
181     fn some_input(&mut self,
182                   input: Input,
183                   input_path: Option<PathBuf>)
184                   -> (Input, Option<PathBuf>) {
185         match input_path {
186             Some(ref ip) => self.input_path = Some(ip.clone()),
187             _ => {
188                 // FIXME should handle string input and write to stdout or something
189                 panic!("No input path");
190             }
191         }
192         (input, input_path)
193     }
194
195     fn no_input(&mut self,
196                 _: &getopts::Matches,
197                 _: &config::Options,
198                 _: &Option<PathBuf>,
199                 _: &Option<PathBuf>,
200                 _: &diagnostics::registry::Registry)
201                 -> Option<(Input, Option<PathBuf>)> {
202         panic!("No input supplied to RustFmt");
203     }
204
205     fn late_callback(&mut self,
206                      _: &getopts::Matches,
207                      _: &Session,
208                      _: &Input,
209                      _: &Option<PathBuf>,
210                      _: &Option<PathBuf>)
211                      -> Compilation {
212         Compilation::Continue
213     }
214
215     fn build_controller(&mut self, _: &Session) -> driver::CompileController<'a> {
216         let write_mode = self.write_mode;
217         let mut control = driver::CompileController::basic();
218         control.after_parse.stop = Compilation::Stop;
219         control.after_parse.callback = box move |state| {
220             let krate = state.krate.unwrap();
221             let codemap = state.session.codemap();
222             let mut changes = fmt_ast(krate, codemap);
223             // For some reason, the codemap does not include terminating newlines
224             // so we must add one on for each file. This is sad.
225             changes.append_newlines();
226             fmt_lines(&mut changes);
227
228             // FIXME(#5) Should be user specified whether to show or replace.
229             let result = changes.write_all_files(write_mode);
230
231             match result {
232                 Err(msg) => println!("Error writing files: {}", msg),
233                 Ok(result) => {
234                     if let WriteMode::Return(callback) = write_mode {
235                         callback(result);
236                     }
237                 }
238             }
239         };
240
241         control
242     }
243 }
244
245 pub fn run(args: Vec<String>, write_mode: WriteMode) {
246     let mut call_ctxt = RustFmtCalls { input_path: None, write_mode: write_mode };
247     rustc_driver::run_compiler(&args, &mut call_ctxt);
248 }