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 syntex_errors as errors;
20 extern crate rustc_serialize;
24 extern crate unicode_segmentation;
28 extern crate itertools;
29 extern crate multimap;
31 use errors::{Handler, DiagnosticBuilder};
32 use errors::emitter::{ColorConfig, EmitterWriter};
34 use syntax::codemap::{mk_sp, CodeMap, Span};
35 use syntax::parse::{self, ParseSess};
37 use strings::string_buffer::StringBuffer;
39 use std::io::{self, stdout, Write};
40 use std::ops::{Add, Sub};
41 use std::path::{Path, PathBuf};
43 use std::collections::HashMap;
46 use issues::{BadIssueSeeker, Issue};
48 use visitor::FmtVisitor;
50 use checkstyle::{output_header, output_footer};
52 pub use self::summary::Summary;
79 const MIN_STRING: usize = 10;
80 // When we get scoped annotations, we should have rustfmt::skip.
81 const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
84 fn span(&self) -> Span;
87 impl Spanned for ast::Expr {
88 fn span(&self) -> Span {
93 impl Spanned for ast::Pat {
94 fn span(&self) -> Span {
99 impl Spanned for ast::Ty {
100 fn span(&self) -> Span {
105 impl Spanned for ast::Arg {
106 fn span(&self) -> Span {
107 if items::is_named_arg(self) {
108 mk_sp(self.pat.span.lo, self.ty.span.hi)
115 #[derive(Copy, Clone, Debug)]
117 // Width of the block indent, in characters. Must be a multiple of
118 // Config::tab_spaces.
119 pub block_indent: usize,
120 // Alignment in characters.
121 pub alignment: usize,
125 pub fn new(block_indent: usize, alignment: usize) -> Indent {
127 block_indent: block_indent,
128 alignment: alignment,
132 pub fn empty() -> Indent {
136 pub fn block_only(&self) -> Indent {
138 block_indent: self.block_indent,
143 pub fn block_indent(mut self, config: &Config) -> Indent {
144 self.block_indent += config.tab_spaces;
148 pub fn block_unindent(mut self, config: &Config) -> Indent {
149 self.block_indent -= config.tab_spaces;
153 pub fn width(&self) -> usize {
154 self.block_indent + self.alignment
157 pub fn to_string(&self, config: &Config) -> String {
158 let (num_tabs, num_spaces) = if config.hard_tabs {
159 (self.block_indent / config.tab_spaces, self.alignment)
161 (0, self.block_indent + self.alignment)
163 let num_chars = num_tabs + num_spaces;
164 let mut indent = String::with_capacity(num_chars);
165 for _ in 0..num_tabs {
168 for _ in 0..num_spaces {
175 impl Add for Indent {
176 type Output = Indent;
178 fn add(self, rhs: Indent) -> Indent {
180 block_indent: self.block_indent + rhs.block_indent,
181 alignment: self.alignment + rhs.alignment,
186 impl Sub for Indent {
187 type Output = Indent;
189 fn sub(self, rhs: Indent) -> Indent {
190 Indent::new(self.block_indent - rhs.block_indent,
191 self.alignment - rhs.alignment)
195 impl Add<usize> for Indent {
196 type Output = Indent;
198 fn add(self, rhs: usize) -> Indent {
199 Indent::new(self.block_indent, self.alignment + rhs)
203 impl Sub<usize> for Indent {
204 type Output = Indent;
206 fn sub(self, rhs: usize) -> Indent {
207 Indent::new(self.block_indent, self.alignment - rhs)
211 #[derive(Copy, Clone, Debug)]
214 // The current indentation of code.
216 // Indentation + any already emitted text on the first line of the current
222 pub fn indented(indent: Indent, config: &Config) -> Shape {
224 width: config.max_width,
226 offset: indent.width(),
230 /// `indent` is the indentation of the first line. The next lines
231 /// should begin with at least `indent` spaces (except backwards
232 /// indentation). The first line should not begin with indentation.
233 /// `width` is the maximum number of characters on the last line
234 /// (excluding `indent`). The width of other lines is not limited by
236 /// Note that in reality, we sometimes use width for lines other than the
237 /// last (i.e., we are conservative).
242 // |<------------>| max width
245 pub fn legacy(width: usize, indent: Indent) -> Shape {
249 offset: indent.alignment,
253 pub fn offset(width: usize, indent: Indent, offset: usize) -> Shape {
261 pub fn visual_indent(&self, extra_width: usize) -> Shape {
262 let alignment = self.offset + extra_width;
266 block_indent: self.indent.block_indent,
267 alignment: alignment,
273 pub fn block_indent(&self, extra_width: usize) -> Shape {
274 if self.indent.alignment == 0 {
278 block_indent: self.indent.block_indent + extra_width,
287 block_indent: self.indent.block_indent,
288 alignment: self.indent.alignment + extra_width,
290 offset: self.indent.alignment + extra_width,
295 pub fn add_offset(&self, extra_width: usize) -> Shape {
299 block_indent: self.indent.block_indent,
300 alignment: self.indent.alignment,
302 offset: self.offset + extra_width,
306 pub fn block(&self) -> Shape {
310 block_indent: self.indent.block_indent,
317 pub fn sub_width(&self, width: usize) -> Option<Shape> {
319 width: try_opt!(self.width.checked_sub(width)),
325 pub fn shrink_left(&self, width: usize) -> Option<Shape> {
327 width: try_opt!(self.width.checked_sub(width)),
328 indent: self.indent + width,
329 offset: self.offset + width,
333 pub fn used_width(&self) -> usize {
334 self.indent.block_indent + self.offset
339 // Line has exceeded character limit (found, maximum)
340 LineOverflow(usize, usize),
341 // Line ends in whitespace
343 // TO-DO or FIX-ME item without an issue number
347 impl fmt::Display for ErrorKind {
348 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
350 ErrorKind::LineOverflow(found, maximum) => {
352 "line exceeded maximum length (maximum: {}, found: {})",
356 ErrorKind::TrailingWhitespace => write!(fmt, "left behind trailing whitespace"),
357 ErrorKind::BadIssue(issue) => write!(fmt, "found {}", issue),
362 // Formatting errors that are identified *after* rustfmt has run.
363 pub struct FormattingError {
368 impl FormattingError {
369 fn msg_prefix(&self) -> &str {
371 ErrorKind::LineOverflow(..) |
372 ErrorKind::TrailingWhitespace => "Rustfmt failed at",
373 ErrorKind::BadIssue(_) => "WARNING:",
377 fn msg_suffix(&self) -> &str {
379 ErrorKind::LineOverflow(..) |
380 ErrorKind::TrailingWhitespace => "(sorry)",
381 ErrorKind::BadIssue(_) => "",
386 pub struct FormatReport {
387 // Maps stringified file paths to their associated formatting errors.
388 file_error_map: HashMap<String, Vec<FormattingError>>,
392 fn new() -> FormatReport {
393 FormatReport { file_error_map: HashMap::new() }
396 pub fn warning_count(&self) -> usize {
399 .map(|(_, errors)| errors.len())
400 .fold(0, |acc, x| acc + x)
403 pub fn has_warnings(&self) -> bool {
404 self.warning_count() > 0
408 impl fmt::Display for FormatReport {
409 // Prints all the formatting errors.
410 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
411 for (file, errors) in &self.file_error_map {
412 for error in errors {
419 error.msg_suffix()));
426 // Formatting which depends on the AST.
427 fn format_ast<F>(krate: &ast::Crate,
428 parse_session: &ParseSess,
432 -> Result<(FileMap, bool), io::Error>
433 where F: FnMut(&str, &mut StringBuffer) -> Result<bool, io::Error>
435 let mut result = FileMap::new();
436 // diff mode: check if any files are differing
437 let mut has_diff = false;
439 // We always skip children for the "Plain" write mode, since there is
440 // nothing to distinguish the nested module contents.
441 let skip_children = config.skip_children || config.write_mode == config::WriteMode::Plain;
442 for (path, module) in modules::list_files(krate, parse_session.codemap()) {
443 if skip_children && path.as_path() != main_file {
446 let path = path.to_str().unwrap();
448 println!("Formatting {}", path);
450 let mut visitor = FmtVisitor::from_codemap(parse_session, config);
451 visitor.format_separate_mod(module);
453 has_diff |= try!(after_file(path, &mut visitor.buffer));
455 result.push((path.to_owned(), visitor.buffer));
458 Ok((result, has_diff))
461 // Formatting done on a char by char or line by line basis.
462 // FIXME(#209) warn on bad license
463 // FIXME(#20) other stuff for parity with make tidy
464 fn format_lines(text: &mut StringBuffer, name: &str, config: &Config, report: &mut FormatReport) {
465 // Iterate over the chars in the file map.
466 let mut trims = vec![];
467 let mut last_wspace: Option<usize> = None;
468 let mut line_len = 0;
469 let mut cur_line = 1;
470 let mut newline_count = 0;
471 let mut errors = vec![];
472 let mut issue_seeker = BadIssueSeeker::new(config.report_todo, config.report_fixme);
474 for (c, b) in text.chars() {
476 line_len += c.len_utf8();
480 // Add warnings for bad todos/ fixmes
481 if let Some(issue) = issue_seeker.inspect(c) {
482 errors.push(FormattingError {
484 kind: ErrorKind::BadIssue(issue),
489 // Check for (and record) trailing whitespace.
490 if let Some(lw) = last_wspace {
491 trims.push((cur_line, lw, b));
494 // Check for any line width errors we couldn't correct.
495 if config.error_on_line_overflow && line_len > config.max_width {
496 errors.push(FormattingError {
498 kind: ErrorKind::LineOverflow(line_len, config.max_width),
507 line_len += c.len_utf8();
508 if c.is_whitespace() {
509 if last_wspace.is_none() {
510 last_wspace = Some(b);
518 if newline_count > 1 {
519 debug!("track truncate: {} {}", text.len, newline_count);
520 let line = text.len - newline_count + 1;
524 for &(l, _, _) in &trims {
525 errors.push(FormattingError {
527 kind: ErrorKind::TrailingWhitespace,
531 report.file_error_map.insert(name.to_owned(), errors);
534 fn parse_input(input: Input,
535 parse_session: &ParseSess)
536 -> Result<ast::Crate, Option<DiagnosticBuilder>> {
537 let result = match input {
538 Input::File(file) => {
539 let mut parser = parse::new_parser_from_file(parse_session, &file);
540 parser.cfg_mods = false;
541 parser.parse_crate_mod()
543 Input::Text(text) => {
545 parse::new_parser_from_source_str(parse_session, "stdin".to_owned(), text);
546 parser.cfg_mods = false;
547 parser.parse_crate_mod()
553 if parse_session.span_diagnostic.has_errors() {
554 // Bail out if the parser recovered from an error.
560 Err(e) => Err(Some(e)),
564 pub fn format_input<T: Write>(input: Input,
566 mut out: Option<&mut T>)
567 -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
568 let mut summary = Summary::new();
569 if config.disable_all_formatting {
570 return Ok((summary, FileMap::new(), FormatReport::new()));
572 let codemap = Rc::new(CodeMap::new());
575 Handler::with_tty_emitter(ColorConfig::Auto, true, false, Some(codemap.clone()));
576 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
578 let main_file = match input {
579 Input::File(ref file) => file.clone(),
580 Input::Text(..) => PathBuf::from("stdin"),
583 let krate = match parse_input(input, &parse_session) {
586 if let Some(mut diagnostic) = diagnostic {
589 summary.add_parsing_error();
590 return Ok((summary, FileMap::new(), FormatReport::new()));
594 if parse_session.span_diagnostic.has_errors() {
595 summary.add_parsing_error();
598 // Suppress error output after parsing.
599 let silent_emitter = Box::new(EmitterWriter::new(Box::new(Vec::new()), Some(codemap.clone())));
600 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
602 let mut report = FormatReport::new();
604 match format_ast(&krate,
609 // For some reason, the codemap does not include terminating
610 // newlines so we must add one on for each file. This is sad.
611 filemap::append_newline(file);
613 format_lines(file, file_name, config, &mut report);
615 if let Some(ref mut out) = out {
616 return filemap::write_file(file, file_name, out, config);
620 Ok((file_map, has_diff)) => {
621 if report.has_warnings() {
622 summary.add_formatting_error();
629 Ok((summary, file_map, report))
631 Err(e) => Err((e, summary)),
641 pub fn run(input: Input, config: &Config) -> Summary {
642 let mut out = &mut stdout();
643 output_header(out, config.write_mode).ok();
644 match format_input(input, config, Some(out)) {
645 Ok((summary, _, report)) => {
646 output_footer(out, config.write_mode).ok();
648 if report.has_warnings() {
654 Err((msg, mut summary)) => {
655 msg!("Error writing files: {}", msg);
656 summary.add_operational_error();
667 fn indent_add_sub() {
668 let indent = Indent::new(4, 8) + Indent::new(8, 12);
669 assert_eq!(12, indent.block_indent);
670 assert_eq!(20, indent.alignment);
672 let indent = indent - Indent::new(4, 4);
673 assert_eq!(8, indent.block_indent);
674 assert_eq!(16, indent.alignment);
678 fn indent_add_sub_alignment() {
679 let indent = Indent::new(4, 8) + 4;
680 assert_eq!(4, indent.block_indent);
681 assert_eq!(12, indent.alignment);
683 let indent = indent - 4;
684 assert_eq!(4, indent.block_indent);
685 assert_eq!(8, indent.alignment);
689 fn indent_to_string_spaces() {
690 let config = Config::default();
691 let indent = Indent::new(4, 8);
694 assert_eq!(" ", indent.to_string(&config));
698 fn indent_to_string_hard_tabs() {
699 let mut config = Config::default();
700 config.hard_tabs = true;
701 let indent = Indent::new(8, 4);
704 assert_eq!("\t\t ", indent.to_string(&config));
708 fn shape_visual_indent() {
709 let config = Config::default();
710 let indent = Indent::new(4, 8);
711 let shape = Shape::indented(indent, &config);
712 let shape = shape.visual_indent(20);
714 assert_eq!(config.max_width, shape.width);
715 assert_eq!(4, shape.indent.block_indent);
716 assert_eq!(32, shape.indent.alignment);
717 assert_eq!(32, shape.offset);
721 fn shape_block_indent_without_alignment() {
722 let config = Config::default();
723 let indent = Indent::new(4, 0);
724 let shape = Shape::indented(indent, &config);
725 let shape = shape.block_indent(20);
727 assert_eq!(config.max_width, shape.width);
728 assert_eq!(24, shape.indent.block_indent);
729 assert_eq!(0, shape.indent.alignment);
730 assert_eq!(0, shape.offset);
734 fn shape_block_indent_with_alignment() {
735 let config = Config::default();
736 let indent = Indent::new(4, 8);
737 let shape = Shape::indented(indent, &config);
738 let shape = shape.block_indent(20);
740 assert_eq!(config.max_width, shape.width);
741 assert_eq!(4, shape.indent.block_indent);
742 assert_eq!(28, shape.indent.alignment);
743 assert_eq!(28, shape.offset);