]> git.lizzy.rs Git - rust.git/blob - src/lib.rs
Merge pull request #90 from marcusklaas/empty-imports
[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(str_escape)]
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 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 use std::fmt;
44
45 use issues::{BadIssueSeeker, Issue};
46 use changes::ChangeSet;
47 use visitor::FmtVisitor;
48
49 #[macro_use]
50 mod config;
51 #[macro_use]
52 mod utils;
53 mod changes;
54 mod visitor;
55 mod items;
56 mod missed_spans;
57 mod lists;
58 mod types;
59 mod expr;
60 mod imports;
61 mod issues;
62 mod rewrite;
63
64 const MIN_STRING: usize = 10;
65 // When we get scoped annotations, we should have rustfmt::skip.
66 const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
67
68 static mut CONFIG: Option<config::Config> = None;
69
70 #[derive(Copy, Clone)]
71 pub enum WriteMode {
72     Overwrite,
73     // str is the extension of the new file
74     NewFile(&'static str),
75     // Write the output to stdout.
76     Display,
77     // Return the result as a mapping from filenames to StringBuffers.
78     Return(&'static Fn(HashMap<String, String>)),
79 }
80
81 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
82 pub enum NewlineStyle {
83     Windows, // \r\n
84     Unix, // \n
85 }
86
87 impl_enum_decodable!(NewlineStyle, Windows, Unix);
88
89 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
90 pub enum BraceStyle {
91     AlwaysNextLine,
92     PreferSameLine,
93     // Prefer same line except where there is a where clause, in which case force
94     // the brace to the next line.
95     SameLineWhere,
96 }
97
98 impl_enum_decodable!(BraceStyle, AlwaysNextLine, PreferSameLine, SameLineWhere);
99
100 // How to indent a function's return type.
101 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
102 pub enum ReturnIndent {
103     // Aligned with the arguments
104     WithArgs,
105     // Aligned with the where clause
106     WithWhereClause,
107 }
108
109 impl_enum_decodable!(ReturnIndent, WithArgs, WithWhereClause);
110
111 enum ErrorKind {
112     // Line has more than config!(max_width) characters
113     LineOverflow,
114     // Line ends in whitespace
115     TrailingWhitespace,
116     // TO-DO or FIX-ME item without an issue number
117     BadIssue(Issue),
118 }
119
120 impl fmt::Display for ErrorKind {
121     fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
122         match *self {
123             ErrorKind::LineOverflow => {
124                 write!(fmt, "line exceeded maximum length")
125             },
126             ErrorKind::TrailingWhitespace => {
127                 write!(fmt, "left behind trailing whitespace")
128             },
129             ErrorKind::BadIssue(issue) => {
130                 write!(fmt, "found {}", issue)
131             },
132         }
133     }
134 }
135
136 // Formatting errors that are identified *after* rustfmt has run
137 struct FormattingError {
138     line: u32,
139     kind: ErrorKind,
140 }
141
142 struct FormatReport {
143     // Maps stringified file paths to their associated formatting errors
144     file_error_map: HashMap<String, Vec<FormattingError>>,
145 }
146
147 impl fmt::Display for FormatReport {
148     // Prints all the formatting errors.
149     fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
150         for (file, errors) in self.file_error_map.iter() {
151             for error in errors {
152                 try!(write!(fmt,
153                             "Rustfmt failed at {}:{}: {} (sorry)\n",
154                             file,
155                             error.line,
156                             error.kind));
157             }
158         }
159         Ok(())
160     }
161 }
162
163 // Formatting which depends on the AST.
164 fn fmt_ast<'a>(krate: &ast::Crate, codemap: &'a CodeMap) -> ChangeSet<'a> {
165     let mut visitor = FmtVisitor::from_codemap(codemap);
166     visit::walk_crate(&mut visitor, krate);
167     let files = codemap.files.borrow();
168     if let Some(last) = files.last() {
169         visitor.format_missing(last.end_pos);
170     }
171
172     visitor.changes
173 }
174
175 // Formatting done on a char by char or line by line basis.
176 // TODO warn on bad license
177 // TODO other stuff for parity with make tidy
178 fn fmt_lines(changes: &mut ChangeSet) -> FormatReport {
179     let mut truncate_todo = Vec::new();
180     let mut report = FormatReport { file_error_map: HashMap::new() };
181
182     // Iterate over the chars in the change set.
183     for (f, text) in changes.text() {
184         let mut trims = vec![];
185         let mut last_wspace: Option<usize> = None;
186         let mut line_len = 0;
187         let mut cur_line = 1;
188         let mut newline_count = 0;
189         let mut errors = vec![];
190         let mut issue_seeker = BadIssueSeeker::new(config!(report_todo),
191                                                    config!(report_fixme));
192
193         for (c, b) in text.chars() {
194             if c == '\r' { continue; }
195
196             // Add warnings for bad todos/ fixmes
197             if let Some(issue) = issue_seeker.inspect(c) {
198                 errors.push(FormattingError {
199                     line: cur_line,
200                     kind: ErrorKind::BadIssue(issue)
201                 });
202             }
203
204             if c == '\n' {
205                 // Check for (and record) trailing whitespace.
206                 if let Some(lw) = last_wspace {
207                     trims.push((cur_line, lw, b));
208                     line_len -= b - lw;
209                 }
210                 // Check for any line width errors we couldn't correct.
211                 if line_len > config!(max_width) {
212                     errors.push(FormattingError {
213                         line: cur_line,
214                         kind: ErrorKind::LineOverflow
215                     });
216                 }
217                 line_len = 0;
218                 cur_line += 1;
219                 newline_count += 1;
220                 last_wspace = None;
221             } else {
222                 newline_count = 0;
223                 line_len += 1;
224                 if c.is_whitespace() {
225                     if last_wspace.is_none() {
226                         last_wspace = Some(b);
227                     }
228                 } else {
229                     last_wspace = None;
230                 }
231             }
232         }
233
234         if newline_count > 1 {
235             debug!("track truncate: {} {} {}", f, text.len, newline_count);
236             truncate_todo.push((f.to_owned(), text.len - newline_count + 1))
237         }
238
239         for &(l, _, _) in trims.iter() {
240             errors.push(FormattingError {
241                 line: l,
242                 kind: ErrorKind::TrailingWhitespace
243             });
244         }
245
246         report.file_error_map.insert(f.to_owned(), errors);
247     }
248
249     for (f, l) in truncate_todo {
250         changes.get_mut(&f).truncate(l);
251     }
252
253     report
254 }
255
256 struct RustFmtCalls {
257     input_path: Option<PathBuf>,
258     write_mode: WriteMode,
259 }
260
261 impl<'a> CompilerCalls<'a> for RustFmtCalls {
262     fn early_callback(&mut self,
263                       _: &getopts::Matches,
264                       _: &diagnostics::registry::Registry)
265                       -> Compilation {
266         Compilation::Continue
267     }
268
269     fn some_input(&mut self,
270                   input: Input,
271                   input_path: Option<PathBuf>)
272                   -> (Input, Option<PathBuf>) {
273         match input_path {
274             Some(ref ip) => self.input_path = Some(ip.clone()),
275             _ => {
276                 // FIXME should handle string input and write to stdout or something
277                 panic!("No input path");
278             }
279         }
280         (input, input_path)
281     }
282
283     fn no_input(&mut self,
284                 _: &getopts::Matches,
285                 _: &rustc_config::Options,
286                 _: &Option<PathBuf>,
287                 _: &Option<PathBuf>,
288                 _: &diagnostics::registry::Registry)
289                 -> Option<(Input, Option<PathBuf>)> {
290         panic!("No input supplied to RustFmt");
291     }
292
293     fn late_callback(&mut self,
294                      _: &getopts::Matches,
295                      _: &Session,
296                      _: &Input,
297                      _: &Option<PathBuf>,
298                      _: &Option<PathBuf>)
299                      -> Compilation {
300         Compilation::Continue
301     }
302
303     fn build_controller(&mut self, _: &Session) -> driver::CompileController<'a> {
304         let write_mode = self.write_mode;
305         let mut control = driver::CompileController::basic();
306         control.after_parse.stop = Compilation::Stop;
307         control.after_parse.callback = Box::new(move |state| {
308             let krate = state.krate.unwrap();
309             let codemap = state.session.codemap();
310             let mut changes = fmt_ast(krate, codemap);
311             // For some reason, the codemap does not include terminating newlines
312             // so we must add one on for each file. This is sad.
313             changes.append_newlines();
314             println!("{}", fmt_lines(&mut changes));
315
316             let result = changes.write_all_files(write_mode);
317
318             match result {
319                 Err(msg) => println!("Error writing files: {}", msg),
320                 Ok(result) => {
321                     if let WriteMode::Return(callback) = write_mode {
322                         callback(result);
323                     }
324                 }
325             }
326         });
327
328         control
329     }
330 }
331
332 // args are the arguments passed on the command line, generally passed through
333 // to the compiler.
334 // write_mode determines what happens to the result of running rustfmt, see
335 // WriteMode.
336 // default_config is a string of toml data to be used to configure rustfmt.
337 pub fn run(args: Vec<String>, write_mode: WriteMode, default_config: &str) {
338     config::set_config(default_config);
339
340     let mut call_ctxt = RustFmtCalls { input_path: None, write_mode: write_mode };
341     rustc_driver::run_compiler(&args, &mut call_ctxt);
342 }