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