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