]> git.lizzy.rs Git - rust.git/blob - src/lib.rs
Format modules into separate files
[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     visitor.changes
171 }
172
173 // Formatting done on a char by char or line by line basis.
174 // TODO warn on bad license
175 // TODO other stuff for parity with make tidy
176 fn fmt_lines(changes: &mut ChangeSet, config: &Config) -> FormatReport {
177     let mut truncate_todo = Vec::new();
178     let mut report = FormatReport { file_error_map: HashMap::new() };
179
180     // Iterate over the chars in the change set.
181     for (f, text) in changes.text() {
182         let mut trims = vec![];
183         let mut last_wspace: Option<usize> = None;
184         let mut line_len = 0;
185         let mut cur_line = 1;
186         let mut newline_count = 0;
187         let mut errors = vec![];
188         let mut issue_seeker = BadIssueSeeker::new(config.report_todo,
189                                                    config.report_fixme);
190
191         for (c, b) in text.chars() {
192             if c == '\r' { continue; }
193
194             // Add warnings for bad todos/ fixmes
195             if let Some(issue) = issue_seeker.inspect(c) {
196                 errors.push(FormattingError {
197                     line: cur_line,
198                     kind: ErrorKind::BadIssue(issue)
199                 });
200             }
201
202             if c == '\n' {
203                 // Check for (and record) trailing whitespace.
204                 if let Some(lw) = last_wspace {
205                     trims.push((cur_line, lw, b));
206                     line_len -= b - lw;
207                 }
208                 // Check for any line width errors we couldn't correct.
209                 if line_len > config.max_width {
210                     errors.push(FormattingError {
211                         line: cur_line,
212                         kind: ErrorKind::LineOverflow
213                     });
214                 }
215                 line_len = 0;
216                 cur_line += 1;
217                 newline_count += 1;
218                 last_wspace = None;
219             } else {
220                 newline_count = 0;
221                 line_len += 1;
222                 if c.is_whitespace() {
223                     if last_wspace.is_none() {
224                         last_wspace = Some(b);
225                     }
226                 } else {
227                     last_wspace = None;
228                 }
229             }
230         }
231
232         if newline_count > 1 {
233             debug!("track truncate: {} {} {}", f, text.len, newline_count);
234             truncate_todo.push((f.to_owned(), text.len - newline_count + 1))
235         }
236
237         for &(l, _, _) in trims.iter() {
238             errors.push(FormattingError {
239                 line: l,
240                 kind: ErrorKind::TrailingWhitespace
241             });
242         }
243
244         report.file_error_map.insert(f.to_owned(), errors);
245     }
246
247     for (f, l) in truncate_todo {
248         changes.get_mut(&f).truncate(l);
249     }
250
251     report
252 }
253
254 struct RustFmtCalls {
255     input_path: Option<PathBuf>,
256     write_mode: WriteMode,
257     config: Option<Box<config::Config>>,
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
305         let mut config_option = None;
306         swap(&mut self.config, &mut config_option);
307         let config = config_option.unwrap();
308
309         let mut control = driver::CompileController::basic();
310         control.after_parse.stop = Compilation::Stop;
311         control.after_parse.callback = Box::new(move |state| {
312             let krate = state.krate.unwrap();
313             let codemap = state.session.codemap();
314             let mut changes = fmt_ast(krate, codemap, &*config);
315             // For some reason, the codemap does not include terminating newlines
316             // so we must add one on for each file. This is sad.
317             changes.append_newlines();
318             println!("{}", fmt_lines(&mut changes, &*config));
319
320             let result = changes.write_all_files(write_mode, &*config);
321
322             match result {
323                 Err(msg) => println!("Error writing files: {}", msg),
324                 Ok(result) => {
325                     if let WriteMode::Return(callback) = write_mode {
326                         callback(result);
327                     }
328                 }
329             }
330         });
331
332         control
333     }
334 }
335
336 // args are the arguments passed on the command line, generally passed through
337 // to the compiler.
338 // write_mode determines what happens to the result of running rustfmt, see
339 // WriteMode.
340 // default_config is a string of toml data to be used to configure rustfmt.
341 pub fn run(args: Vec<String>, write_mode: WriteMode, default_config: &str) {
342     let config = Some(Box::new(config::Config::from_toml(default_config)));
343     let mut call_ctxt = RustFmtCalls { input_path: None, write_mode: write_mode, config: config };
344     rustc_driver::run_compiler(&args, &mut call_ctxt);
345 }