]> git.lizzy.rs Git - rust.git/blob - src/lib.rs
discard trailing blank comments
[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(tool_attributes)]
12 #![feature(decl_macro)]
13 #![allow(unused_attributes)]
14 #![feature(type_ascription)]
15 #![feature(unicode_internals)]
16 #![feature(extern_prelude)]
17 #![feature(nll)]
18
19 #[macro_use]
20 extern crate derive_new;
21 extern crate diff;
22 extern crate failure;
23 extern crate isatty;
24 extern crate itertools;
25 #[cfg(test)]
26 #[macro_use]
27 extern crate lazy_static;
28 #[macro_use]
29 extern crate log;
30 extern crate regex;
31 extern crate rustc_target;
32 extern crate serde;
33 #[macro_use]
34 extern crate serde_derive;
35 extern crate serde_json;
36 extern crate syntax;
37 extern crate syntax_pos;
38 extern crate toml;
39 extern crate unicode_segmentation;
40
41 use std::cell::RefCell;
42 use std::collections::HashMap;
43 use std::fmt;
44 use std::io::{self, Write};
45 use std::mem;
46 use std::path::PathBuf;
47 use std::rc::Rc;
48 use syntax::ast;
49
50 use comment::LineClasses;
51 use failure::Fail;
52 use formatting::{FileMap, FormatErrorMap, FormattingError, ReportedErrors};
53 use issues::Issue;
54 use shape::Indent;
55
56 pub use config::{
57     load_config, CliOptions, Color, Config, EmitMode, FileLines, FileName, NewlineStyle, Range,
58     Verbosity,
59 };
60
61 #[macro_use]
62 mod utils;
63
64 mod attr;
65 mod chains;
66 pub(crate) mod checkstyle;
67 mod closures;
68 pub(crate) mod codemap;
69 mod comment;
70 pub(crate) mod config;
71 mod expr;
72 pub(crate) mod filemap;
73 pub(crate) mod formatting;
74 mod imports;
75 mod issues;
76 mod items;
77 mod lists;
78 mod macros;
79 mod matches;
80 mod missed_spans;
81 pub(crate) mod modules;
82 mod overflow;
83 mod pairs;
84 mod patterns;
85 mod reorder;
86 mod rewrite;
87 pub(crate) mod rustfmt_diff;
88 mod shape;
89 mod spanned;
90 mod string;
91 #[cfg(test)]
92 mod test;
93 mod types;
94 mod vertical;
95 pub(crate) mod visitor;
96
97 /// The various errors that can occur during formatting. Note that not all of
98 /// these can currently be propagated to clients.
99 #[derive(Fail, Debug)]
100 pub enum ErrorKind {
101     /// Line has exceeded character limit (found, maximum).
102     #[fail(
103         display = "line formatted, but exceeded maximum width \
104                    (maximum: {} (see `max_width` option), found: {})",
105         _0,
106         _1
107     )]
108     LineOverflow(usize, usize),
109     /// Line ends in whitespace.
110     #[fail(display = "left behind trailing whitespace")]
111     TrailingWhitespace,
112     /// TODO or FIXME item without an issue number.
113     #[fail(display = "found {}", _0)]
114     BadIssue(Issue),
115     /// License check has failed.
116     #[fail(display = "license check failed")]
117     LicenseCheck,
118     /// Used deprecated skip attribute.
119     #[fail(display = "`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
120     DeprecatedAttr,
121     /// Used a rustfmt:: attribute other than skip.
122     #[fail(display = "invalid attribute")]
123     BadAttr,
124     /// An io error during reading or writing.
125     #[fail(display = "io error: {}", _0)]
126     IoError(io::Error),
127     /// Parse error occured when parsing the Input.
128     #[fail(display = "parse error")]
129     ParseError,
130     /// The user mandated a version and the current version of Rustfmt does not
131     /// satisfy that requirement.
132     #[fail(display = "version mismatch")]
133     VersionMismatch,
134     /// If we had formatted the given node, then we would have lost a comment.
135     #[fail(display = "not formatted because a comment would be lost")]
136     LostComment,
137 }
138
139 impl ErrorKind {
140     fn is_comment(&self) -> bool {
141         match self {
142             ErrorKind::LostComment => true,
143             _ => false,
144         }
145     }
146 }
147
148 impl From<io::Error> for ErrorKind {
149     fn from(e: io::Error) -> ErrorKind {
150         ErrorKind::IoError(e)
151     }
152 }
153
154 /// Reports on any issues that occurred during a run of Rustfmt.
155 ///
156 /// Can be reported to the user via its `Display` implementation of `print_fancy`.
157 #[derive(Clone)]
158 pub struct FormatReport {
159     // Maps stringified file paths to their associated formatting errors.
160     internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
161 }
162
163 impl FormatReport {
164     fn new() -> FormatReport {
165         FormatReport {
166             internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
167         }
168     }
169
170     fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
171         self.track_errors(&v);
172         self.internal
173             .borrow_mut()
174             .0
175             .entry(f)
176             .and_modify(|fe| fe.append(&mut v))
177             .or_insert(v);
178     }
179
180     fn track_errors(&self, new_errors: &[FormattingError]) {
181         let errs = &mut self.internal.borrow_mut().1;
182         if !new_errors.is_empty() {
183             errs.has_formatting_errors = true;
184         }
185         if errs.has_operational_errors && errs.has_check_errors {
186             return;
187         }
188         for err in new_errors {
189             match err.kind {
190                 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => {
191                     errs.has_operational_errors = true;
192                 }
193                 ErrorKind::BadIssue(_)
194                 | ErrorKind::LicenseCheck
195                 | ErrorKind::DeprecatedAttr
196                 | ErrorKind::BadAttr
197                 | ErrorKind::VersionMismatch => {
198                     errs.has_check_errors = true;
199                 }
200                 _ => {}
201             }
202         }
203     }
204
205     fn add_diff(&mut self) {
206         self.internal.borrow_mut().1.has_diff = true;
207     }
208
209     fn add_macro_format_failure(&mut self) {
210         self.internal.borrow_mut().1.has_macro_format_failure = true;
211     }
212
213     fn add_parsing_error(&mut self) {
214         self.internal.borrow_mut().1.has_parsing_errors = true;
215     }
216
217     fn warning_count(&self) -> usize {
218         self.internal
219             .borrow()
220             .0
221             .iter()
222             .map(|(_, errors)| errors.len())
223             .sum()
224     }
225
226     /// Whether any warnings or errors are present in the report.
227     pub fn has_warnings(&self) -> bool {
228         self.internal.borrow().1.has_formatting_errors
229     }
230
231     /// Print the report to a terminal using colours and potentially other
232     /// fancy output.
233     pub fn fancy_print(
234         &self,
235         mut t: Box<term::Terminal<Output = io::Stderr>>,
236     ) -> Result<(), term::Error> {
237         for (file, errors) in &self.internal.borrow().0 {
238             for error in errors {
239                 let prefix_space_len = error.line.to_string().len();
240                 let prefix_spaces = " ".repeat(1 + prefix_space_len);
241
242                 // First line: the overview of error
243                 t.fg(term::color::RED)?;
244                 t.attr(term::Attr::Bold)?;
245                 write!(t, "{} ", error.msg_prefix())?;
246                 t.reset()?;
247                 t.attr(term::Attr::Bold)?;
248                 writeln!(t, "{}", error.kind)?;
249
250                 // Second line: file info
251                 write!(t, "{}--> ", &prefix_spaces[1..])?;
252                 t.reset()?;
253                 writeln!(t, "{}:{}", file, error.line)?;
254
255                 // Third to fifth lines: show the line which triggered error, if available.
256                 if !error.line_buffer.is_empty() {
257                     let (space_len, target_len) = error.format_len();
258                     t.attr(term::Attr::Bold)?;
259                     write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
260                     t.reset()?;
261                     writeln!(t, "{}", error.line_buffer)?;
262                     t.attr(term::Attr::Bold)?;
263                     write!(t, "{}| ", prefix_spaces)?;
264                     t.fg(term::color::RED)?;
265                     writeln!(t, "{}", FormatReport::target_str(space_len, target_len))?;
266                     t.reset()?;
267                 }
268
269                 // The last line: show note if available.
270                 let msg_suffix = error.msg_suffix();
271                 if !msg_suffix.is_empty() {
272                     t.attr(term::Attr::Bold)?;
273                     write!(t, "{}= note: ", prefix_spaces)?;
274                     t.reset()?;
275                     writeln!(t, "{}", error.msg_suffix())?;
276                 } else {
277                     writeln!(t)?;
278                 }
279                 t.reset()?;
280             }
281         }
282
283         if !self.internal.borrow().0.is_empty() {
284             t.attr(term::Attr::Bold)?;
285             write!(t, "warning: ")?;
286             t.reset()?;
287             write!(
288                 t,
289                 "rustfmt may have failed to format. See previous {} errors.\n\n",
290                 self.warning_count(),
291             )?;
292         }
293
294         Ok(())
295     }
296
297     fn target_str(space_len: usize, target_len: usize) -> String {
298         let empty_line = " ".repeat(space_len);
299         let overflowed = "^".repeat(target_len);
300         empty_line + &overflowed
301     }
302 }
303
304 impl fmt::Display for FormatReport {
305     // Prints all the formatting errors.
306     fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
307         for (file, errors) in &self.internal.borrow().0 {
308             for error in errors {
309                 let prefix_space_len = error.line.to_string().len();
310                 let prefix_spaces = " ".repeat(1 + prefix_space_len);
311
312                 let error_line_buffer = if error.line_buffer.is_empty() {
313                     String::from(" ")
314                 } else {
315                     let (space_len, target_len) = error.format_len();
316                     format!(
317                         "{}|\n{} | {}\n{}| {}",
318                         prefix_spaces,
319                         error.line,
320                         error.line_buffer,
321                         prefix_spaces,
322                         FormatReport::target_str(space_len, target_len)
323                     )
324                 };
325
326                 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
327                 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
328                 let msg_suffix = error.msg_suffix();
329                 let note = if msg_suffix.is_empty() {
330                     String::new()
331                 } else {
332                     format!("{}note= ", prefix_spaces)
333                 };
334
335                 writeln!(
336                     fmt,
337                     "{}\n{}\n{}\n{}{}",
338                     error_info,
339                     file_info,
340                     error_line_buffer,
341                     note,
342                     error.msg_suffix()
343                 )?;
344             }
345         }
346         if !self.internal.borrow().0.is_empty() {
347             writeln!(
348                 fmt,
349                 "warning: rustfmt may have failed to format. See previous {} errors.",
350                 self.warning_count(),
351             )?;
352         }
353         Ok(())
354     }
355 }
356
357 /// Format the given snippet. The snippet is expected to be *complete* code.
358 /// When we cannot parse the given snippet, this function returns `None`.
359 fn format_snippet(snippet: &str, config: &Config) -> Option<String> {
360     let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
361     let input = Input::Text(snippet.into());
362     let mut config = config.clone();
363     config.set().emit_mode(config::EmitMode::Stdout);
364     config.set().verbose(Verbosity::Quiet);
365     config.set().hide_parse_errors(true);
366     {
367         let mut session = Session::new(config, Some(&mut out));
368         let result = session.format(input);
369         let formatting_error = session.errors.has_macro_format_failure
370             || session.out.as_ref().unwrap().is_empty() && !snippet.is_empty();
371         if formatting_error || result.is_err() {
372             return None;
373         }
374     }
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     filemap: FileMap,
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             filemap: FileMap::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 }