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, CodeMap, Span};
30 use syntax::errors::{Handler, DiagnosticBuilder};
31 use syntax::errors::emitter::{ColorConfig, EmitterWriter};
32 use syntax::parse::{self, ParseSess};
34 use std::io::{stdout, Write};
35 use std::ops::{Add, Sub};
36 use std::path::{Path, PathBuf};
38 use std::collections::HashMap;
41 use issues::{BadIssueSeeker, Issue};
43 use visitor::FmtVisitor;
46 pub use self::summary::Summary;
71 const MIN_STRING: usize = 10;
72 // When we get scoped annotations, we should have rustfmt::skip.
73 const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
76 fn span(&self) -> Span;
79 impl Spanned for ast::Expr {
80 fn span(&self) -> Span {
85 impl Spanned for ast::Pat {
86 fn span(&self) -> Span {
91 impl Spanned for ast::Ty {
92 fn span(&self) -> Span {
97 impl Spanned for ast::Arg {
98 fn span(&self) -> Span {
99 if items::is_named_arg(self) {
100 mk_sp(self.pat.span.lo, self.ty.span.hi)
107 #[derive(Copy, Clone, Debug)]
109 // Width of the block indent, in characters. Must be a multiple of
110 // Config::tab_spaces.
111 pub block_indent: usize,
112 // Alignment in characters.
113 pub alignment: usize,
117 pub fn new(block_indent: usize, alignment: usize) -> Indent {
119 block_indent: block_indent,
120 alignment: alignment,
124 pub fn empty() -> Indent {
128 pub fn block_indent(mut self, config: &Config) -> Indent {
129 self.block_indent += config.tab_spaces;
133 pub fn block_unindent(mut self, config: &Config) -> Indent {
134 self.block_indent -= config.tab_spaces;
138 pub fn width(&self) -> usize {
139 self.block_indent + self.alignment
142 pub fn to_string(&self, config: &Config) -> String {
143 let (num_tabs, num_spaces) = if config.hard_tabs {
144 (self.block_indent / config.tab_spaces, self.alignment)
146 (0, self.block_indent + self.alignment)
148 let num_chars = num_tabs + num_spaces;
149 let mut indent = String::with_capacity(num_chars);
150 for _ in 0..num_tabs {
153 for _ in 0..num_spaces {
160 impl Add for Indent {
161 type Output = Indent;
163 fn add(self, rhs: Indent) -> Indent {
165 block_indent: self.block_indent + rhs.block_indent,
166 alignment: self.alignment + rhs.alignment,
171 impl Sub for Indent {
172 type Output = Indent;
174 fn sub(self, rhs: Indent) -> Indent {
175 Indent::new(self.block_indent - rhs.block_indent,
176 self.alignment - rhs.alignment)
180 impl Add<usize> for Indent {
181 type Output = Indent;
183 fn add(self, rhs: usize) -> Indent {
184 Indent::new(self.block_indent, self.alignment + rhs)
188 impl Sub<usize> for Indent {
189 type Output = Indent;
191 fn sub(self, rhs: usize) -> Indent {
192 Indent::new(self.block_indent, self.alignment - rhs)
197 // Line has exceeded character limit
199 // Line ends in whitespace
201 // TO-DO or FIX-ME item without an issue number
205 impl fmt::Display for ErrorKind {
206 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
208 ErrorKind::LineOverflow => write!(fmt, "line exceeded maximum length"),
209 ErrorKind::TrailingWhitespace => write!(fmt, "left behind trailing whitespace"),
210 ErrorKind::BadIssue(issue) => write!(fmt, "found {}", issue),
215 // Formatting errors that are identified *after* rustfmt has run.
216 pub struct FormattingError {
221 impl FormattingError {
222 fn msg_prefix(&self) -> &str {
224 ErrorKind::LineOverflow |
225 ErrorKind::TrailingWhitespace => "Rustfmt failed at",
226 ErrorKind::BadIssue(_) => "WARNING:",
230 fn msg_suffix(&self) -> &str {
232 ErrorKind::LineOverflow |
233 ErrorKind::TrailingWhitespace => "(sorry)",
234 ErrorKind::BadIssue(_) => "",
239 pub struct FormatReport {
240 // Maps stringified file paths to their associated formatting errors.
241 file_error_map: HashMap<String, Vec<FormattingError>>,
245 fn new() -> FormatReport {
246 FormatReport { file_error_map: HashMap::new() }
249 pub fn warning_count(&self) -> usize {
250 self.file_error_map.iter().map(|(_, ref errors)| errors.len()).fold(0, |acc, x| acc + x)
253 pub fn has_warnings(&self) -> bool {
254 self.warning_count() > 0
258 impl fmt::Display for FormatReport {
259 // Prints all the formatting errors.
260 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
261 for (file, errors) in &self.file_error_map {
262 for error in errors {
269 error.msg_suffix()));
276 // Formatting which depends on the AST.
277 fn format_ast(krate: &ast::Crate,
278 parse_session: &ParseSess,
282 let mut file_map = FileMap::new();
283 for (path, module) in modules::list_files(krate, parse_session.codemap()) {
284 if config.skip_children && path.as_path() != main_file {
287 let path = path.to_str().unwrap();
289 println!("Formatting {}", path);
291 let mut visitor = FmtVisitor::from_codemap(parse_session, config);
292 visitor.format_separate_mod(module);
293 file_map.insert(path.to_owned(), visitor.buffer);
298 // Formatting done on a char by char or line by line basis.
299 // TODO(#209) warn on bad license
300 // TODO(#20) other stuff for parity with make tidy
301 fn format_lines(file_map: &mut FileMap, config: &Config) -> FormatReport {
302 let mut truncate_todo = Vec::new();
303 let mut report = FormatReport::new();
305 // Iterate over the chars in the file map.
306 for (f, text) in file_map.iter() {
307 let mut trims = vec![];
308 let mut last_wspace: Option<usize> = None;
309 let mut line_len = 0;
310 let mut cur_line = 1;
311 let mut newline_count = 0;
312 let mut errors = vec![];
313 let mut issue_seeker = BadIssueSeeker::new(config.report_todo, config.report_fixme);
315 for (c, b) in text.chars() {
317 line_len += c.len_utf8();
321 // Add warnings for bad todos/ fixmes
322 if let Some(issue) = issue_seeker.inspect(c) {
323 errors.push(FormattingError {
325 kind: ErrorKind::BadIssue(issue),
330 // Check for (and record) trailing whitespace.
331 if let Some(lw) = last_wspace {
332 trims.push((cur_line, lw, b));
335 // Check for any line width errors we couldn't correct.
336 if line_len > config.max_width {
337 errors.push(FormattingError {
339 kind: ErrorKind::LineOverflow,
348 line_len += c.len_utf8();
349 if c.is_whitespace() {
350 if last_wspace.is_none() {
351 last_wspace = Some(b);
359 if newline_count > 1 {
360 debug!("track truncate: {} {} {}", f, text.len, newline_count);
361 truncate_todo.push((f.to_owned(), text.len - newline_count + 1))
364 for &(l, _, _) in &trims {
365 errors.push(FormattingError {
367 kind: ErrorKind::TrailingWhitespace,
371 report.file_error_map.insert(f.to_owned(), errors);
374 for (f, l) in truncate_todo {
375 file_map.get_mut(&f).unwrap().truncate(l);
381 fn parse_input(input: Input, parse_session: &ParseSess) -> Result<ast::Crate, DiagnosticBuilder> {
383 Input::File(file) => parse::parse_crate_from_file(&file, Vec::new(), &parse_session),
384 Input::Text(text) => {
385 parse::parse_crate_from_source_str("stdin".to_owned(), text, Vec::new(), &parse_session)
390 pub fn format_input(input: Input, config: &Config) -> (Summary, FileMap, FormatReport) {
391 let mut summary = Summary::new();
392 let codemap = Rc::new(CodeMap::new());
394 let tty_handler = Handler::with_tty_emitter(ColorConfig::Auto,
399 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
401 let main_file = match input {
402 Input::File(ref file) => file.clone(),
403 Input::Text(..) => PathBuf::from("stdin"),
406 let krate = match parse_input(input, &parse_session) {
408 Err(mut diagnostic) => {
410 summary.add_parsing_error();
411 return (summary, FileMap::new(), FormatReport::new());
415 if parse_session.span_diagnostic.has_errors() {
416 summary.add_parsing_error();
419 // Suppress error output after parsing.
420 let silent_emitter = Box::new(EmitterWriter::new(Box::new(Vec::new()), None, codemap.clone()));
421 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
423 let mut file_map = format_ast(&krate, &parse_session, &main_file, config);
425 // For some reason, the codemap does not include terminating
426 // newlines so we must add one on for each file. This is sad.
427 filemap::append_newlines(&mut file_map);
429 let report = format_lines(&mut file_map, config);
430 if report.has_warnings() {
431 summary.add_formatting_error();
433 (summary, file_map, report)
441 pub fn run(input: Input, config: &Config) -> Summary {
442 let (mut summary, file_map, report) = format_input(input, config);
443 if report.has_warnings() {
447 let mut out = stdout();
448 let write_result = filemap::write_all_files(&file_map, &mut out, config);
450 if let Err(msg) = write_result {
451 msg!("Error writing files: {}", msg);
452 summary.add_operational_error();