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