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
20 extern crate serde_derive;
21 extern crate serde_json;
23 extern crate syntex_syntax as syntax;
24 extern crate syntex_errors as errors;
28 extern crate unicode_segmentation;
33 use errors::{Handler, DiagnosticBuilder};
34 use errors::emitter::{ColorConfig, EmitterWriter};
36 use syntax::codemap::{mk_sp, CodeMap, Span};
37 use syntax::parse::{self, ParseSess};
39 use strings::string_buffer::StringBuffer;
41 use std::io::{self, stdout, Write};
42 use std::ops::{Add, Sub};
43 use std::path::{Path, PathBuf};
45 use std::collections::HashMap;
48 use issues::{BadIssueSeeker, Issue};
50 use visitor::FmtVisitor;
52 use checkstyle::{output_header, output_footer};
54 pub use self::summary::Summary;
81 const MIN_STRING: usize = 10;
82 // When we get scoped annotations, we should have rustfmt::skip.
83 const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
86 fn span(&self) -> Span;
89 impl Spanned for ast::Expr {
90 fn span(&self) -> Span {
95 impl Spanned for ast::Pat {
96 fn span(&self) -> Span {
101 impl Spanned for ast::Ty {
102 fn span(&self) -> Span {
107 impl Spanned for ast::Arg {
108 fn span(&self) -> Span {
109 if items::is_named_arg(self) {
110 mk_sp(self.pat.span.lo, self.ty.span.hi)
117 #[derive(Copy, Clone, Debug)]
119 // Width of the block indent, in characters. Must be a multiple of
120 // Config::tab_spaces.
121 pub block_indent: usize,
122 // Alignment in characters.
123 pub alignment: usize,
127 pub fn new(block_indent: usize, alignment: usize) -> Indent {
129 block_indent: block_indent,
130 alignment: alignment,
134 pub fn empty() -> Indent {
138 pub fn block_only(&self) -> Indent {
140 block_indent: self.block_indent,
145 pub fn block_indent(mut self, config: &Config) -> Indent {
146 self.block_indent += config.tab_spaces();
150 pub fn block_unindent(mut self, config: &Config) -> Indent {
151 self.block_indent -= config.tab_spaces();
155 pub fn width(&self) -> usize {
156 self.block_indent + self.alignment
159 pub fn to_string(&self, config: &Config) -> String {
160 let (num_tabs, num_spaces) = if config.hard_tabs() {
161 (self.block_indent / config.tab_spaces(), self.alignment)
165 let num_chars = num_tabs + num_spaces;
166 let mut indent = String::with_capacity(num_chars);
167 for _ in 0..num_tabs {
170 for _ in 0..num_spaces {
177 impl Add for Indent {
178 type Output = Indent;
180 fn add(self, rhs: Indent) -> Indent {
182 block_indent: self.block_indent + rhs.block_indent,
183 alignment: self.alignment + rhs.alignment,
188 impl Sub for Indent {
189 type Output = Indent;
191 fn sub(self, rhs: Indent) -> Indent {
192 Indent::new(self.block_indent - rhs.block_indent,
193 self.alignment - rhs.alignment)
197 impl Add<usize> for Indent {
198 type Output = Indent;
200 fn add(self, rhs: usize) -> Indent {
201 Indent::new(self.block_indent, self.alignment + rhs)
205 impl Sub<usize> for Indent {
206 type Output = Indent;
208 fn sub(self, rhs: usize) -> Indent {
209 Indent::new(self.block_indent, self.alignment - rhs)
213 #[derive(Copy, Clone, Debug)]
216 // The current indentation of code.
218 // Indentation + any already emitted text on the first line of the current
224 /// `indent` is the indentation of the first line. The next lines
225 /// should begin with at least `indent` spaces (except backwards
226 /// indentation). The first line should not begin with indentation.
227 /// `width` is the maximum number of characters on the last line
228 /// (excluding `indent`). The width of other lines is not limited by
230 /// Note that in reality, we sometimes use width for lines other than the
231 /// last (i.e., we are conservative).
236 // |<------------>| max width
239 pub fn legacy(width: usize, indent: Indent) -> Shape {
243 offset: indent.alignment,
247 pub fn indented(indent: Indent, config: &Config) -> Shape {
249 width: config.max_width().checked_sub(indent.width()).unwrap_or(0),
251 offset: indent.alignment,
255 pub fn with_max_width(&self, config: &Config) -> Shape {
259 .checked_sub(self.indent.width())
265 pub fn offset(width: usize, indent: Indent, offset: usize) -> Shape {
273 pub fn visual_indent(&self, extra_width: usize) -> Shape {
274 let alignment = self.offset + extra_width;
277 indent: Indent::new(self.indent.block_indent, alignment),
282 pub fn block_indent(&self, extra_width: usize) -> Shape {
283 if self.indent.alignment == 0 {
286 indent: Indent::new(self.indent.block_indent + extra_width, 0),
292 indent: self.indent + extra_width,
293 offset: self.indent.alignment + extra_width,
298 pub fn block_left(&self, width: usize) -> Option<Shape> {
299 self.block_indent(width).sub_width(width)
302 pub fn add_offset(&self, extra_width: usize) -> Shape {
304 offset: self.offset + extra_width,
309 pub fn block(&self) -> Shape {
311 indent: self.indent.block_only(),
316 pub fn sub_width(&self, width: usize) -> Option<Shape> {
318 width: try_opt!(self.width.checked_sub(width)),
323 pub fn shrink_left(&self, width: usize) -> Option<Shape> {
325 width: try_opt!(self.width.checked_sub(width)),
326 indent: self.indent + width,
327 offset: self.offset + width,
331 pub fn offset_left(&self, width: usize) -> Option<Shape> {
332 self.add_offset(width).sub_width(width)
335 pub fn used_width(&self) -> usize {
336 self.indent.block_indent + self.offset
341 // Line has exceeded character limit (found, maximum)
342 LineOverflow(usize, usize),
343 // Line ends in whitespace
345 // TO-DO or FIX-ME item without an issue number
349 impl fmt::Display for ErrorKind {
350 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
352 ErrorKind::LineOverflow(found, maximum) => {
354 "line exceeded maximum length (maximum: {}, found: {})",
358 ErrorKind::TrailingWhitespace => write!(fmt, "left behind trailing whitespace"),
359 ErrorKind::BadIssue(issue) => write!(fmt, "found {}", issue),
364 // Formatting errors that are identified *after* rustfmt has run.
365 pub struct FormattingError {
370 impl FormattingError {
371 fn msg_prefix(&self) -> &str {
373 ErrorKind::LineOverflow(..) |
374 ErrorKind::TrailingWhitespace => "Rustfmt failed at",
375 ErrorKind::BadIssue(_) => "WARNING:",
379 fn msg_suffix(&self) -> &str {
381 ErrorKind::LineOverflow(..) |
382 ErrorKind::TrailingWhitespace => "(sorry)",
383 ErrorKind::BadIssue(_) => "",
388 pub struct FormatReport {
389 // Maps stringified file paths to their associated formatting errors.
390 file_error_map: HashMap<String, Vec<FormattingError>>,
394 fn new() -> FormatReport {
395 FormatReport { file_error_map: HashMap::new() }
398 pub fn warning_count(&self) -> usize {
401 .map(|(_, errors)| errors.len())
402 .fold(0, |acc, x| acc + x)
405 pub fn has_warnings(&self) -> bool {
406 self.warning_count() > 0
410 impl fmt::Display for FormatReport {
411 // Prints all the formatting errors.
412 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
413 for (file, errors) in &self.file_error_map {
414 for error in errors {
421 error.msg_suffix())?;
428 // Formatting which depends on the AST.
429 fn format_ast<F>(krate: &ast::Crate,
430 parse_session: &ParseSess,
434 -> Result<(FileMap, bool), io::Error>
435 where F: FnMut(&str, &mut StringBuffer) -> Result<bool, io::Error>
437 let mut result = FileMap::new();
438 // diff mode: check if any files are differing
439 let mut has_diff = false;
441 // We always skip children for the "Plain" write mode, since there is
442 // nothing to distinguish the nested module contents.
443 let skip_children = config.skip_children() || config.write_mode() == config::WriteMode::Plain;
444 for (path, module) in modules::list_files(krate, parse_session.codemap()) {
445 if skip_children && path.as_path() != main_file {
448 let path = path.to_str().unwrap();
449 if config.verbose() {
450 println!("Formatting {}", path);
452 let mut visitor = FmtVisitor::from_codemap(parse_session, config);
453 visitor.format_separate_mod(module);
455 has_diff |= after_file(path, &mut visitor.buffer)?;
457 result.push((path.to_owned(), visitor.buffer));
460 Ok((result, has_diff))
463 // Formatting done on a char by char or line by line basis.
464 // FIXME(#209) warn on bad license
465 // FIXME(#20) other stuff for parity with make tidy
466 fn format_lines(text: &mut StringBuffer, name: &str, config: &Config, report: &mut FormatReport) {
467 // Iterate over the chars in the file map.
468 let mut trims = vec![];
469 let mut last_wspace: Option<usize> = None;
470 let mut line_len = 0;
471 let mut cur_line = 1;
472 let mut newline_count = 0;
473 let mut errors = vec![];
474 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
476 for (c, b) in text.chars() {
481 let format_line = config.file_lines().contains_line(name, cur_line as usize);
484 // Add warnings for bad todos/ fixmes
485 if let Some(issue) = issue_seeker.inspect(c) {
486 errors.push(FormattingError {
488 kind: ErrorKind::BadIssue(issue),
495 // Check for (and record) trailing whitespace.
496 if let Some(lw) = last_wspace {
497 trims.push((cur_line, lw, b));
501 // Check for any line width errors we couldn't correct.
502 if config.error_on_line_overflow() && line_len > config.max_width() {
503 errors.push(FormattingError {
505 kind: ErrorKind::LineOverflow(line_len, config.max_width()),
517 if c.is_whitespace() {
518 if last_wspace.is_none() {
519 last_wspace = Some(b);
527 if newline_count > 1 {
528 debug!("track truncate: {} {}", text.len, newline_count);
529 let line = text.len - newline_count + 1;
533 for &(l, _, _) in &trims {
534 errors.push(FormattingError {
536 kind: ErrorKind::TrailingWhitespace,
540 report.file_error_map.insert(name.to_owned(), errors);
543 fn parse_input(input: Input,
544 parse_session: &ParseSess)
545 -> Result<ast::Crate, Option<DiagnosticBuilder>> {
546 let result = match input {
547 Input::File(file) => {
548 let mut parser = parse::new_parser_from_file(parse_session, &file);
549 parser.cfg_mods = false;
550 parser.parse_crate_mod()
552 Input::Text(text) => {
554 parse::new_parser_from_source_str(parse_session, "stdin".to_owned(), text);
555 parser.cfg_mods = false;
556 parser.parse_crate_mod()
562 if parse_session.span_diagnostic.has_errors() {
563 // Bail out if the parser recovered from an error.
569 Err(e) => Err(Some(e)),
573 pub fn format_input<T: Write>(input: Input,
575 mut out: Option<&mut T>)
576 -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
577 let mut summary = Summary::new();
578 if config.disable_all_formatting() {
579 return Ok((summary, FileMap::new(), FormatReport::new()));
581 let codemap = Rc::new(CodeMap::new());
584 Handler::with_tty_emitter(ColorConfig::Auto, true, false, Some(codemap.clone()));
585 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
587 let main_file = match input {
588 Input::File(ref file) => file.clone(),
589 Input::Text(..) => PathBuf::from("stdin"),
592 let krate = match parse_input(input, &parse_session) {
595 if let Some(mut diagnostic) = diagnostic {
598 summary.add_parsing_error();
599 return Ok((summary, FileMap::new(), FormatReport::new()));
603 if parse_session.span_diagnostic.has_errors() {
604 summary.add_parsing_error();
607 // Suppress error output after parsing.
608 let silent_emitter = Box::new(EmitterWriter::new(Box::new(Vec::new()), Some(codemap.clone())));
609 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
611 let mut report = FormatReport::new();
613 match format_ast(&krate,
618 // For some reason, the codemap does not include terminating
619 // newlines so we must add one on for each file. This is sad.
620 filemap::append_newline(file);
622 format_lines(file, file_name, config, &mut report);
624 if let Some(ref mut out) = out {
625 return filemap::write_file(file, file_name, out, config);
629 Ok((file_map, has_diff)) => {
630 if report.has_warnings() {
631 summary.add_formatting_error();
638 Ok((summary, file_map, report))
640 Err(e) => Err((e, summary)),
650 pub fn run(input: Input, config: &Config) -> Summary {
651 let mut out = &mut stdout();
652 output_header(out, config.write_mode()).ok();
653 match format_input(input, config, Some(out)) {
654 Ok((summary, _, report)) => {
655 output_footer(out, config.write_mode()).ok();
657 if report.has_warnings() {
663 Err((msg, mut summary)) => {
664 msg!("Error writing files: {}", msg);
665 summary.add_operational_error();
676 fn indent_add_sub() {
677 let indent = Indent::new(4, 8) + Indent::new(8, 12);
678 assert_eq!(12, indent.block_indent);
679 assert_eq!(20, indent.alignment);
681 let indent = indent - Indent::new(4, 4);
682 assert_eq!(8, indent.block_indent);
683 assert_eq!(16, indent.alignment);
687 fn indent_add_sub_alignment() {
688 let indent = Indent::new(4, 8) + 4;
689 assert_eq!(4, indent.block_indent);
690 assert_eq!(12, indent.alignment);
692 let indent = indent - 4;
693 assert_eq!(4, indent.block_indent);
694 assert_eq!(8, indent.alignment);
698 fn indent_to_string_spaces() {
699 let config = Config::default();
700 let indent = Indent::new(4, 8);
703 assert_eq!(" ", indent.to_string(&config));
707 fn indent_to_string_hard_tabs() {
708 let mut config = Config::default();
709 config.set().hard_tabs(true);
710 let indent = Indent::new(8, 4);
713 assert_eq!("\t\t ", indent.to_string(&config));
717 fn shape_visual_indent() {
718 let config = Config::default();
719 let indent = Indent::new(4, 8);
720 let shape = Shape::legacy(config.max_width(), indent);
721 let shape = shape.visual_indent(20);
723 assert_eq!(config.max_width(), shape.width);
724 assert_eq!(4, shape.indent.block_indent);
725 assert_eq!(28, shape.indent.alignment);
726 assert_eq!(28, shape.offset);
730 fn shape_block_indent_without_alignment() {
731 let config = Config::default();
732 let indent = Indent::new(4, 0);
733 let shape = Shape::legacy(config.max_width(), indent);
734 let shape = shape.block_indent(20);
736 assert_eq!(config.max_width(), shape.width);
737 assert_eq!(24, shape.indent.block_indent);
738 assert_eq!(0, shape.indent.alignment);
739 assert_eq!(0, shape.offset);
743 fn shape_block_indent_with_alignment() {
744 let config = Config::default();
745 let indent = Indent::new(4, 8);
746 let shape = Shape::legacy(config.max_width(), indent);
747 let shape = shape.block_indent(20);
749 assert_eq!(config.max_width(), shape.width);
750 assert_eq!(4, shape.indent.block_indent);
751 assert_eq!(28, shape.indent.alignment);
752 assert_eq!(28, shape.offset);