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