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 std::collections::HashMap;
33 use std::io::{self, stdout, Write};
34 use std::ops::{Add, Sub};
35 use std::path::{Path, PathBuf};
38 use errors::{DiagnosticBuilder, Handler};
39 use errors::emitter::{ColorConfig, EmitterWriter};
40 use strings::string_buffer::StringBuffer;
42 use syntax::codemap::{CodeMap, FilePathMapping, Span};
43 use syntax::parse::{self, ParseSess};
45 use checkstyle::{output_footer, output_header};
48 use issues::{BadIssueSeeker, Issue};
50 use visitor::FmtVisitor;
52 pub use self::summary::Summary;
81 fn span(&self) -> Span;
84 impl Spanned for ast::Expr {
85 fn span(&self) -> Span {
86 if self.attrs.is_empty() {
89 mk_sp(self.attrs[0].span.lo, self.span.hi)
94 impl Spanned for ast::Stmt {
95 fn span(&self) -> Span {
98 ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => {
99 mk_sp(expr.span().lo, self.span.hi)
106 impl Spanned for ast::Pat {
107 fn span(&self) -> Span {
112 impl Spanned for ast::Ty {
113 fn span(&self) -> Span {
118 impl Spanned for ast::Arm {
119 fn span(&self) -> Span {
120 let hi = self.body.span.hi;
121 if self.attrs.is_empty() {
122 mk_sp(self.pats[0].span.lo, hi)
124 mk_sp(self.attrs[0].span.lo, hi)
129 impl Spanned for ast::Arg {
130 fn span(&self) -> Span {
131 if items::is_named_arg(self) {
132 utils::mk_sp(self.pat.span.lo, self.ty.span.hi)
139 impl Spanned for ast::StructField {
140 fn span(&self) -> Span {
141 if self.attrs.is_empty() {
142 mk_sp(self.span.lo, self.ty.span.hi)
144 // Include attributes and doc comments, if present
145 mk_sp(self.attrs[0].span.lo, self.ty.span.hi)
150 impl Spanned for ast::Field {
151 fn span(&self) -> Span {
152 let lo = if self.attrs.is_empty() {
155 self.attrs[0].span.lo
157 mk_sp(lo, self.span.hi)
161 impl Spanned for ast::WherePredicate {
162 fn span(&self) -> Span {
164 ast::WherePredicate::BoundPredicate(ref p) => p.span,
165 ast::WherePredicate::RegionPredicate(ref p) => p.span,
166 ast::WherePredicate::EqPredicate(ref p) => p.span,
171 impl Spanned for ast::FunctionRetTy {
172 fn span(&self) -> Span {
174 ast::FunctionRetTy::Default(span) => span,
175 ast::FunctionRetTy::Ty(ref ty) => ty.span,
180 impl Spanned for ast::TyParam {
181 fn span(&self) -> Span {
182 // Note that ty.span is the span for ty.ident, not the whole item.
183 let lo = if self.attrs.is_empty() {
186 self.attrs[0].span.lo
188 if let Some(ref def) = self.default {
189 return mk_sp(lo, def.span.hi);
191 if self.bounds.is_empty() {
192 return mk_sp(lo, self.span.hi);
194 let hi = self.bounds[self.bounds.len() - 1].span().hi;
199 impl Spanned for ast::TyParamBound {
200 fn span(&self) -> Span {
202 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span,
203 ast::TyParamBound::RegionTyParamBound(ref l) => l.span,
208 #[derive(Copy, Clone, Debug)]
210 // Width of the block indent, in characters. Must be a multiple of
211 // Config::tab_spaces.
212 pub block_indent: usize,
213 // Alignment in characters.
214 pub alignment: usize,
218 pub fn new(block_indent: usize, alignment: usize) -> Indent {
220 block_indent: block_indent,
221 alignment: alignment,
225 pub fn empty() -> Indent {
229 pub fn block_only(&self) -> Indent {
231 block_indent: self.block_indent,
236 pub fn block_indent(mut self, config: &Config) -> Indent {
237 self.block_indent += config.tab_spaces();
241 pub fn block_unindent(mut self, config: &Config) -> Indent {
242 if self.block_indent < config.tab_spaces() {
243 Indent::new(self.block_indent, 0)
245 self.block_indent -= config.tab_spaces();
250 pub fn width(&self) -> usize {
251 self.block_indent + self.alignment
254 pub fn to_string(&self, config: &Config) -> String {
255 let (num_tabs, num_spaces) = if config.hard_tabs() {
256 (self.block_indent / config.tab_spaces(), self.alignment)
260 let num_chars = num_tabs + num_spaces;
261 let mut indent = String::with_capacity(num_chars);
262 for _ in 0..num_tabs {
265 for _ in 0..num_spaces {
272 impl Add for Indent {
273 type Output = Indent;
275 fn add(self, rhs: Indent) -> Indent {
277 block_indent: self.block_indent + rhs.block_indent,
278 alignment: self.alignment + rhs.alignment,
283 impl Sub for Indent {
284 type Output = Indent;
286 fn sub(self, rhs: Indent) -> Indent {
288 self.block_indent - rhs.block_indent,
289 self.alignment - rhs.alignment,
294 impl Add<usize> for Indent {
295 type Output = Indent;
297 fn add(self, rhs: usize) -> Indent {
298 Indent::new(self.block_indent, self.alignment + rhs)
302 impl Sub<usize> for Indent {
303 type Output = Indent;
305 fn sub(self, rhs: usize) -> Indent {
306 Indent::new(self.block_indent, self.alignment - rhs)
310 #[derive(Copy, Clone, Debug)]
313 // The current indentation of code.
315 // Indentation + any already emitted text on the first line of the current
321 /// `indent` is the indentation of the first line. The next lines
322 /// should begin with at least `indent` spaces (except backwards
323 /// indentation). The first line should not begin with indentation.
324 /// `width` is the maximum number of characters on the last line
325 /// (excluding `indent`). The width of other lines is not limited by
327 /// Note that in reality, we sometimes use width for lines other than the
328 /// last (i.e., we are conservative).
333 // |<------------>| max width
336 pub fn legacy(width: usize, indent: Indent) -> Shape {
340 offset: indent.alignment,
344 pub fn indented(indent: Indent, config: &Config) -> Shape {
346 width: config.max_width().checked_sub(indent.width()).unwrap_or(0),
348 offset: indent.alignment,
352 pub fn with_max_width(&self, config: &Config) -> Shape {
356 .checked_sub(self.indent.width())
362 pub fn offset(width: usize, indent: Indent, offset: usize) -> Shape {
370 pub fn visual_indent(&self, extra_width: usize) -> Shape {
371 let alignment = self.offset + extra_width;
374 indent: Indent::new(self.indent.block_indent, alignment),
379 pub fn block_indent(&self, extra_width: usize) -> Shape {
380 if self.indent.alignment == 0 {
383 indent: Indent::new(self.indent.block_indent + extra_width, 0),
389 indent: self.indent + extra_width,
390 offset: self.indent.alignment + extra_width,
395 pub fn block_left(&self, width: usize) -> Option<Shape> {
396 self.block_indent(width).sub_width(width)
399 pub fn add_offset(&self, extra_width: usize) -> Shape {
401 offset: self.offset + extra_width,
406 pub fn block(&self) -> Shape {
408 indent: self.indent.block_only(),
413 pub fn sub_width(&self, width: usize) -> Option<Shape> {
415 width: try_opt!(self.width.checked_sub(width)),
420 pub fn shrink_left(&self, width: usize) -> Option<Shape> {
422 width: try_opt!(self.width.checked_sub(width)),
423 indent: self.indent + width,
424 offset: self.offset + width,
428 pub fn offset_left(&self, width: usize) -> Option<Shape> {
429 self.add_offset(width).sub_width(width)
432 pub fn used_width(&self) -> usize {
433 self.indent.block_indent + self.offset
436 pub fn rhs_overhead(&self, config: &Config) -> usize {
439 .checked_sub(self.used_width() + self.width)
445 // Line has exceeded character limit (found, maximum)
446 LineOverflow(usize, usize),
447 // Line ends in whitespace
449 // TO-DO or FIX-ME item without an issue number
453 impl fmt::Display for ErrorKind {
454 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
456 ErrorKind::LineOverflow(found, maximum) => write!(
458 "line exceeded maximum length (maximum: {}, found: {})",
462 ErrorKind::TrailingWhitespace => write!(fmt, "left behind trailing whitespace"),
463 ErrorKind::BadIssue(issue) => write!(fmt, "found {}", issue),
468 // Formatting errors that are identified *after* rustfmt has run.
469 pub struct FormattingError {
474 impl FormattingError {
475 fn msg_prefix(&self) -> &str {
477 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => "Rustfmt failed at",
478 ErrorKind::BadIssue(_) => "WARNING:",
482 fn msg_suffix(&self) -> &str {
484 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => "(sorry)",
485 ErrorKind::BadIssue(_) => "",
490 pub struct FormatReport {
491 // Maps stringified file paths to their associated formatting errors.
492 file_error_map: HashMap<String, Vec<FormattingError>>,
496 fn new() -> FormatReport {
498 file_error_map: HashMap::new(),
502 pub fn warning_count(&self) -> usize {
505 .map(|(_, errors)| errors.len())
506 .fold(0, |acc, x| acc + x)
509 pub fn has_warnings(&self) -> bool {
510 self.warning_count() > 0
514 impl fmt::Display for FormatReport {
515 // Prints all the formatting errors.
516 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
517 for (file, errors) in &self.file_error_map {
518 for error in errors {
534 // Formatting which depends on the AST.
537 mut parse_session: &mut ParseSess,
540 codemap: &Rc<CodeMap>,
542 ) -> Result<(FileMap, bool), io::Error>
544 F: FnMut(&str, &mut StringBuffer) -> Result<bool, io::Error>,
546 let mut result = FileMap::new();
547 // diff mode: check if any files are differing
548 let mut has_diff = false;
550 // We always skip children for the "Plain" write mode, since there is
551 // nothing to distinguish the nested module contents.
552 let skip_children = config.skip_children() || config.write_mode() == config::WriteMode::Plain;
553 for (path, module) in modules::list_files(krate, parse_session.codemap()) {
554 if skip_children && path.as_path() != main_file {
557 let path_str = path.to_str().unwrap();
558 if config.verbose() {
559 println!("Formatting {}", path_str);
562 let mut visitor = FmtVisitor::from_codemap(parse_session, config);
563 let filemap = visitor.codemap.lookup_char_pos(module.inner.lo).file;
564 // Format inner attributes if available.
565 if !krate.attrs.is_empty() && path == main_file {
566 visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner);
568 visitor.last_pos = filemap.start_pos;
570 visitor.format_separate_mod(module, &*filemap);
572 has_diff |= after_file(path_str, &mut visitor.buffer)?;
574 result.push((path_str.to_owned(), visitor.buffer));
576 // Reset the error count.
577 if parse_session.span_diagnostic.has_errors() {
578 let silent_emitter = Box::new(EmitterWriter::new(
579 Box::new(Vec::new()),
580 Some(codemap.clone()),
582 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
586 Ok((result, has_diff))
589 // Formatting done on a char by char or line by line basis.
590 // FIXME(#209) warn on bad license
591 // FIXME(#20) other stuff for parity with make tidy
592 fn format_lines(text: &mut StringBuffer, name: &str, config: &Config, report: &mut FormatReport) {
593 // Iterate over the chars in the file map.
594 let mut trims = vec![];
595 let mut last_wspace: Option<usize> = None;
596 let mut line_len = 0;
597 let mut cur_line = 1;
598 let mut newline_count = 0;
599 let mut errors = vec![];
600 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
602 for (c, b) in text.chars() {
607 let format_line = config.file_lines().contains_line(name, cur_line as usize);
610 // Add warnings for bad todos/ fixmes
611 if let Some(issue) = issue_seeker.inspect(c) {
612 errors.push(FormattingError {
614 kind: ErrorKind::BadIssue(issue),
621 // Check for (and record) trailing whitespace.
622 if let Some(lw) = last_wspace {
623 trims.push((cur_line, lw, b));
627 // Check for any line width errors we couldn't correct.
628 if config.error_on_line_overflow() && line_len > config.max_width() {
629 errors.push(FormattingError {
631 kind: ErrorKind::LineOverflow(line_len, config.max_width()),
643 if c.is_whitespace() {
644 if last_wspace.is_none() {
645 last_wspace = Some(b);
653 if newline_count > 1 {
654 debug!("track truncate: {} {}", text.len, newline_count);
655 let line = text.len - newline_count + 1;
659 for &(l, _, _) in &trims {
660 errors.push(FormattingError {
662 kind: ErrorKind::TrailingWhitespace,
666 report.file_error_map.insert(name.to_owned(), errors);
671 parse_session: &ParseSess,
672 ) -> Result<ast::Crate, Option<DiagnosticBuilder>> {
673 let result = match input {
674 Input::File(file) => {
675 let mut parser = parse::new_parser_from_file(parse_session, &file);
676 parser.cfg_mods = false;
677 parser.parse_crate_mod()
679 Input::Text(text) => {
681 parse::new_parser_from_source_str(parse_session, "stdin".to_owned(), text);
682 parser.cfg_mods = false;
683 parser.parse_crate_mod()
689 if parse_session.span_diagnostic.has_errors() {
690 // Bail out if the parser recovered from an error.
696 Err(e) => Err(Some(e)),
700 pub fn format_input<T: Write>(
703 mut out: Option<&mut T>,
704 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
705 let mut summary = Summary::new();
706 if config.disable_all_formatting() {
707 return Ok((summary, FileMap::new(), FormatReport::new()));
709 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
712 Handler::with_tty_emitter(ColorConfig::Auto, true, false, Some(codemap.clone()));
713 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
715 let main_file = match input {
716 Input::File(ref file) => file.clone(),
717 Input::Text(..) => PathBuf::from("stdin"),
720 let krate = match parse_input(input, &parse_session) {
723 if let Some(mut diagnostic) = diagnostic {
726 summary.add_parsing_error();
727 return Ok((summary, FileMap::new(), FormatReport::new()));
731 if parse_session.span_diagnostic.has_errors() {
732 summary.add_parsing_error();
735 // Suppress error output after parsing.
736 let silent_emitter = Box::new(EmitterWriter::new(
737 Box::new(Vec::new()),
738 Some(codemap.clone()),
740 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
742 let mut report = FormatReport::new();
751 // For some reason, the codemap does not include terminating
752 // newlines so we must add one on for each file. This is sad.
753 filemap::append_newline(file);
755 format_lines(file, file_name, config, &mut report);
757 if let Some(ref mut out) = out {
758 return filemap::write_file(file, file_name, out, config);
763 Ok((file_map, has_diff)) => {
764 if report.has_warnings() {
765 summary.add_formatting_error();
772 Ok((summary, file_map, report))
774 Err(e) => Err((e, summary)),
784 pub fn run(input: Input, config: &Config) -> Summary {
785 let mut out = &mut stdout();
786 output_header(out, config.write_mode()).ok();
787 match format_input(input, config, Some(out)) {
788 Ok((summary, _, report)) => {
789 output_footer(out, config.write_mode()).ok();
791 if report.has_warnings() {
797 Err((msg, mut summary)) => {
798 msg!("Error writing files: {}", msg);
799 summary.add_operational_error();
810 fn indent_add_sub() {
811 let indent = Indent::new(4, 8) + Indent::new(8, 12);
812 assert_eq!(12, indent.block_indent);
813 assert_eq!(20, indent.alignment);
815 let indent = indent - Indent::new(4, 4);
816 assert_eq!(8, indent.block_indent);
817 assert_eq!(16, indent.alignment);
821 fn indent_add_sub_alignment() {
822 let indent = Indent::new(4, 8) + 4;
823 assert_eq!(4, indent.block_indent);
824 assert_eq!(12, indent.alignment);
826 let indent = indent - 4;
827 assert_eq!(4, indent.block_indent);
828 assert_eq!(8, indent.alignment);
832 fn indent_to_string_spaces() {
833 let config = Config::default();
834 let indent = Indent::new(4, 8);
837 assert_eq!(" ", indent.to_string(&config));
841 fn indent_to_string_hard_tabs() {
842 let mut config = Config::default();
843 config.set().hard_tabs(true);
844 let indent = Indent::new(8, 4);
847 assert_eq!("\t\t ", indent.to_string(&config));
851 fn shape_visual_indent() {
852 let config = Config::default();
853 let indent = Indent::new(4, 8);
854 let shape = Shape::legacy(config.max_width(), indent);
855 let shape = shape.visual_indent(20);
857 assert_eq!(config.max_width(), shape.width);
858 assert_eq!(4, shape.indent.block_indent);
859 assert_eq!(28, shape.indent.alignment);
860 assert_eq!(28, shape.offset);
864 fn shape_block_indent_without_alignment() {
865 let config = Config::default();
866 let indent = Indent::new(4, 0);
867 let shape = Shape::legacy(config.max_width(), indent);
868 let shape = shape.block_indent(20);
870 assert_eq!(config.max_width(), shape.width);
871 assert_eq!(24, shape.indent.block_indent);
872 assert_eq!(0, shape.indent.alignment);
873 assert_eq!(0, shape.offset);
877 fn shape_block_indent_with_alignment() {
878 let config = Config::default();
879 let indent = Indent::new(4, 8);
880 let shape = Shape::legacy(config.max_width(), indent);
881 let shape = shape.block_indent(20);
883 assert_eq!(config.max_width(), shape.width);
884 assert_eq!(4, shape.indent.block_indent);
885 assert_eq!(28, shape.indent.alignment);
886 assert_eq!(28, shape.offset);