]> git.lizzy.rs Git - rust.git/blob - src/lib.rs
Merge pull request #2499 from davidalber/add-rust-code-of-conduct
[rust.git] / src / lib.rs
1 // Copyright 2015-2018 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.
4 //
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.
10
11 #![feature(custom_attribute)]
12 #![feature(decl_macro)]
13 #![feature(match_default_bindings)]
14 #![feature(type_ascription)]
15
16 #[macro_use]
17 extern crate derive_new;
18 extern crate diff;
19 #[macro_use]
20 extern crate log;
21 extern crate regex;
22 extern crate rustc_errors as errors;
23 extern crate serde;
24 #[macro_use]
25 extern crate serde_derive;
26 extern crate serde_json;
27 extern crate syntax;
28 extern crate term;
29 extern crate toml;
30 extern crate unicode_segmentation;
31
32 use std::collections::HashMap;
33 use std::fmt;
34 use std::io::{self, stdout, BufRead, Write};
35 use std::iter::repeat;
36 use std::path::PathBuf;
37 use std::rc::Rc;
38 use std::time::Duration;
39
40 use errors::{DiagnosticBuilder, Handler};
41 use errors::emitter::{ColorConfig, EmitterWriter};
42 use syntax::ast;
43 use syntax::codemap::{CodeMap, FilePathMapping};
44 pub use syntax::codemap::FileName;
45 use syntax::parse::{self, ParseSess};
46
47 use checkstyle::{output_footer, output_header};
48 use comment::{CharClasses, FullCodeCharKind};
49 use issues::{BadIssueSeeker, Issue};
50 use shape::Indent;
51 use utils::use_colored_tty;
52 use visitor::{FmtVisitor, SnippetProvider};
53
54 pub use config::Config;
55 pub use config::summary::Summary;
56
57 #[macro_use]
58 mod utils;
59
60 mod attr;
61 mod chains;
62 mod checkstyle;
63 mod closures;
64 pub mod codemap;
65 mod comment;
66 pub mod config;
67 mod expr;
68 pub mod filemap;
69 mod imports;
70 mod issues;
71 mod items;
72 mod lists;
73 mod macros;
74 mod missed_spans;
75 pub mod modules;
76 mod patterns;
77 mod reorder;
78 mod rewrite;
79 pub mod rustfmt_diff;
80 mod shape;
81 mod spanned;
82 mod string;
83 mod types;
84 mod vertical;
85 pub mod visitor;
86
87 const STDIN: &str = "<stdin>";
88
89 // A map of the files of a crate, with their new content
90 pub type FileMap = Vec<FileRecord>;
91
92 pub type FileRecord = (FileName, String);
93
94 #[derive(Clone, Copy)]
95 pub enum ErrorKind {
96     // Line has exceeded character limit (found, maximum)
97     LineOverflow(usize, usize),
98     // Line ends in whitespace
99     TrailingWhitespace,
100     // TO-DO or FIX-ME item without an issue number
101     BadIssue(Issue),
102 }
103
104 impl fmt::Display for ErrorKind {
105     fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
106         match *self {
107             ErrorKind::LineOverflow(found, maximum) => write!(
108                 fmt,
109                 "line exceeded maximum width (maximum: {}, found: {})",
110                 maximum, found
111             ),
112             ErrorKind::TrailingWhitespace => write!(fmt, "left behind trailing whitespace"),
113             ErrorKind::BadIssue(issue) => write!(fmt, "found {}", issue),
114         }
115     }
116 }
117
118 // Formatting errors that are identified *after* rustfmt has run.
119 pub struct FormattingError {
120     line: usize,
121     kind: ErrorKind,
122     is_comment: bool,
123     is_string: bool,
124     line_buffer: String,
125 }
126
127 impl FormattingError {
128     fn msg_prefix(&self) -> &str {
129         match self.kind {
130             ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => "error:",
131             ErrorKind::BadIssue(_) => "WARNING:",
132         }
133     }
134
135     fn msg_suffix(&self) -> &str {
136         if self.is_comment || self.is_string {
137             "set `error_on_unformatted = false` to suppress \
138              the warning against comments or string literals\n"
139         } else {
140             ""
141         }
142     }
143
144     // (space, target)
145     pub fn format_len(&self) -> (usize, usize) {
146         match self.kind {
147             ErrorKind::LineOverflow(found, max) => (max, found - max),
148             ErrorKind::TrailingWhitespace => {
149                 let trailing_ws_len = self.line_buffer
150                     .chars()
151                     .rev()
152                     .take_while(|c| c.is_whitespace())
153                     .count();
154                 (self.line_buffer.len() - trailing_ws_len, trailing_ws_len)
155             }
156             _ => unreachable!(),
157         }
158     }
159 }
160
161 pub struct FormatReport {
162     // Maps stringified file paths to their associated formatting errors.
163     file_error_map: HashMap<FileName, Vec<FormattingError>>,
164 }
165
166 impl FormatReport {
167     fn new() -> FormatReport {
168         FormatReport {
169             file_error_map: HashMap::new(),
170         }
171     }
172
173     pub fn warning_count(&self) -> usize {
174         self.file_error_map
175             .iter()
176             .map(|(_, errors)| errors.len())
177             .sum()
178     }
179
180     pub fn has_warnings(&self) -> bool {
181         self.warning_count() > 0
182     }
183
184     pub fn print_warnings_fancy(
185         &self,
186         mut t: Box<term::Terminal<Output = io::Stderr>>,
187     ) -> Result<(), term::Error> {
188         for (file, errors) in &self.file_error_map {
189             for error in errors {
190                 let prefix_space_len = error.line.to_string().len();
191                 let prefix_spaces: String = repeat(" ").take(1 + prefix_space_len).collect();
192
193                 // First line: the overview of error
194                 t.fg(term::color::RED)?;
195                 t.attr(term::Attr::Bold)?;
196                 write!(t, "{} ", error.msg_prefix())?;
197                 t.reset()?;
198                 t.attr(term::Attr::Bold)?;
199                 write!(t, "{}\n", error.kind)?;
200
201                 // Second line: file info
202                 write!(t, "{}--> ", &prefix_spaces[1..])?;
203                 t.reset()?;
204                 write!(t, "{}:{}\n", file, error.line)?;
205
206                 // Third to fifth lines: show the line which triggered error, if available.
207                 if !error.line_buffer.is_empty() {
208                     let (space_len, target_len) = error.format_len();
209                     t.attr(term::Attr::Bold)?;
210                     write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
211                     t.reset()?;
212                     write!(t, "{}\n", error.line_buffer)?;
213                     t.attr(term::Attr::Bold)?;
214                     write!(t, "{}| ", prefix_spaces)?;
215                     t.fg(term::color::RED)?;
216                     write!(t, "{}\n", target_str(space_len, target_len))?;
217                     t.reset()?;
218                 }
219
220                 // The last line: show note if available.
221                 let msg_suffix = error.msg_suffix();
222                 if !msg_suffix.is_empty() {
223                     t.attr(term::Attr::Bold)?;
224                     write!(t, "{}= note: ", prefix_spaces)?;
225                     t.reset()?;
226                     write!(t, "{}\n", error.msg_suffix())?;
227                 } else {
228                     write!(t, "\n")?;
229                 }
230                 t.reset()?;
231             }
232         }
233
234         if !self.file_error_map.is_empty() {
235             t.attr(term::Attr::Bold)?;
236             write!(t, "warning: ")?;
237             t.reset()?;
238             write!(
239                 t,
240                 "rustfmt may have failed to format. See previous {} errors.\n\n",
241                 self.warning_count(),
242             )?;
243         }
244
245         Ok(())
246     }
247 }
248
249 fn target_str(space_len: usize, target_len: usize) -> String {
250     let empty_line: String = repeat(" ").take(space_len).collect();
251     let overflowed: String = repeat("^").take(target_len).collect();
252     empty_line + &overflowed
253 }
254
255 impl fmt::Display for FormatReport {
256     // Prints all the formatting errors.
257     fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
258         for (file, errors) in &self.file_error_map {
259             for error in errors {
260                 let prefix_space_len = error.line.to_string().len();
261                 let prefix_spaces: String = repeat(" ").take(1 + prefix_space_len).collect();
262
263                 let error_line_buffer = if error.line_buffer.is_empty() {
264                     String::from(" ")
265                 } else {
266                     let (space_len, target_len) = error.format_len();
267                     format!(
268                         "{}|\n{} | {}\n{}| {}",
269                         prefix_spaces,
270                         error.line,
271                         error.line_buffer,
272                         prefix_spaces,
273                         target_str(space_len, target_len)
274                     )
275                 };
276
277                 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
278                 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
279                 let msg_suffix = error.msg_suffix();
280                 let note = if msg_suffix.is_empty() {
281                     String::new()
282                 } else {
283                     format!("{}note= ", prefix_spaces)
284                 };
285
286                 write!(
287                     fmt,
288                     "{}\n{}\n{}\n{}{}\n",
289                     error_info,
290                     file_info,
291                     error_line_buffer,
292                     note,
293                     error.msg_suffix()
294                 )?;
295             }
296         }
297         if !self.file_error_map.is_empty() {
298             write!(
299                 fmt,
300                 "warning: rustfmt may have failed to format. See previous {} errors.\n",
301                 self.warning_count(),
302             )?;
303         }
304         Ok(())
305     }
306 }
307
308 fn should_emit_verbose<F>(path: &FileName, config: &Config, f: F)
309 where
310     F: Fn(),
311 {
312     if config.verbose() && path.to_string() != STDIN {
313         f();
314     }
315 }
316
317 // Formatting which depends on the AST.
318 fn format_ast<F>(
319     krate: &ast::Crate,
320     parse_session: &mut ParseSess,
321     main_file: &FileName,
322     config: &Config,
323     mut after_file: F,
324 ) -> Result<(FileMap, bool), io::Error>
325 where
326     F: FnMut(&FileName, &mut String, &[(usize, usize)]) -> Result<bool, io::Error>,
327 {
328     let mut result = FileMap::new();
329     // diff mode: check if any files are differing
330     let mut has_diff = false;
331
332     // We always skip children for the "Plain" write mode, since there is
333     // nothing to distinguish the nested module contents.
334     let skip_children = config.skip_children() || config.write_mode() == config::WriteMode::Plain;
335     for (path, module) in modules::list_files(krate, parse_session.codemap())? {
336         if skip_children && path != *main_file {
337             continue;
338         }
339         should_emit_verbose(&path, config, || println!("Formatting {}", path));
340         let filemap = parse_session
341             .codemap()
342             .lookup_char_pos(module.inner.lo())
343             .file;
344         let big_snippet = filemap.src.as_ref().unwrap();
345         let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
346         let mut visitor = FmtVisitor::from_codemap(parse_session, config, &snippet_provider);
347         // Format inner attributes if available.
348         if !krate.attrs.is_empty() && path == *main_file {
349             visitor.skip_empty_lines(filemap.end_pos);
350             if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
351                 visitor.push_rewrite(module.inner, None);
352             } else {
353                 visitor.format_separate_mod(module, &*filemap);
354             }
355         } else {
356             visitor.last_pos = filemap.start_pos;
357             visitor.skip_empty_lines(filemap.end_pos);
358             visitor.format_separate_mod(module, &*filemap);
359         };
360
361         debug_assert_eq!(
362             visitor.line_number,
363             ::utils::count_newlines(&format!("{}", visitor.buffer))
364         );
365
366         let filename = path.clone();
367         has_diff |= match after_file(&filename, &mut visitor.buffer, &visitor.skipped_range) {
368             Ok(result) => result,
369             Err(e) => {
370                 // Create a new error with path_str to help users see which files failed
371                 let err_msg = format!("{}: {}", path, e);
372                 return Err(io::Error::new(e.kind(), err_msg));
373             }
374         };
375
376         result.push((filename, visitor.buffer));
377     }
378
379     Ok((result, has_diff))
380 }
381
382 /// Returns true if the line with the given line number was skipped by `#[rustfmt_skip]`.
383 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
384     skipped_range
385         .iter()
386         .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
387 }
388
389 fn should_report_error(
390     config: &Config,
391     char_kind: FullCodeCharKind,
392     is_string: bool,
393     error_kind: ErrorKind,
394 ) -> bool {
395     let allow_error_report = if char_kind.is_comment() || is_string {
396         config.error_on_unformatted()
397     } else {
398         true
399     };
400
401     match error_kind {
402         ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
403         ErrorKind::TrailingWhitespace => allow_error_report,
404         _ => true,
405     }
406 }
407
408 // Formatting done on a char by char or line by line basis.
409 // FIXME(#209) warn on bad license
410 // FIXME(#20) other stuff for parity with make tidy
411 fn format_lines(
412     text: &mut String,
413     name: &FileName,
414     skipped_range: &[(usize, usize)],
415     config: &Config,
416     report: &mut FormatReport,
417 ) {
418     // Iterate over the chars in the file map.
419     let mut trims = vec![];
420     let mut last_wspace: Option<usize> = None;
421     let mut line_len = 0;
422     let mut cur_line = 1;
423     let mut newline_count = 0;
424     let mut errors = vec![];
425     let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
426     let mut line_buffer = String::with_capacity(config.max_width() * 2);
427     let mut is_string = false; // true if the current line contains a string literal.
428     let mut format_line = config.file_lines().contains_line(name, cur_line);
429     let allow_issue_seek = !issue_seeker.is_disabled();
430
431     for (kind, (b, c)) in CharClasses::new(text.chars().enumerate()) {
432         if c == '\r' {
433             continue;
434         }
435
436         if allow_issue_seek && format_line {
437             // Add warnings for bad todos/ fixmes
438             if let Some(issue) = issue_seeker.inspect(c) {
439                 errors.push(FormattingError {
440                     line: cur_line,
441                     kind: ErrorKind::BadIssue(issue),
442                     is_comment: false,
443                     is_string: false,
444                     line_buffer: String::new(),
445                 });
446             }
447         }
448
449         if c == '\n' {
450             if format_line {
451                 // Check for (and record) trailing whitespace.
452                 if let Some(..) = last_wspace {
453                     if should_report_error(config, kind, is_string, ErrorKind::TrailingWhitespace) {
454                         trims.push((cur_line, kind, line_buffer.clone()));
455                     }
456                     line_len -= 1;
457                 }
458
459                 // Check for any line width errors we couldn't correct.
460                 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
461                 if line_len > config.max_width() && !is_skipped_line(cur_line, skipped_range)
462                     && should_report_error(config, kind, is_string, error_kind)
463                 {
464                     errors.push(FormattingError {
465                         line: cur_line,
466                         kind: error_kind,
467                         is_comment: kind.is_comment(),
468                         is_string,
469                         line_buffer: line_buffer.clone(),
470                     });
471                 }
472             }
473
474             line_len = 0;
475             cur_line += 1;
476             format_line = config.file_lines().contains_line(name, cur_line);
477             newline_count += 1;
478             last_wspace = None;
479             line_buffer.clear();
480             is_string = false;
481         } else {
482             newline_count = 0;
483             line_len += if c == '\t' { config.tab_spaces() } else { 1 };
484             if c.is_whitespace() {
485                 if last_wspace.is_none() {
486                     last_wspace = Some(b);
487                 }
488             } else {
489                 last_wspace = None;
490             }
491             line_buffer.push(c);
492             if kind.is_string() {
493                 is_string = true;
494             }
495         }
496     }
497
498     if newline_count > 1 {
499         debug!("track truncate: {} {}", text.len(), newline_count);
500         let line = text.len() - newline_count + 1;
501         text.truncate(line);
502     }
503
504     for &(l, kind, ref b) in &trims {
505         if !is_skipped_line(l, skipped_range) {
506             errors.push(FormattingError {
507                 line: l,
508                 kind: ErrorKind::TrailingWhitespace,
509                 is_comment: kind.is_comment(),
510                 is_string: kind.is_string(),
511                 line_buffer: b.clone(),
512             });
513         }
514     }
515
516     report.file_error_map.insert(name.clone(), errors);
517 }
518
519 fn parse_input<'sess>(
520     input: Input,
521     parse_session: &'sess ParseSess,
522     config: &Config,
523 ) -> Result<ast::Crate, Option<DiagnosticBuilder<'sess>>> {
524     let result = match input {
525         Input::File(file) => {
526             let mut parser = parse::new_parser_from_file(parse_session, &file);
527             parser.cfg_mods = false;
528             if config.skip_children() {
529                 parser.recurse_into_file_modules = false;
530             }
531             parser.parse_crate_mod()
532         }
533         Input::Text(text) => {
534             let mut parser = parse::new_parser_from_source_str(
535                 parse_session,
536                 FileName::Custom("stdin".to_owned()),
537                 text,
538             );
539             parser.cfg_mods = false;
540             if config.skip_children() {
541                 parser.recurse_into_file_modules = false;
542             }
543             parser.parse_crate_mod()
544         }
545     };
546
547     match result {
548         Ok(c) => {
549             if parse_session.span_diagnostic.has_errors() {
550                 // Bail out if the parser recovered from an error.
551                 Err(None)
552             } else {
553                 Ok(c)
554             }
555         }
556         Err(e) => Err(Some(e)),
557     }
558 }
559
560 /// Format the given snippet. The snippet is expected to be *complete* code.
561 /// When we cannot parse the given snippet, this function returns `None`.
562 pub fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
563     let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
564     let input = Input::Text(snippet.into());
565     let mut config = config.clone();
566     config.set().write_mode(config::WriteMode::Plain);
567     config.set().hide_parse_errors(true);
568     match format_input(input, &config, Some(&mut out)) {
569         // `format_input()` returns an empty string on parsing error.
570         Ok(..) if out.is_empty() && !snippet.is_empty() => None,
571         Ok(..) => String::from_utf8(out).ok(),
572         Err(..) => None,
573     }
574 }
575
576 /// Format the given code block. Mainly targeted for code block in comment.
577 /// The code block may be incomplete (i.e. parser may be unable to parse it).
578 /// To avoid panic in parser, we wrap the code block with a dummy function.
579 /// The returned code block does *not* end with newline.
580 pub fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
581     // Wrap the given code block with `fn main()` if it does not have one.
582     let fn_main_prefix = "fn main() {\n";
583     let snippet = fn_main_prefix.to_owned() + code_snippet + "\n}";
584     let mut result = String::with_capacity(snippet.len());
585     let mut is_first = true;
586
587     // Trim "fn main() {" on the first line and "}" on the last line,
588     // then unindent the whole code block.
589     let formatted = format_snippet(&snippet, config)?;
590     // 2 = "}\n"
591     let block_len = formatted.len().checked_sub(2).unwrap_or(0);
592     for line in formatted[fn_main_prefix.len()..block_len].lines() {
593         if !is_first {
594             result.push('\n');
595         } else {
596             is_first = false;
597         }
598         let trimmed_line = if line.len() > config.max_width() {
599             // If there are lines that are larger than max width, we cannot tell
600             // whether we have succeeded but have some comments or strings that
601             // are too long, or we have failed to format code block. We will be
602             // conservative and just return `None` in this case.
603             return None;
604         } else if line.len() > config.tab_spaces() {
605             // Make sure that the line has leading whitespaces.
606             let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
607             if line.starts_with(indent_str.as_ref()) {
608                 let offset = if config.hard_tabs() {
609                     1
610                 } else {
611                     config.tab_spaces()
612                 };
613                 &line[offset..]
614             } else {
615                 line
616             }
617         } else {
618             line
619         };
620         result.push_str(trimmed_line);
621     }
622     Some(result)
623 }
624
625 pub fn format_input<T: Write>(
626     input: Input,
627     config: &Config,
628     mut out: Option<&mut T>,
629 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
630     let mut summary = Summary::default();
631     if config.disable_all_formatting() {
632         // When the input is from stdin, echo back the input.
633         if let Input::Text(ref buf) = input {
634             if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
635                 return Err((e, summary));
636             }
637         }
638         return Ok((summary, FileMap::new(), FormatReport::new()));
639     }
640     let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
641
642     let tty_handler = if config.hide_parse_errors() {
643         let silent_emitter = Box::new(EmitterWriter::new(
644             Box::new(Vec::new()),
645             Some(codemap.clone()),
646             false,
647             false,
648         ));
649         Handler::with_emitter(true, false, silent_emitter)
650     } else {
651         let supports_color = term::stderr().map_or(false, |term| term.supports_color());
652         let color_cfg = if supports_color {
653             ColorConfig::Auto
654         } else {
655             ColorConfig::Never
656         };
657         Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
658     };
659     let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
660
661     let main_file = match input {
662         Input::File(ref file) => FileName::Real(file.clone()),
663         Input::Text(..) => FileName::Custom("stdin".to_owned()),
664     };
665
666     let krate = match parse_input(input, &parse_session, config) {
667         Ok(krate) => krate,
668         Err(diagnostic) => {
669             if let Some(mut diagnostic) = diagnostic {
670                 diagnostic.emit();
671             }
672             summary.add_parsing_error();
673             return Ok((summary, FileMap::new(), FormatReport::new()));
674         }
675     };
676
677     summary.mark_parse_time();
678
679     if parse_session.span_diagnostic.has_errors() {
680         summary.add_parsing_error();
681     }
682
683     // Suppress error output after parsing.
684     let silent_emitter = Box::new(EmitterWriter::new(
685         Box::new(Vec::new()),
686         Some(codemap.clone()),
687         false,
688         false,
689     ));
690     parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
691
692     let mut report = FormatReport::new();
693
694     let format_result = format_ast(
695         &krate,
696         &mut parse_session,
697         &main_file,
698         config,
699         |file_name, file, skipped_range| {
700             // For some reason, the codemap does not include terminating
701             // newlines so we must add one on for each file. This is sad.
702             filemap::append_newline(file);
703
704             format_lines(file, file_name, skipped_range, config, &mut report);
705
706             if let Some(ref mut out) = out {
707                 return filemap::write_file(file, file_name, out, config);
708             }
709             Ok(false)
710         },
711     );
712
713     summary.mark_format_time();
714
715     should_emit_verbose(&main_file, config, || {
716         fn duration_to_f32(d: Duration) -> f32 {
717             d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
718         }
719
720         println!(
721             "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
722             duration_to_f32(summary.get_parse_time().unwrap()),
723             duration_to_f32(summary.get_format_time().unwrap()),
724         )
725     });
726
727     match format_result {
728         Ok((file_map, has_diff)) => {
729             if report.has_warnings() {
730                 summary.add_formatting_error();
731             }
732
733             if has_diff {
734                 summary.add_diff();
735             }
736
737             Ok((summary, file_map, report))
738         }
739         Err(e) => Err((e, summary)),
740     }
741 }
742
743 /// A single span of changed lines, with 0 or more removed lines
744 /// and a vector of 0 or more inserted lines.
745 #[derive(Debug, PartialEq, Eq)]
746 pub struct ModifiedChunk {
747     /// The first to be removed from the original text
748     pub line_number_orig: u32,
749     /// The number of lines which have been replaced
750     pub lines_removed: u32,
751     /// The new lines
752     pub lines: Vec<String>,
753 }
754
755 /// Set of changed sections of a file.
756 #[derive(Debug, PartialEq, Eq)]
757 pub struct ModifiedLines {
758     /// The set of changed chunks.
759     pub chunks: Vec<ModifiedChunk>,
760 }
761
762 /// The successful result of formatting via `get_modified_lines()`.
763 pub struct ModifiedLinesResult {
764     /// The high level summary details
765     pub summary: Summary,
766     /// The result Filemap
767     pub filemap: FileMap,
768     /// Map of formatting errors
769     pub report: FormatReport,
770     /// The sets of updated lines.
771     pub modified_lines: ModifiedLines,
772 }
773
774 /// Format a file and return a `ModifiedLines` data structure describing
775 /// the changed ranges of lines.
776 pub fn get_modified_lines(
777     input: Input,
778     config: &Config,
779 ) -> Result<ModifiedLinesResult, (io::Error, Summary)> {
780     let mut data = Vec::new();
781
782     let mut config = config.clone();
783     config.set().write_mode(config::WriteMode::Modified);
784     let (summary, filemap, formatreport) = format_input(input, &config, Some(&mut data))?;
785
786     let mut lines = data.lines();
787     let mut chunks = Vec::new();
788     while let Some(Ok(header)) = lines.next() {
789         // Parse the header line
790         let values: Vec<_> = header
791             .split(' ')
792             .map(|s| s.parse::<u32>().unwrap())
793             .collect();
794         assert_eq!(values.len(), 3);
795         let line_number_orig = values[0];
796         let lines_removed = values[1];
797         let num_added = values[2];
798         let mut added_lines = Vec::new();
799         for _ in 0..num_added {
800             added_lines.push(lines.next().unwrap().unwrap());
801         }
802         chunks.push(ModifiedChunk {
803             line_number_orig,
804             lines_removed,
805             lines: added_lines,
806         });
807     }
808     Ok(ModifiedLinesResult {
809         summary: summary,
810         filemap: filemap,
811         report: formatreport,
812         modified_lines: ModifiedLines { chunks },
813     })
814 }
815
816 #[derive(Debug)]
817 pub enum Input {
818     File(PathBuf),
819     Text(String),
820 }
821
822 pub fn run(input: Input, config: &Config) -> Summary {
823     let out = &mut stdout();
824     output_header(out, config.write_mode()).ok();
825     match format_input(input, config, Some(out)) {
826         Ok((summary, _, report)) => {
827             output_footer(out, config.write_mode()).ok();
828
829             if report.has_warnings() {
830                 match term::stderr() {
831                     Some(ref t)
832                         if use_colored_tty(config.color()) && t.supports_color()
833                             && t.supports_attr(term::Attr::Bold) =>
834                     {
835                         match report.print_warnings_fancy(term::stderr().unwrap()) {
836                             Ok(..) => (),
837                             Err(..) => panic!("Unable to write to stderr: {}", report),
838                         }
839                     }
840                     _ => msg!("{}", report),
841                 }
842             }
843
844             summary
845         }
846         Err((msg, mut summary)) => {
847             msg!("Error writing files: {}", msg);
848             summary.add_operational_error();
849             summary
850         }
851     }
852 }
853
854 #[cfg(test)]
855 mod test {
856     use super::{format_code_block, format_snippet, Config};
857
858     #[test]
859     fn test_no_panic_on_format_snippet_and_format_code_block() {
860         // `format_snippet()` and `format_code_block()` should not panic
861         // even when we cannot parse the given snippet.
862         let snippet = "let";
863         assert!(format_snippet(snippet, &Config::default()).is_none());
864         assert!(format_code_block(snippet, &Config::default()).is_none());
865     }
866
867     fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
868     where
869         F: Fn(&str, &Config) -> Option<String>,
870     {
871         let output = formatter(input, &Config::default());
872         output.is_some() && output.unwrap() == expected
873     }
874
875     #[test]
876     fn test_format_snippet() {
877         let snippet = "fn main() { println!(\"hello, world\"); }";
878         let expected = "fn main() {\n    \
879                         println!(\"hello, world\");\n\
880                         }\n";
881         assert!(test_format_inner(format_snippet, snippet, expected));
882     }
883
884     #[test]
885     fn test_format_code_block_fail() {
886         #[rustfmt_skip]
887         let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
888         assert!(format_code_block(code_block, &Config::default()).is_none());
889     }
890
891     #[test]
892     fn test_format_code_block() {
893         // simple code block
894         let code_block = "let x=3;";
895         let expected = "let x = 3;";
896         assert!(test_format_inner(format_code_block, code_block, expected));
897
898         // more complex code block, taken from chains.rs.
899         let code_block =
900 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
901 (
902 chain_indent(context, shape.add_offset(parent_rewrite.len())),
903 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
904 )
905 } else if is_block_expr(context, &parent, &parent_rewrite) {
906 match context.config.indent_style() {
907 // Try to put the first child on the same line with parent's last line
908 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
909 // The parent is a block, so align the rest of the chain with the closing
910 // brace.
911 IndentStyle::Visual => (parent_shape, false),
912 }
913 } else {
914 (
915 chain_indent(context, shape.add_offset(parent_rewrite.len())),
916 false,
917 )
918 };
919 ";
920         let expected =
921 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
922     (
923         chain_indent(context, shape.add_offset(parent_rewrite.len())),
924         context.config.indent_style() == IndentStyle::Visual || is_small_parent,
925     )
926 } else if is_block_expr(context, &parent, &parent_rewrite) {
927     match context.config.indent_style() {
928         // Try to put the first child on the same line with parent's last line
929         IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
930         // The parent is a block, so align the rest of the chain with the closing
931         // brace.
932         IndentStyle::Visual => (parent_shape, false),
933     }
934 } else {
935     (
936         chain_indent(context, shape.add_offset(parent_rewrite.len())),
937         false,
938     )
939 };";
940         assert!(test_format_inner(format_code_block, code_block, expected));
941     }
942 }