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