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.
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.
11 #![feature(rustc_private)]
12 #![feature(collections)]
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
25 extern crate rustc_driver;
27 extern crate rustc_serialize;
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};
36 use rustc_serialize::{Decodable, Decoder};
39 use syntax::codemap::CodeMap;
40 use syntax::diagnostics;
43 use std::path::PathBuf;
44 use std::collections::HashMap;
46 use changes::ChangeSet;
47 use visitor::FmtVisitor;
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";
66 static mut CONFIG: Option<config::Config> = None;
68 #[derive(Copy, Clone)]
71 // str is the extension of the new file
72 NewFile(&'static str),
73 // Write the output to stdout.
75 // Return the result as a mapping from filenames to StringBuffers.
76 Return(&'static Fn(HashMap<String, String>)),
79 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
80 pub enum NewlineStyle {
85 impl_enum_decodable!(NewlineStyle, Windows, Unix);
87 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
91 // Prefer same line except where there is a where clause, in which case force
92 // the brace to the next line.
96 impl_enum_decodable!(BraceStyle, AlwaysNextLine, PreferSameLine, SameLineWhere);
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
103 // Aligned with the where clause
107 impl_enum_decodable!(ReturnIndent, WithArgs, WithWhereClause);
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);
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();
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; }
138 // Check for (and record) trailing whitespace.
139 if let Some(lw) = last_wspace {
140 trims.push((cur_line, lw, b));
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));
156 if c.is_whitespace() {
157 if last_wspace.is_none() {
158 last_wspace = Some(b);
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))
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);
177 for (f, l) in truncate_todo {
178 changes.get_mut(&f).truncate(l);
182 struct RustFmtCalls {
183 input_path: Option<PathBuf>,
184 write_mode: WriteMode,
187 impl<'a> CompilerCalls<'a> for RustFmtCalls {
188 fn early_callback(&mut self,
189 _: &getopts::Matches,
190 _: &diagnostics::registry::Registry)
192 Compilation::Continue
195 fn some_input(&mut self,
197 input_path: Option<PathBuf>)
198 -> (Input, Option<PathBuf>) {
200 Some(ref ip) => self.input_path = Some(ip.clone()),
202 // FIXME should handle string input and write to stdout or something
203 panic!("No input path");
209 fn no_input(&mut self,
210 _: &getopts::Matches,
211 _: &rustc_config::Options,
214 _: &diagnostics::registry::Registry)
215 -> Option<(Input, Option<PathBuf>)> {
216 panic!("No input supplied to RustFmt");
219 fn late_callback(&mut self,
220 _: &getopts::Matches,
226 Compilation::Continue
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);
242 let result = changes.write_all_files(write_mode);
245 Err(msg) => println!("Error writing files: {}", msg),
247 if let WriteMode::Return(callback) = write_mode {
258 // args are the arguments passed on the command line, generally passed through
260 // write_mode determines what happens to the result of running rustfmt, see
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);
266 let mut call_ctxt = RustFmtCalls { input_path: None, write_mode: write_mode };
267 rustc_driver::run_compiler(&args, &mut call_ctxt);