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