]> git.lizzy.rs Git - rust.git/blob - src/lib.rs
Use Unicode-standard char width to wrap comments or strings. (#3275)
[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 #[macro_use]
12 extern crate derive_new;
13 extern crate atty;
14 extern crate bytecount;
15 extern crate diff;
16 extern crate failure;
17 extern crate itertools;
18 #[cfg(test)]
19 #[macro_use]
20 extern crate lazy_static;
21 #[macro_use]
22 extern crate log;
23 extern crate regex;
24 extern crate rustc_target;
25 extern crate serde;
26 #[macro_use]
27 extern crate serde_derive;
28 extern crate serde_json;
29 extern crate syntax;
30 extern crate syntax_pos;
31 extern crate toml;
32 extern crate unicode_categories;
33 extern crate unicode_segmentation;
34 extern crate unicode_width;
35
36 use std::cell::RefCell;
37 use std::collections::HashMap;
38 use std::fmt;
39 use std::io::{self, Write};
40 use std::mem;
41 use std::panic;
42 use std::path::PathBuf;
43 use std::rc::Rc;
44 use syntax::ast;
45
46 use comment::LineClasses;
47 use failure::Fail;
48 use formatting::{FormatErrorMap, FormattingError, ReportedErrors, SourceFile};
49 use issues::Issue;
50 use shape::Indent;
51
52 pub use config::{
53     load_config, CliOptions, Color, Config, Edition, EmitMode, FileLines, FileName, NewlineStyle,
54     Range, Verbosity,
55 };
56
57 #[macro_use]
58 mod utils;
59
60 mod attr;
61 mod chains;
62 pub(crate) mod checkstyle;
63 mod closures;
64 mod comment;
65 pub(crate) mod config;
66 mod expr;
67 pub(crate) mod formatting;
68 mod imports;
69 mod issues;
70 mod items;
71 mod lists;
72 mod macros;
73 mod matches;
74 mod missed_spans;
75 pub(crate) mod modules;
76 mod overflow;
77 mod pairs;
78 mod patterns;
79 mod reorder;
80 mod rewrite;
81 pub(crate) mod rustfmt_diff;
82 mod shape;
83 pub(crate) mod source_file;
84 pub(crate) mod source_map;
85 mod spanned;
86 mod string;
87 #[cfg(test)]
88 mod test;
89 mod types;
90 mod vertical;
91 pub(crate) mod visitor;
92
93 /// The various errors that can occur during formatting. Note that not all of
94 /// these can currently be propagated to clients.
95 #[derive(Fail, Debug)]
96 pub enum ErrorKind {
97     /// Line has exceeded character limit (found, maximum).
98     #[fail(
99         display = "line formatted, but exceeded maximum width \
100                    (maximum: {} (see `max_width` option), found: {})",
101         _1, _0
102     )]
103     LineOverflow(usize, usize),
104     /// Line ends in whitespace.
105     #[fail(display = "left behind trailing whitespace")]
106     TrailingWhitespace,
107     /// TODO or FIXME item without an issue number.
108     #[fail(display = "found {}", _0)]
109     BadIssue(Issue),
110     /// License check has failed.
111     #[fail(display = "license check failed")]
112     LicenseCheck,
113     /// Used deprecated skip attribute.
114     #[fail(display = "`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
115     DeprecatedAttr,
116     /// Used a rustfmt:: attribute other than skip.
117     #[fail(display = "invalid attribute")]
118     BadAttr,
119     /// An io error during reading or writing.
120     #[fail(display = "io error: {}", _0)]
121     IoError(io::Error),
122     /// Parse error occurred when parsing the input.
123     #[fail(display = "parse error")]
124     ParseError,
125     /// The user mandated a version and the current version of Rustfmt does not
126     /// satisfy that requirement.
127     #[fail(display = "version mismatch")]
128     VersionMismatch,
129     /// If we had formatted the given node, then we would have lost a comment.
130     #[fail(display = "not formatted because a comment would be lost")]
131     LostComment,
132 }
133
134 impl ErrorKind {
135     fn is_comment(&self) -> bool {
136         match self {
137             ErrorKind::LostComment => true,
138             _ => false,
139         }
140     }
141 }
142
143 impl From<io::Error> for ErrorKind {
144     fn from(e: io::Error) -> ErrorKind {
145         ErrorKind::IoError(e)
146     }
147 }
148
149 /// Result of formatting a snippet of code along with ranges of lines that didn't get formatted,
150 /// i.e., that got returned as they were originally.
151 #[derive(Debug)]
152 struct FormattedSnippet {
153     snippet: String,
154     non_formatted_ranges: Vec<(usize, usize)>,
155 }
156
157 impl FormattedSnippet {
158     /// In case the snippet needed to be wrapped in a function, this shifts down the ranges of
159     /// non-formatted code.
160     fn unwrap_code_block(&mut self) {
161         self.non_formatted_ranges
162             .iter_mut()
163             .for_each(|(low, high)| {
164                 *low -= 1;
165                 *high -= 1;
166             });
167     }
168
169     /// Returns true if the line n did not get formatted.
170     fn is_line_non_formatted(&self, n: usize) -> bool {
171         self.non_formatted_ranges
172             .iter()
173             .any(|(low, high)| *low <= n && n <= *high)
174     }
175 }
176
177 /// Reports on any issues that occurred during a run of Rustfmt.
178 ///
179 /// Can be reported to the user via its `Display` implementation of `print_fancy`.
180 #[derive(Clone)]
181 pub struct FormatReport {
182     // Maps stringified file paths to their associated formatting errors.
183     internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
184     non_formatted_ranges: Vec<(usize, usize)>,
185 }
186
187 impl FormatReport {
188     fn new() -> FormatReport {
189         FormatReport {
190             internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
191             non_formatted_ranges: Vec::new(),
192         }
193     }
194
195     fn add_non_formatted_ranges(&mut self, mut ranges: Vec<(usize, usize)>) {
196         self.non_formatted_ranges.append(&mut ranges);
197     }
198
199     fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
200         self.track_errors(&v);
201         self.internal
202             .borrow_mut()
203             .0
204             .entry(f)
205             .and_modify(|fe| fe.append(&mut v))
206             .or_insert(v);
207     }
208
209     fn track_errors(&self, new_errors: &[FormattingError]) {
210         let errs = &mut self.internal.borrow_mut().1;
211         if !new_errors.is_empty() {
212             errs.has_formatting_errors = true;
213         }
214         if errs.has_operational_errors && errs.has_check_errors {
215             return;
216         }
217         for err in new_errors {
218             match err.kind {
219                 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => {
220                     errs.has_operational_errors = true;
221                 }
222                 ErrorKind::BadIssue(_)
223                 | ErrorKind::LicenseCheck
224                 | ErrorKind::DeprecatedAttr
225                 | ErrorKind::BadAttr
226                 | ErrorKind::VersionMismatch => {
227                     errs.has_check_errors = true;
228                 }
229                 _ => {}
230             }
231         }
232     }
233
234     fn add_diff(&mut self) {
235         self.internal.borrow_mut().1.has_diff = true;
236     }
237
238     fn add_macro_format_failure(&mut self) {
239         self.internal.borrow_mut().1.has_macro_format_failure = true;
240     }
241
242     fn add_parsing_error(&mut self) {
243         self.internal.borrow_mut().1.has_parsing_errors = true;
244     }
245
246     fn warning_count(&self) -> usize {
247         self.internal
248             .borrow()
249             .0
250             .iter()
251             .map(|(_, errors)| errors.len())
252             .sum()
253     }
254
255     /// Whether any warnings or errors are present in the report.
256     pub fn has_warnings(&self) -> bool {
257         self.internal.borrow().1.has_formatting_errors
258     }
259
260     /// Print the report to a terminal using colours and potentially other
261     /// fancy output.
262     pub fn fancy_print(
263         &self,
264         mut t: Box<term::Terminal<Output = io::Stderr>>,
265     ) -> Result<(), term::Error> {
266         for (file, errors) in &self.internal.borrow().0 {
267             for error in errors {
268                 let prefix_space_len = error.line.to_string().len();
269                 let prefix_spaces = " ".repeat(1 + prefix_space_len);
270
271                 // First line: the overview of error
272                 t.fg(term::color::RED)?;
273                 t.attr(term::Attr::Bold)?;
274                 write!(t, "{} ", error.msg_prefix())?;
275                 t.reset()?;
276                 t.attr(term::Attr::Bold)?;
277                 writeln!(t, "{}", error.kind)?;
278
279                 // Second line: file info
280                 write!(t, "{}--> ", &prefix_spaces[1..])?;
281                 t.reset()?;
282                 writeln!(t, "{}:{}", file, error.line)?;
283
284                 // Third to fifth lines: show the line which triggered error, if available.
285                 if !error.line_buffer.is_empty() {
286                     let (space_len, target_len) = error.format_len();
287                     t.attr(term::Attr::Bold)?;
288                     write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
289                     t.reset()?;
290                     writeln!(t, "{}", error.line_buffer)?;
291                     t.attr(term::Attr::Bold)?;
292                     write!(t, "{}| ", prefix_spaces)?;
293                     t.fg(term::color::RED)?;
294                     writeln!(t, "{}", FormatReport::target_str(space_len, target_len))?;
295                     t.reset()?;
296                 }
297
298                 // The last line: show note if available.
299                 let msg_suffix = error.msg_suffix();
300                 if !msg_suffix.is_empty() {
301                     t.attr(term::Attr::Bold)?;
302                     write!(t, "{}= note: ", prefix_spaces)?;
303                     t.reset()?;
304                     writeln!(t, "{}", error.msg_suffix())?;
305                 } else {
306                     writeln!(t)?;
307                 }
308                 t.reset()?;
309             }
310         }
311
312         if !self.internal.borrow().0.is_empty() {
313             t.attr(term::Attr::Bold)?;
314             write!(t, "warning: ")?;
315             t.reset()?;
316             write!(
317                 t,
318                 "rustfmt may have failed to format. See previous {} errors.\n\n",
319                 self.warning_count(),
320             )?;
321         }
322
323         Ok(())
324     }
325
326     fn target_str(space_len: usize, target_len: usize) -> String {
327         let empty_line = " ".repeat(space_len);
328         let overflowed = "^".repeat(target_len);
329         empty_line + &overflowed
330     }
331 }
332
333 impl fmt::Display for FormatReport {
334     // Prints all the formatting errors.
335     fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
336         for (file, errors) in &self.internal.borrow().0 {
337             for error in errors {
338                 let prefix_space_len = error.line.to_string().len();
339                 let prefix_spaces = " ".repeat(1 + prefix_space_len);
340
341                 let error_line_buffer = if error.line_buffer.is_empty() {
342                     String::from(" ")
343                 } else {
344                     let (space_len, target_len) = error.format_len();
345                     format!(
346                         "{}|\n{} | {}\n{}| {}",
347                         prefix_spaces,
348                         error.line,
349                         error.line_buffer,
350                         prefix_spaces,
351                         FormatReport::target_str(space_len, target_len)
352                     )
353                 };
354
355                 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
356                 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
357                 let msg_suffix = error.msg_suffix();
358                 let note = if msg_suffix.is_empty() {
359                     String::new()
360                 } else {
361                     format!("{}note= ", prefix_spaces)
362                 };
363
364                 writeln!(
365                     fmt,
366                     "{}\n{}\n{}\n{}{}",
367                     error_info,
368                     file_info,
369                     error_line_buffer,
370                     note,
371                     error.msg_suffix()
372                 )?;
373             }
374         }
375         if !self.internal.borrow().0.is_empty() {
376             writeln!(
377                 fmt,
378                 "warning: rustfmt may have failed to format. See previous {} errors.",
379                 self.warning_count(),
380             )?;
381         }
382         Ok(())
383     }
384 }
385
386 /// Format the given snippet. The snippet is expected to be *complete* code.
387 /// When we cannot parse the given snippet, this function returns `None`.
388 fn format_snippet(snippet: &str, config: &Config) -> Option<FormattedSnippet> {
389     let mut config = config.clone();
390     panic::catch_unwind(|| {
391         let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
392         config.set().emit_mode(config::EmitMode::Stdout);
393         config.set().verbose(Verbosity::Quiet);
394         config.set().hide_parse_errors(true);
395
396         let (formatting_error, result) = {
397             let input = Input::Text(snippet.into());
398             let mut session = Session::new(config, Some(&mut out));
399             let result = session.format(input);
400             (
401                 session.errors.has_macro_format_failure
402                     || session.out.as_ref().unwrap().is_empty() && !snippet.is_empty()
403                     || result.is_err(),
404                 result,
405             )
406         };
407         if formatting_error {
408             None
409         } else {
410             String::from_utf8(out).ok().map(|snippet| FormattedSnippet {
411                 snippet,
412                 non_formatted_ranges: result.unwrap().non_formatted_ranges,
413             })
414         }
415     })
416     // Discard panics encountered while formatting the snippet
417     // The ? operator is needed to remove the extra Option
418     .ok()?
419 }
420
421 /// Format the given code block. Mainly targeted for code block in comment.
422 /// The code block may be incomplete (i.e. parser may be unable to parse it).
423 /// To avoid panic in parser, we wrap the code block with a dummy function.
424 /// The returned code block does *not* end with newline.
425 fn format_code_block(code_snippet: &str, config: &Config) -> Option<FormattedSnippet> {
426     const FN_MAIN_PREFIX: &str = "fn main() {\n";
427
428     fn enclose_in_main_block(s: &str, config: &Config) -> String {
429         let indent = Indent::from_width(config, config.tab_spaces());
430         let mut result = String::with_capacity(s.len() * 2);
431         result.push_str(FN_MAIN_PREFIX);
432         let mut need_indent = true;
433         for (kind, line) in LineClasses::new(s) {
434             if need_indent {
435                 result.push_str(&indent.to_string(config));
436             }
437             result.push_str(&line);
438             result.push('\n');
439             need_indent = !kind.is_string() || line.ends_with('\\');
440         }
441         result.push('}');
442         result
443     }
444
445     // Wrap the given code block with `fn main()` if it does not have one.
446     let snippet = enclose_in_main_block(code_snippet, config);
447     let mut result = String::with_capacity(snippet.len());
448     let mut is_first = true;
449
450     // While formatting the code, ignore the config's newline style setting and always use "\n"
451     // instead of "\r\n" for the newline characters. This is okay because the output here is
452     // not directly outputted by rustfmt command, but used by the comment formatter's input.
453     // We have output-file-wide "\n" ==> "\r\n" conversion process after here if it's necessary.
454     let mut config_with_unix_newline = config.clone();
455     config_with_unix_newline
456         .set()
457         .newline_style(NewlineStyle::Unix);
458     let mut formatted = format_snippet(&snippet, &config_with_unix_newline)?;
459     // Remove wrapping main block
460     formatted.unwrap_code_block();
461
462     // Trim "fn main() {" on the first line and "}" on the last line,
463     // then unindent the whole code block.
464     let block_len = formatted
465         .snippet
466         .rfind('}')
467         .unwrap_or(formatted.snippet.len());
468     let mut is_indented = true;
469     for (kind, ref line) in LineClasses::new(&formatted.snippet[FN_MAIN_PREFIX.len()..block_len]) {
470         if !is_first {
471             result.push('\n');
472         } else {
473             is_first = false;
474         }
475         let trimmed_line = if !is_indented {
476             line
477         } else if line.len() > config.max_width() {
478             // If there are lines that are larger than max width, we cannot tell
479             // whether we have succeeded but have some comments or strings that
480             // are too long, or we have failed to format code block. We will be
481             // conservative and just return `None` in this case.
482             return None;
483         } else if line.len() > config.tab_spaces() {
484             // Make sure that the line has leading whitespaces.
485             let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
486             if line.starts_with(indent_str.as_ref()) {
487                 let offset = if config.hard_tabs() {
488                     1
489                 } else {
490                     config.tab_spaces()
491                 };
492                 &line[offset..]
493             } else {
494                 line
495             }
496         } else {
497             line
498         };
499         result.push_str(trimmed_line);
500         is_indented = !kind.is_string() || line.ends_with('\\');
501     }
502     Some(FormattedSnippet {
503         snippet: result,
504         non_formatted_ranges: formatted.non_formatted_ranges,
505     })
506 }
507
508 /// A session is a run of rustfmt across a single or multiple inputs.
509 pub struct Session<'b, T: Write + 'b> {
510     pub config: Config,
511     pub out: Option<&'b mut T>,
512     pub(crate) errors: ReportedErrors,
513     source_file: SourceFile,
514 }
515
516 impl<'b, T: Write + 'b> Session<'b, T> {
517     pub fn new(config: Config, out: Option<&'b mut T>) -> Session<'b, T> {
518         if config.emit_mode() == EmitMode::Checkstyle {
519             println!("{}", checkstyle::header());
520         }
521
522         Session {
523             config,
524             out,
525             errors: ReportedErrors::default(),
526             source_file: SourceFile::new(),
527         }
528     }
529
530     /// The main entry point for Rustfmt. Formats the given input according to the
531     /// given config. `out` is only necessary if required by the configuration.
532     pub fn format(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
533         self.format_input_inner(input)
534     }
535
536     pub fn override_config<F, U>(&mut self, mut config: Config, f: F) -> U
537     where
538         F: FnOnce(&mut Session<'b, T>) -> U,
539     {
540         mem::swap(&mut config, &mut self.config);
541         let result = f(self);
542         mem::swap(&mut config, &mut self.config);
543         result
544     }
545
546     pub fn add_operational_error(&mut self) {
547         self.errors.has_operational_errors = true;
548     }
549
550     pub fn has_operational_errors(&self) -> bool {
551         self.errors.has_operational_errors
552     }
553
554     pub fn has_parsing_errors(&self) -> bool {
555         self.errors.has_parsing_errors
556     }
557
558     pub fn has_formatting_errors(&self) -> bool {
559         self.errors.has_formatting_errors
560     }
561
562     pub fn has_check_errors(&self) -> bool {
563         self.errors.has_check_errors
564     }
565
566     pub fn has_diff(&self) -> bool {
567         self.errors.has_diff
568     }
569
570     pub fn has_no_errors(&self) -> bool {
571         !(self.has_operational_errors()
572             || self.has_parsing_errors()
573             || self.has_formatting_errors()
574             || self.has_check_errors()
575             || self.has_diff())
576             || self.errors.has_macro_format_failure
577     }
578 }
579
580 impl<'b, T: Write + 'b> Drop for Session<'b, T> {
581     fn drop(&mut self) {
582         if self.config.emit_mode() == EmitMode::Checkstyle {
583             println!("{}", checkstyle::footer());
584         }
585     }
586 }
587
588 #[derive(Debug)]
589 pub enum Input {
590     File(PathBuf),
591     Text(String),
592 }
593
594 impl Input {
595     fn is_text(&self) -> bool {
596         match *self {
597             Input::File(_) => false,
598             Input::Text(_) => true,
599         }
600     }
601
602     fn file_name(&self) -> FileName {
603         match *self {
604             Input::File(ref file) => FileName::Real(file.clone()),
605             Input::Text(..) => FileName::Stdin,
606         }
607     }
608 }
609
610 #[cfg(test)]
611 mod unit_tests {
612     use super::*;
613
614     #[test]
615     fn test_no_panic_on_format_snippet_and_format_code_block() {
616         // `format_snippet()` and `format_code_block()` should not panic
617         // even when we cannot parse the given snippet.
618         let snippet = "let";
619         assert!(format_snippet(snippet, &Config::default()).is_none());
620         assert!(format_code_block(snippet, &Config::default()).is_none());
621     }
622
623     fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
624     where
625         F: Fn(&str, &Config) -> Option<FormattedSnippet>,
626     {
627         let output = formatter(input, &Config::default());
628         output.is_some() && output.unwrap().snippet == expected
629     }
630
631     #[test]
632     fn test_format_snippet() {
633         let snippet = "fn main() { println!(\"hello, world\"); }";
634         #[cfg(not(windows))]
635         let expected = "fn main() {\n    \
636                         println!(\"hello, world\");\n\
637                         }\n";
638         #[cfg(windows)]
639         let expected = "fn main() {\r\n    \
640                         println!(\"hello, world\");\r\n\
641                         }\r\n";
642         assert!(test_format_inner(format_snippet, snippet, expected));
643     }
644
645     #[test]
646     fn test_format_code_block_fail() {
647         #[rustfmt::skip]
648         let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
649         assert!(format_code_block(code_block, &Config::default()).is_none());
650     }
651
652     #[test]
653     fn test_format_code_block() {
654         // simple code block
655         let code_block = "let x=3;";
656         let expected = "let x = 3;";
657         assert!(test_format_inner(format_code_block, code_block, expected));
658
659         // more complex code block, taken from chains.rs.
660         let code_block =
661 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
662 (
663 chain_indent(context, shape.add_offset(parent_rewrite.len())),
664 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
665 )
666 } else if is_block_expr(context, &parent, &parent_rewrite) {
667 match context.config.indent_style() {
668 // Try to put the first child on the same line with parent's last line
669 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
670 // The parent is a block, so align the rest of the chain with the closing
671 // brace.
672 IndentStyle::Visual => (parent_shape, false),
673 }
674 } else {
675 (
676 chain_indent(context, shape.add_offset(parent_rewrite.len())),
677 false,
678 )
679 };
680 ";
681         let expected =
682 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
683     (
684         chain_indent(context, shape.add_offset(parent_rewrite.len())),
685         context.config.indent_style() == IndentStyle::Visual || is_small_parent,
686     )
687 } else if is_block_expr(context, &parent, &parent_rewrite) {
688     match context.config.indent_style() {
689         // Try to put the first child on the same line with parent's last line
690         IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
691         // The parent is a block, so align the rest of the chain with the closing
692         // brace.
693         IndentStyle::Visual => (parent_shape, false),
694     }
695 } else {
696     (
697         chain_indent(context, shape.add_offset(parent_rewrite.len())),
698         false,
699     )
700 };";
701         assert!(test_format_inner(format_code_block, code_block, expected));
702     }
703 }