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