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