]> git.lizzy.rs Git - rust.git/blob - src/lib.rs
Use impl_enum_decodable for SeparatorTactic
[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 rustc_serialize::{Decodable, Decoder};
37
38 use syntax::ast;
39 use syntax::codemap::CodeMap;
40 use syntax::diagnostics;
41 use syntax::visit;
42
43 use std::path::PathBuf;
44 use std::collections::HashMap;
45
46 use changes::ChangeSet;
47 use visitor::FmtVisitor;
48
49 #[macro_use]
50 mod config;
51 mod changes;
52 mod visitor;
53 mod items;
54 mod missed_spans;
55 mod lists;
56 #[macro_use]
57 mod utils;
58 mod types;
59 mod expr;
60 mod imports;
61
62 const MIN_STRING: usize = 10;
63 // When we get scoped annotations, we should have rustfmt::skip.
64 const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
65
66 static mut CONFIG: Option<config::Config> = None;
67
68 #[derive(Copy, Clone)]
69 pub enum WriteMode {
70     Overwrite,
71     // str is the extension of the new file
72     NewFile(&'static str),
73     // Write the output to stdout.
74     Display,
75     // Return the result as a mapping from filenames to StringBuffers.
76     Return(&'static Fn(HashMap<String, String>)),
77 }
78
79 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
80 pub enum NewlineStyle {
81     Windows, // \r\n
82     Unix, // \n
83 }
84
85 impl_enum_decodable!(NewlineStyle, Windows, Unix);
86
87 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
88 pub enum BraceStyle {
89     AlwaysNextLine,
90     PreferSameLine,
91     // Prefer same line except where there is a where clause, in which case force
92     // the brace to the next line.
93     SameLineWhere,
94 }
95
96 impl_enum_decodable!(BraceStyle, AlwaysNextLine, PreferSameLine, SameLineWhere);
97
98 // How to indent a function's return type.
99 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
100 pub enum ReturnIndent {
101     // Aligned with the arguments
102     WithArgs,
103     // Aligned with the where clause
104     WithWhereClause,
105 }
106
107 impl_enum_decodable!(ReturnIndent, WithArgs, WithWhereClause);
108
109 // Formatting which depends on the AST.
110 fn fmt_ast<'a>(krate: &ast::Crate, codemap: &'a CodeMap) -> ChangeSet<'a> {
111     let mut visitor = FmtVisitor::from_codemap(codemap);
112     visit::walk_crate(&mut visitor, krate);
113     let files = codemap.files.borrow();
114     if let Some(last) = files.last() {
115         visitor.format_missing(last.end_pos);
116     }
117
118     visitor.changes
119 }
120
121 // Formatting done on a char by char or line by line basis.
122 // TODO warn on TODOs and FIXMEs without an issue number
123 // TODO warn on bad license
124 // TODO other stuff for parity with make tidy
125 fn fmt_lines(changes: &mut ChangeSet) {
126     let mut truncate_todo = Vec::new();
127
128     // Iterate over the chars in the change set.
129     for (f, text) in changes.text() {
130         let mut trims = vec![];
131         let mut last_wspace: Option<usize> = None;
132         let mut line_len = 0;
133         let mut cur_line = 1;
134         let mut newline_count = 0;
135         for (c, b) in text.chars() {
136             if c == '\r' { continue; }
137             if c == '\n' {
138                 // Check for (and record) trailing whitespace.
139                 if let Some(lw) = last_wspace {
140                     trims.push((cur_line, lw, b));
141                     line_len -= b - lw;
142                 }
143                 // Check for any line width errors we couldn't correct.
144                 if line_len > config!(max_width) {
145                     // TODO store the error rather than reporting immediately.
146                     println!("Rustfmt couldn't fix (sorry). {}:{}: line longer than {} characters",
147                              f, cur_line, config!(max_width));
148                 }
149                 line_len = 0;
150                 cur_line += 1;
151                 newline_count += 1;
152                 last_wspace = None;
153             } else {
154                 newline_count = 0;
155                 line_len += 1;
156                 if c.is_whitespace() {
157                     if last_wspace.is_none() {
158                         last_wspace = Some(b);
159                     }
160                 } else {
161                     last_wspace = None;
162                 }
163             }
164         }
165
166         if newline_count > 1 {
167             debug!("track truncate: {} {} {}", f, text.len, newline_count);
168             truncate_todo.push((f.to_string(), text.len - newline_count + 1))
169         }
170
171         for &(l, _, _) in trims.iter() {
172             // TODO store the error rather than reporting immediately.
173             println!("Rustfmt left trailing whitespace at {}:{} (sorry)", f, l);
174         }
175     }
176
177     for (f, l) in truncate_todo {
178         changes.get_mut(&f).truncate(l);
179     }
180 }
181
182 struct RustFmtCalls {
183     input_path: Option<PathBuf>,
184     write_mode: WriteMode,
185 }
186
187 impl<'a> CompilerCalls<'a> for RustFmtCalls {
188     fn early_callback(&mut self,
189                       _: &getopts::Matches,
190                       _: &diagnostics::registry::Registry)
191                       -> Compilation {
192         Compilation::Continue
193     }
194
195     fn some_input(&mut self,
196                   input: Input,
197                   input_path: Option<PathBuf>)
198                   -> (Input, Option<PathBuf>) {
199         match input_path {
200             Some(ref ip) => self.input_path = Some(ip.clone()),
201             _ => {
202                 // FIXME should handle string input and write to stdout or something
203                 panic!("No input path");
204             }
205         }
206         (input, input_path)
207     }
208
209     fn no_input(&mut self,
210                 _: &getopts::Matches,
211                 _: &rustc_config::Options,
212                 _: &Option<PathBuf>,
213                 _: &Option<PathBuf>,
214                 _: &diagnostics::registry::Registry)
215                 -> Option<(Input, Option<PathBuf>)> {
216         panic!("No input supplied to RustFmt");
217     }
218
219     fn late_callback(&mut self,
220                      _: &getopts::Matches,
221                      _: &Session,
222                      _: &Input,
223                      _: &Option<PathBuf>,
224                      _: &Option<PathBuf>)
225                      -> Compilation {
226         Compilation::Continue
227     }
228
229     fn build_controller(&mut self, _: &Session) -> driver::CompileController<'a> {
230         let write_mode = self.write_mode;
231         let mut control = driver::CompileController::basic();
232         control.after_parse.stop = Compilation::Stop;
233         control.after_parse.callback = Box::new(move |state| {
234             let krate = state.krate.unwrap();
235             let codemap = state.session.codemap();
236             let mut changes = fmt_ast(krate, codemap);
237             // For some reason, the codemap does not include terminating newlines
238             // so we must add one on for each file. This is sad.
239             changes.append_newlines();
240             fmt_lines(&mut changes);
241
242             let result = changes.write_all_files(write_mode);
243
244             match result {
245                 Err(msg) => println!("Error writing files: {}", msg),
246                 Ok(result) => {
247                     if let WriteMode::Return(callback) = write_mode {
248                         callback(result);
249                     }
250                 }
251             }
252         });
253
254         control
255     }
256 }
257
258 // args are the arguments passed on the command line, generally passed through
259 // to the compiler.
260 // write_mode determines what happens to the result of running rustfmt, see
261 // WriteMode.
262 // default_config is a string of toml data to be used to configure rustfmt.
263 pub fn run(args: Vec<String>, write_mode: WriteMode, default_config: &str) {
264     config::set_config(default_config);
265
266     let mut call_ctxt = RustFmtCalls { input_path: None, write_mode: write_mode };
267     rustc_driver::run_compiler(&args, &mut call_ctxt);
268 }