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 // TODO we're going to allocate a whole bunch of temp Strings, is it worth
12 // keeping some scratch mem for this and running our own StrPool?
13 // TODO for lint violations of names, emit a refactor script
18 extern crate syntex_syntax as syntax;
19 extern crate rustc_serialize;
23 extern crate unicode_segmentation;
29 use syntax::codemap::{mk_sp, Span};
30 use syntax::diagnostic::{EmitterWriter, Handler};
31 use syntax::parse::{self, ParseSess};
34 use std::ops::{Add, Sub};
36 use std::collections::HashMap;
39 use issues::{BadIssueSeeker, Issue};
41 use visitor::FmtVisitor;
42 use config::{Config, WriteMode};
66 const MIN_STRING: usize = 10;
67 // When we get scoped annotations, we should have rustfmt::skip.
68 const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
71 fn span(&self) -> Span;
74 impl Spanned for ast::Expr {
75 fn span(&self) -> Span {
80 impl Spanned for ast::Pat {
81 fn span(&self) -> Span {
86 impl Spanned for ast::Ty {
87 fn span(&self) -> Span {
92 impl Spanned for ast::Arg {
93 fn span(&self) -> Span {
94 if items::is_named_arg(self) {
95 mk_sp(self.pat.span.lo, self.ty.span.hi)
102 #[derive(Copy, Clone, Debug)]
104 // Width of the block indent, in characters. Must be a multiple of
105 // Config::tab_spaces.
106 pub block_indent: usize,
107 // Alignment in characters.
108 pub alignment: usize,
112 pub fn new(block_indent: usize, alignment: usize) -> Indent {
114 block_indent: block_indent,
115 alignment: alignment,
119 pub fn empty() -> Indent {
123 pub fn block_indent(mut self, config: &Config) -> Indent {
124 self.block_indent += config.tab_spaces;
128 pub fn block_unindent(mut self, config: &Config) -> Indent {
129 self.block_indent -= config.tab_spaces;
133 pub fn width(&self) -> usize {
134 self.block_indent + self.alignment
137 pub fn to_string(&self, config: &Config) -> String {
138 let (num_tabs, num_spaces) = if config.hard_tabs {
139 (self.block_indent / config.tab_spaces, self.alignment)
141 (0, self.block_indent + self.alignment)
143 let num_chars = num_tabs + num_spaces;
144 let mut indent = String::with_capacity(num_chars);
145 for _ in 0..num_tabs {
148 for _ in 0..num_spaces {
155 impl Add for Indent {
156 type Output = Indent;
158 fn add(self, rhs: Indent) -> Indent {
160 block_indent: self.block_indent + rhs.block_indent,
161 alignment: self.alignment + rhs.alignment,
166 impl Sub for Indent {
167 type Output = Indent;
169 fn sub(self, rhs: Indent) -> Indent {
170 Indent::new(self.block_indent - rhs.block_indent,
171 self.alignment - rhs.alignment)
175 impl Add<usize> for Indent {
176 type Output = Indent;
178 fn add(self, rhs: usize) -> Indent {
179 Indent::new(self.block_indent, self.alignment + rhs)
183 impl Sub<usize> for Indent {
184 type Output = Indent;
186 fn sub(self, rhs: usize) -> Indent {
187 Indent::new(self.block_indent, self.alignment - rhs)
192 // Line has exceeded character limit
194 // Line ends in whitespace
196 // TO-DO or FIX-ME item without an issue number
200 impl fmt::Display for ErrorKind {
201 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
203 ErrorKind::LineOverflow => write!(fmt, "line exceeded maximum length"),
204 ErrorKind::TrailingWhitespace => write!(fmt, "left behind trailing whitespace"),
205 ErrorKind::BadIssue(issue) => write!(fmt, "found {}", issue),
210 // Formatting errors that are identified *after* rustfmt has run.
211 pub struct FormattingError {
216 impl FormattingError {
217 fn msg_prefix(&self) -> &str {
219 ErrorKind::LineOverflow |
220 ErrorKind::TrailingWhitespace => "Rustfmt failed at",
221 ErrorKind::BadIssue(_) => "WARNING:",
225 fn msg_suffix(&self) -> &str {
227 ErrorKind::LineOverflow |
228 ErrorKind::TrailingWhitespace => "(sorry)",
229 ErrorKind::BadIssue(_) => "",
234 pub struct FormatReport {
235 // Maps stringified file paths to their associated formatting errors.
236 file_error_map: HashMap<String, Vec<FormattingError>>,
240 pub fn warning_count(&self) -> usize {
241 self.file_error_map.iter().map(|(_, ref errors)| errors.len()).fold(0, |acc, x| acc + x)
245 impl fmt::Display for FormatReport {
246 // Prints all the formatting errors.
247 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
248 for (file, errors) in &self.file_error_map {
249 for error in errors {
256 error.msg_suffix()));
263 // Formatting which depends on the AST.
264 fn fmt_ast(krate: &ast::Crate,
265 parse_session: &ParseSess,
270 let mut file_map = FileMap::new();
271 for (path, module) in modules::list_files(krate, parse_session.codemap()) {
272 if config.skip_children && path.as_path() != main_file {
275 let path = path.to_str().unwrap();
277 println!("Formatting {}", path);
279 let mut visitor = FmtVisitor::from_codemap(parse_session, config, Some(mode));
280 visitor.format_separate_mod(module);
281 file_map.insert(path.to_owned(), visitor.buffer);
286 // Formatting done on a char by char or line by line basis.
287 // TODO(#209) warn on bad license
288 // TODO(#20) other stuff for parity with make tidy
289 pub fn fmt_lines(file_map: &mut FileMap, config: &Config) -> FormatReport {
290 let mut truncate_todo = Vec::new();
291 let mut report = FormatReport { file_error_map: HashMap::new() };
293 // Iterate over the chars in the file map.
294 for (f, text) in file_map.iter() {
295 let mut trims = vec![];
296 let mut last_wspace: Option<usize> = None;
297 let mut line_len = 0;
298 let mut cur_line = 1;
299 let mut newline_count = 0;
300 let mut errors = vec![];
301 let mut issue_seeker = BadIssueSeeker::new(config.report_todo, config.report_fixme);
303 for (c, b) in text.chars() {
305 line_len += c.len_utf8();
309 // Add warnings for bad todos/ fixmes
310 if let Some(issue) = issue_seeker.inspect(c) {
311 errors.push(FormattingError {
313 kind: ErrorKind::BadIssue(issue),
318 // Check for (and record) trailing whitespace.
319 if let Some(lw) = last_wspace {
320 trims.push((cur_line, lw, b));
323 // Check for any line width errors we couldn't correct.
324 if line_len > config.max_width {
325 errors.push(FormattingError {
327 kind: ErrorKind::LineOverflow,
336 line_len += c.len_utf8();
337 if c.is_whitespace() {
338 if last_wspace.is_none() {
339 last_wspace = Some(b);
347 if newline_count > 1 {
348 debug!("track truncate: {} {} {}", f, text.len, newline_count);
349 truncate_todo.push((f.to_owned(), text.len - newline_count + 1))
352 for &(l, _, _) in &trims {
353 errors.push(FormattingError {
355 kind: ErrorKind::TrailingWhitespace,
359 report.file_error_map.insert(f.to_owned(), errors);
362 for (f, l) in truncate_todo {
363 file_map.get_mut(&f).unwrap().truncate(l);
369 pub fn format_string(input: String, config: &Config, mode: WriteMode) -> FileMap {
371 let mut parse_session = ParseSess::new();
372 let krate = parse::parse_crate_from_source_str(path.to_owned(),
377 // Suppress error output after parsing.
378 let emitter = Box::new(EmitterWriter::new(Box::new(Vec::new()), None));
379 parse_session.span_diagnostic.handler = Handler::with_emitter(false, emitter);
381 // FIXME: we still use a FileMap even though we only have
382 // one file, because fmt_lines requires a FileMap
383 let mut file_map = FileMap::new();
385 // do the actual formatting
386 let mut visitor = FmtVisitor::from_codemap(&parse_session, config, Some(mode));
387 visitor.format_separate_mod(&krate.module);
389 // append final newline
390 visitor.buffer.push_str("\n");
391 file_map.insert(path.to_owned(), visitor.buffer);
396 pub fn format(file: &Path, config: &Config, mode: WriteMode) -> FileMap {
397 let mut parse_session = ParseSess::new();
398 let krate = parse::parse_crate_from_file(file, Vec::new(), &parse_session);
400 // Suppress error output after parsing.
401 let emitter = Box::new(EmitterWriter::new(Box::new(Vec::new()), None));
402 parse_session.span_diagnostic.handler = Handler::with_emitter(false, emitter);
404 let mut file_map = fmt_ast(&krate, &parse_session, file, config, mode);
406 // For some reason, the codemap does not include terminating
407 // newlines so we must add one on for each file. This is sad.
408 filemap::append_newlines(&mut file_map);
413 // Make sure that we are using the correct WriteMode,
414 // preferring what is passed as an argument
415 fn check_write_mode(arg: WriteMode, config: WriteMode) -> WriteMode {
416 match (arg, config) {
417 (WriteMode::Default, WriteMode::Default) => WriteMode::Replace,
418 (WriteMode::Default, mode) => mode,
423 // args are the arguments passed on the command line, generally passed through
425 // write_mode determines what happens to the result of running rustfmt, see
427 pub fn run(file: &Path, write_mode: WriteMode, config: &Config) {
428 let mode = check_write_mode(write_mode, config.write_mode);
429 let mut result = format(file, config, mode);
431 print!("{}", fmt_lines(&mut result, config));
433 let write_result = filemap::write_all_files(&result, out, mode, config);
435 if let Err(msg) = write_result {
436 println!("Error writing files: {}", msg);
440 // Similar to run, but takes an input String instead of a file to format
441 pub fn run_from_stdin(input: String, write_mode: WriteMode, config: &Config) {
442 let mode = check_write_mode(write_mode, config.write_mode);
443 let mut result = format_string(input, config, mode);
444 fmt_lines(&mut result, config);
446 let mut out = stdout();
447 let write_result = filemap::write_file(&result["stdin"], "stdin", &mut out, mode, config);
449 if let Err(msg) = write_result {
450 panic!("Error writing to stdout: {}", msg);