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