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)]
18 extern crate serde_derive;
19 extern crate serde_json;
22 extern crate rustc_errors as errors;
26 extern crate unicode_segmentation;
31 use errors::{Handler, DiagnosticBuilder};
32 use errors::emitter::{ColorConfig, EmitterWriter};
34 use syntax::codemap::{CodeMap, Span, FilePathMapping};
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};
53 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 utils::mk_sp(self.pat.span.lo, self.ty.span.hi)
117 impl Spanned for ast::StructField {
118 fn span(&self) -> Span {
119 if self.attrs.is_empty() {
120 mk_sp(self.span.lo, self.ty.span.hi)
122 // Include attributes and doc comments, if present
123 mk_sp(self.attrs[0].span.lo, self.ty.span.hi)
128 impl Spanned for ast::Field {
129 fn span(&self) -> Span {
130 let lo = if self.attrs.is_empty() {
133 self.attrs[0].span.lo
135 mk_sp(lo, self.span.hi)
139 impl Spanned for ast::WherePredicate {
140 fn span(&self) -> Span {
142 ast::WherePredicate::BoundPredicate(ref p) => p.span,
143 ast::WherePredicate::RegionPredicate(ref p) => p.span,
144 ast::WherePredicate::EqPredicate(ref p) => p.span,
149 impl Spanned for ast::FunctionRetTy {
150 fn span(&self) -> Span {
152 ast::FunctionRetTy::Default(span) => span,
153 ast::FunctionRetTy::Ty(ref ty) => ty.span,
158 impl Spanned for ast::TyParam {
159 fn span(&self) -> Span {
160 // Note that ty.span is the span for ty.ident, not the whole item.
161 let lo = if self.attrs.is_empty() {
164 self.attrs[0].span.lo
166 if let Some(ref def) = self.default {
167 return mk_sp(lo, def.span.hi);
169 if self.bounds.is_empty() {
170 return mk_sp(lo, self.span.hi);
172 let hi = self.bounds[self.bounds.len() - 1].span().hi;
177 impl Spanned for ast::TyParamBound {
178 fn span(&self) -> Span {
180 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span,
181 ast::TyParamBound::RegionTyParamBound(ref l) => l.span,
186 #[derive(Copy, Clone, Debug)]
188 // Width of the block indent, in characters. Must be a multiple of
189 // Config::tab_spaces.
190 pub block_indent: usize,
191 // Alignment in characters.
192 pub alignment: usize,
196 pub fn new(block_indent: usize, alignment: usize) -> Indent {
198 block_indent: block_indent,
199 alignment: alignment,
203 pub fn empty() -> Indent {
207 pub fn block_only(&self) -> Indent {
209 block_indent: self.block_indent,
214 pub fn block_indent(mut self, config: &Config) -> Indent {
215 self.block_indent += config.tab_spaces();
219 pub fn block_unindent(mut self, config: &Config) -> Indent {
220 if self.block_indent < config.tab_spaces() {
221 Indent::new(self.block_indent, 0)
223 self.block_indent -= config.tab_spaces();
228 pub fn width(&self) -> usize {
229 self.block_indent + self.alignment
232 pub fn to_string(&self, config: &Config) -> String {
233 let (num_tabs, num_spaces) = if config.hard_tabs() {
234 (self.block_indent / config.tab_spaces(), self.alignment)
238 let num_chars = num_tabs + num_spaces;
239 let mut indent = String::with_capacity(num_chars);
240 for _ in 0..num_tabs {
243 for _ in 0..num_spaces {
250 impl Add for Indent {
251 type Output = Indent;
253 fn add(self, rhs: Indent) -> Indent {
255 block_indent: self.block_indent + rhs.block_indent,
256 alignment: self.alignment + rhs.alignment,
261 impl Sub for Indent {
262 type Output = Indent;
264 fn sub(self, rhs: Indent) -> Indent {
266 self.block_indent - rhs.block_indent,
267 self.alignment - rhs.alignment,
272 impl Add<usize> for Indent {
273 type Output = Indent;
275 fn add(self, rhs: usize) -> Indent {
276 Indent::new(self.block_indent, self.alignment + rhs)
280 impl Sub<usize> for Indent {
281 type Output = Indent;
283 fn sub(self, rhs: usize) -> Indent {
284 Indent::new(self.block_indent, self.alignment - rhs)
288 #[derive(Copy, Clone, Debug)]
291 // The current indentation of code.
293 // Indentation + any already emitted text on the first line of the current
299 /// `indent` is the indentation of the first line. The next lines
300 /// should begin with at least `indent` spaces (except backwards
301 /// indentation). The first line should not begin with indentation.
302 /// `width` is the maximum number of characters on the last line
303 /// (excluding `indent`). The width of other lines is not limited by
305 /// Note that in reality, we sometimes use width for lines other than the
306 /// last (i.e., we are conservative).
311 // |<------------>| max width
314 pub fn legacy(width: usize, indent: Indent) -> Shape {
318 offset: indent.alignment,
322 pub fn indented(indent: Indent, config: &Config) -> Shape {
324 width: config.max_width().checked_sub(indent.width()).unwrap_or(0),
326 offset: indent.alignment,
330 pub fn with_max_width(&self, config: &Config) -> Shape {
334 .checked_sub(self.indent.width())
340 pub fn offset(width: usize, indent: Indent, offset: usize) -> Shape {
348 pub fn visual_indent(&self, extra_width: usize) -> Shape {
349 let alignment = self.offset + extra_width;
352 indent: Indent::new(self.indent.block_indent, alignment),
357 pub fn block_indent(&self, extra_width: usize) -> Shape {
358 if self.indent.alignment == 0 {
361 indent: Indent::new(self.indent.block_indent + extra_width, 0),
367 indent: self.indent + extra_width,
368 offset: self.indent.alignment + extra_width,
373 pub fn block_left(&self, width: usize) -> Option<Shape> {
374 self.block_indent(width).sub_width(width)
377 pub fn add_offset(&self, extra_width: usize) -> Shape {
379 offset: self.offset + extra_width,
384 pub fn block(&self) -> Shape {
386 indent: self.indent.block_only(),
391 pub fn sub_width(&self, width: usize) -> Option<Shape> {
393 width: try_opt!(self.width.checked_sub(width)),
398 pub fn shrink_left(&self, width: usize) -> Option<Shape> {
400 width: try_opt!(self.width.checked_sub(width)),
401 indent: self.indent + width,
402 offset: self.offset + width,
406 pub fn offset_left(&self, width: usize) -> Option<Shape> {
407 self.add_offset(width).sub_width(width)
410 pub fn used_width(&self) -> usize {
411 self.indent.block_indent + self.offset
414 pub fn rhs_overhead(&self, config: &Config) -> usize {
417 .checked_sub(self.used_width() + self.width)
423 // Line has exceeded character limit (found, maximum)
424 LineOverflow(usize, usize),
425 // Line ends in whitespace
427 // TO-DO or FIX-ME item without an issue number
431 impl fmt::Display for ErrorKind {
432 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
434 ErrorKind::LineOverflow(found, maximum) => {
437 "line exceeded maximum length (maximum: {}, found: {})",
442 ErrorKind::TrailingWhitespace => write!(fmt, "left behind trailing whitespace"),
443 ErrorKind::BadIssue(issue) => write!(fmt, "found {}", issue),
448 // Formatting errors that are identified *after* rustfmt has run.
449 pub struct FormattingError {
454 impl FormattingError {
455 fn msg_prefix(&self) -> &str {
457 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => "Rustfmt failed at",
458 ErrorKind::BadIssue(_) => "WARNING:",
462 fn msg_suffix(&self) -> &str {
464 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => "(sorry)",
465 ErrorKind::BadIssue(_) => "",
470 pub struct FormatReport {
471 // Maps stringified file paths to their associated formatting errors.
472 file_error_map: HashMap<String, Vec<FormattingError>>,
476 fn new() -> FormatReport {
478 file_error_map: HashMap::new(),
482 pub fn warning_count(&self) -> usize {
485 .map(|(_, errors)| errors.len())
486 .fold(0, |acc, x| acc + x)
489 pub fn has_warnings(&self) -> bool {
490 self.warning_count() > 0
494 impl fmt::Display for FormatReport {
495 // Prints all the formatting errors.
496 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
497 for (file, errors) in &self.file_error_map {
498 for error in errors {
514 // Formatting which depends on the AST.
517 mut parse_session: &mut ParseSess,
520 codemap: &Rc<CodeMap>,
522 ) -> Result<(FileMap, bool), io::Error>
524 F: FnMut(&str, &mut StringBuffer) -> Result<bool, io::Error>,
526 let mut result = FileMap::new();
527 // diff mode: check if any files are differing
528 let mut has_diff = false;
530 // We always skip children for the "Plain" write mode, since there is
531 // nothing to distinguish the nested module contents.
532 let skip_children = config.skip_children() || config.write_mode() == config::WriteMode::Plain;
533 for (path, module) in modules::list_files(krate, parse_session.codemap()) {
534 if skip_children && path.as_path() != main_file {
537 let path = path.to_str().unwrap();
538 if config.verbose() {
539 println!("Formatting {}", path);
542 let mut visitor = FmtVisitor::from_codemap(parse_session, config);
543 visitor.format_separate_mod(module);
545 has_diff |= after_file(path, &mut visitor.buffer)?;
547 result.push((path.to_owned(), visitor.buffer));
549 // Reset the error count.
550 if parse_session.span_diagnostic.has_errors() {
551 let silent_emitter = Box::new(EmitterWriter::new(
552 Box::new(Vec::new()),
553 Some(codemap.clone()),
555 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
559 Ok((result, has_diff))
562 // Formatting done on a char by char or line by line basis.
563 // FIXME(#209) warn on bad license
564 // FIXME(#20) other stuff for parity with make tidy
565 fn format_lines(text: &mut StringBuffer, name: &str, config: &Config, report: &mut FormatReport) {
566 // Iterate over the chars in the file map.
567 let mut trims = vec![];
568 let mut last_wspace: Option<usize> = None;
569 let mut line_len = 0;
570 let mut cur_line = 1;
571 let mut newline_count = 0;
572 let mut errors = vec![];
573 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
575 for (c, b) in text.chars() {
580 let format_line = config.file_lines().contains_line(name, cur_line as usize);
583 // Add warnings for bad todos/ fixmes
584 if let Some(issue) = issue_seeker.inspect(c) {
585 errors.push(FormattingError {
587 kind: ErrorKind::BadIssue(issue),
594 // Check for (and record) trailing whitespace.
595 if let Some(lw) = last_wspace {
596 trims.push((cur_line, lw, b));
600 // Check for any line width errors we couldn't correct.
601 if config.error_on_line_overflow() && line_len > config.max_width() {
602 errors.push(FormattingError {
604 kind: ErrorKind::LineOverflow(line_len, config.max_width()),
616 if c.is_whitespace() {
617 if last_wspace.is_none() {
618 last_wspace = Some(b);
626 if newline_count > 1 {
627 debug!("track truncate: {} {}", text.len, newline_count);
628 let line = text.len - newline_count + 1;
632 for &(l, _, _) in &trims {
633 errors.push(FormattingError {
635 kind: ErrorKind::TrailingWhitespace,
639 report.file_error_map.insert(name.to_owned(), errors);
644 parse_session: &ParseSess,
645 ) -> Result<ast::Crate, Option<DiagnosticBuilder>> {
646 let result = match input {
647 Input::File(file) => {
648 let mut parser = parse::new_parser_from_file(parse_session, &file);
649 parser.cfg_mods = false;
650 parser.parse_crate_mod()
652 Input::Text(text) => {
654 parse::new_parser_from_source_str(parse_session, "stdin".to_owned(), text);
655 parser.cfg_mods = false;
656 parser.parse_crate_mod()
662 if parse_session.span_diagnostic.has_errors() {
663 // Bail out if the parser recovered from an error.
669 Err(e) => Err(Some(e)),
673 pub fn format_input<T: Write>(
676 mut out: Option<&mut T>,
677 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
678 let mut summary = Summary::new();
679 if config.disable_all_formatting() {
680 return Ok((summary, FileMap::new(), FormatReport::new()));
682 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
685 Handler::with_tty_emitter(ColorConfig::Auto, true, false, Some(codemap.clone()));
686 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
688 let main_file = match input {
689 Input::File(ref file) => file.clone(),
690 Input::Text(..) => PathBuf::from("stdin"),
693 let krate = match parse_input(input, &parse_session) {
696 if let Some(mut diagnostic) = diagnostic {
699 summary.add_parsing_error();
700 return Ok((summary, FileMap::new(), FormatReport::new()));
704 if parse_session.span_diagnostic.has_errors() {
705 summary.add_parsing_error();
708 // Suppress error output after parsing.
709 let silent_emitter = Box::new(EmitterWriter::new(
710 Box::new(Vec::new()),
711 Some(codemap.clone()),
713 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
715 let mut report = FormatReport::new();
724 // For some reason, the codemap does not include terminating
725 // newlines so we must add one on for each file. This is sad.
726 filemap::append_newline(file);
728 format_lines(file, file_name, config, &mut report);
730 if let Some(ref mut out) = out {
731 return filemap::write_file(file, file_name, out, config);
736 Ok((file_map, has_diff)) => {
737 if report.has_warnings() {
738 summary.add_formatting_error();
745 Ok((summary, file_map, report))
747 Err(e) => Err((e, summary)),
757 pub fn run(input: Input, config: &Config) -> Summary {
758 let mut out = &mut stdout();
759 output_header(out, config.write_mode()).ok();
760 match format_input(input, config, Some(out)) {
761 Ok((summary, _, report)) => {
762 output_footer(out, config.write_mode()).ok();
764 if report.has_warnings() {
770 Err((msg, mut summary)) => {
771 msg!("Error writing files: {}", msg);
772 summary.add_operational_error();
783 fn indent_add_sub() {
784 let indent = Indent::new(4, 8) + Indent::new(8, 12);
785 assert_eq!(12, indent.block_indent);
786 assert_eq!(20, indent.alignment);
788 let indent = indent - Indent::new(4, 4);
789 assert_eq!(8, indent.block_indent);
790 assert_eq!(16, indent.alignment);
794 fn indent_add_sub_alignment() {
795 let indent = Indent::new(4, 8) + 4;
796 assert_eq!(4, indent.block_indent);
797 assert_eq!(12, indent.alignment);
799 let indent = indent - 4;
800 assert_eq!(4, indent.block_indent);
801 assert_eq!(8, indent.alignment);
805 fn indent_to_string_spaces() {
806 let config = Config::default();
807 let indent = Indent::new(4, 8);
810 assert_eq!(" ", indent.to_string(&config));
814 fn indent_to_string_hard_tabs() {
815 let mut config = Config::default();
816 config.set().hard_tabs(true);
817 let indent = Indent::new(8, 4);
820 assert_eq!("\t\t ", indent.to_string(&config));
824 fn shape_visual_indent() {
825 let config = Config::default();
826 let indent = Indent::new(4, 8);
827 let shape = Shape::legacy(config.max_width(), indent);
828 let shape = shape.visual_indent(20);
830 assert_eq!(config.max_width(), shape.width);
831 assert_eq!(4, shape.indent.block_indent);
832 assert_eq!(28, shape.indent.alignment);
833 assert_eq!(28, shape.offset);
837 fn shape_block_indent_without_alignment() {
838 let config = Config::default();
839 let indent = Indent::new(4, 0);
840 let shape = Shape::legacy(config.max_width(), indent);
841 let shape = shape.block_indent(20);
843 assert_eq!(config.max_width(), shape.width);
844 assert_eq!(24, shape.indent.block_indent);
845 assert_eq!(0, shape.indent.alignment);
846 assert_eq!(0, shape.offset);
850 fn shape_block_indent_with_alignment() {
851 let config = Config::default();
852 let indent = Indent::new(4, 8);
853 let shape = Shape::legacy(config.max_width(), indent);
854 let shape = shape.block_indent(20);
856 assert_eq!(config.max_width(), shape.width);
857 assert_eq!(4, shape.indent.block_indent);
858 assert_eq!(28, shape.indent.alignment);
859 assert_eq!(28, shape.offset);