1 #![feature(rustc_private)]
2 #![deny(rust_2018_idioms)]
3 #![warn(unreachable_pub)]
6 extern crate derive_new
;
9 extern crate lazy_static
;
13 // N.B. these crates are loaded from the sysroot, so they need extern crate.
14 extern crate rustc_ast
;
15 extern crate rustc_ast_pretty
;
16 extern crate rustc_data_structures
;
17 extern crate rustc_errors
;
18 extern crate rustc_expand
;
19 extern crate rustc_parse
;
20 extern crate rustc_session
;
21 extern crate rustc_span
;
23 use std
::cell
::RefCell
;
24 use std
::collections
::HashMap
;
26 use std
::io
::{self, Write}
;
29 use std
::path
::PathBuf
;
34 use rustc_span
::symbol
;
37 use crate::comment
::LineClasses
;
38 use crate::emitter
::Emitter
;
39 use crate::formatting
::{FormatErrorMap, FormattingError, ReportedErrors, SourceFile}
;
40 use crate::issues
::Issue
;
41 use crate::modules
::ModuleResolutionError
;
42 use crate::shape
::Indent
;
43 use crate::syntux
::parser
::DirectoryOwnership
;
44 use crate::utils
::indent_next_line
;
46 pub use crate::config
::{
47 load_config
, CliOptions
, Color
, Config
, Edition
, EmitMode
, FileLines
, FileName
, NewlineStyle
,
51 pub use crate::format_report_formatter
::{FormatReportFormatter, FormatReportFormatterBuilder}
;
53 pub use crate::rustfmt_diff
::{ModifiedChunk, ModifiedLines}
;
62 pub(crate) mod config
;
66 mod format_report_formatter
;
67 pub(crate) mod formatting
;
76 pub(crate) mod modules
;
83 pub(crate) mod rustfmt_diff
;
86 pub(crate) mod source_file
;
87 pub(crate) mod source_map
;
96 pub(crate) mod visitor
;
98 /// The various errors that can occur during formatting. Note that not all of
99 /// these can currently be propagated to clients.
100 #[derive(Error, Debug)]
102 /// Line has exceeded character limit (found, maximum).
104 "line formatted, but exceeded maximum width \
105 (maximum: {1} (see `max_width` option), found: {0})"
107 LineOverflow(usize, usize),
108 /// Line ends in whitespace.
109 #[error("left behind trailing whitespace")]
111 /// TODO or FIXME item without an issue number.
112 #[error("found {0}")]
114 /// License check has failed.
115 #[error("license check failed")]
117 /// Used deprecated skip attribute.
118 #[error("`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
120 /// Used a rustfmt:: attribute other than skip or skip::macros.
121 #[error("invalid attribute")]
123 /// An io error during reading or writing.
124 #[error("io error: {0}")]
126 /// Error during module resolution.
128 ModuleResolutionError(#[from] ModuleResolutionError),
129 /// Parse error occurred when parsing the input.
130 #[error("parse error")]
132 /// The user mandated a version and the current version of Rustfmt does not
133 /// satisfy that requirement.
134 #[error("version mismatch")]
136 /// If we had formatted the given node, then we would have lost a comment.
137 #[error("not formatted because a comment would be lost")]
139 /// Invalid glob pattern in `ignore` configuration option.
140 #[error("Invalid glob pattern found in ignore list: {0}")]
141 InvalidGlobPattern(ignore
::Error
),
145 fn is_comment(&self) -> bool
{
147 ErrorKind
::LostComment
=> true,
153 impl From
<io
::Error
> for ErrorKind
{
154 fn from(e
: io
::Error
) -> ErrorKind
{
155 ErrorKind
::IoError(e
)
159 /// Result of formatting a snippet of code along with ranges of lines that didn't get formatted,
160 /// i.e., that got returned as they were originally.
162 struct FormattedSnippet
{
164 non_formatted_ranges
: Vec
<(usize, usize)>,
167 impl FormattedSnippet
{
168 /// In case the snippet needed to be wrapped in a function, this shifts down the ranges of
169 /// non-formatted code.
170 fn unwrap_code_block(&mut self) {
171 self.non_formatted_ranges
173 .for_each(|(low
, high
)| {
179 /// Returns `true` if the line n did not get formatted.
180 fn is_line_non_formatted(&self, n
: usize) -> bool
{
181 self.non_formatted_ranges
183 .any(|(low
, high
)| *low
<= n
&& n
<= *high
)
187 /// Reports on any issues that occurred during a run of Rustfmt.
189 /// Can be reported to the user using the `Display` impl on [`FormatReportFormatter`].
191 pub struct FormatReport
{
192 // Maps stringified file paths to their associated formatting errors.
193 internal
: Rc
<RefCell
<(FormatErrorMap
, ReportedErrors
)>>,
194 non_formatted_ranges
: Vec
<(usize, usize)>,
198 fn new() -> FormatReport
{
200 internal
: Rc
::new(RefCell
::new((HashMap
::new(), ReportedErrors
::default()))),
201 non_formatted_ranges
: Vec
::new(),
205 fn add_non_formatted_ranges(&mut self, mut ranges
: Vec
<(usize, usize)>) {
206 self.non_formatted_ranges
.append(&mut ranges
);
209 fn append(&self, f
: FileName
, mut v
: Vec
<FormattingError
>) {
210 self.track_errors(&v
);
215 .and_modify(|fe
| fe
.append(&mut v
))
219 fn track_errors(&self, new_errors
: &[FormattingError
]) {
220 let errs
= &mut self.internal
.borrow_mut().1;
221 if !new_errors
.is_empty() {
222 errs
.has_formatting_errors
= true;
224 if errs
.has_operational_errors
&& errs
.has_check_errors
&& errs
.has_unformatted_code_errors
228 for err
in new_errors
{
230 ErrorKind
::LineOverflow(..) => {
231 errs
.has_operational_errors
= true;
233 ErrorKind
::TrailingWhitespace
=> {
234 errs
.has_operational_errors
= true;
235 errs
.has_unformatted_code_errors
= true;
237 ErrorKind
::LostComment
=> {
238 errs
.has_unformatted_code_errors
= true;
240 ErrorKind
::BadIssue(_
)
241 | ErrorKind
::LicenseCheck
242 | ErrorKind
::DeprecatedAttr
244 | ErrorKind
::VersionMismatch
=> {
245 errs
.has_check_errors
= true;
252 fn add_diff(&mut self) {
253 self.internal
.borrow_mut().1.has_diff
= true;
256 fn add_macro_format_failure(&mut self) {
257 self.internal
.borrow_mut().1.has_macro_format_failure
= true;
260 fn add_parsing_error(&mut self) {
261 self.internal
.borrow_mut().1.has_parsing_errors
= true;
264 fn warning_count(&self) -> usize {
269 .map(|(_
, errors
)| errors
.len())
273 /// Whether any warnings or errors are present in the report.
274 pub fn has_warnings(&self) -> bool
{
275 self.internal
.borrow().1.has_formatting_errors
278 /// Print the report to a terminal using colours and potentially other
280 #[deprecated(note = "Use FormatReportFormatter with colors enabled instead")]
283 mut t
: Box
<dyn term
::Terminal
<Output
= io
::Stderr
>>,
284 ) -> Result
<(), term
::Error
> {
288 FormatReportFormatterBuilder
::new(&self)
296 /// Deprecated - Use FormatReportFormatter instead
297 // https://github.com/rust-lang/rust/issues/78625
298 // https://github.com/rust-lang/rust/issues/39935
299 impl fmt
::Display
for FormatReport
{
300 // Prints all the formatting errors.
301 fn fmt(&self, fmt
: &mut fmt
::Formatter
<'_
>) -> Result
<(), fmt
::Error
> {
302 write
!(fmt
, "{}", FormatReportFormatterBuilder
::new(&self).build())?
;
307 /// Format the given snippet. The snippet is expected to be *complete* code.
308 /// When we cannot parse the given snippet, this function returns `None`.
309 fn format_snippet(snippet
: &str, config
: &Config
, is_macro_def
: bool
) -> Option
<FormattedSnippet
> {
310 let mut config
= config
.clone();
311 panic
::catch_unwind(|| {
312 let mut out
: Vec
<u8> = Vec
::with_capacity(snippet
.len() * 2);
313 config
.set().emit_mode(config
::EmitMode
::Stdout
);
314 config
.set().verbose(Verbosity
::Quiet
);
315 config
.set().hide_parse_errors(true);
317 config
.set().error_on_unformatted(true);
320 let (formatting_error
, result
) = {
321 let input
= Input
::Text(snippet
.into());
322 let mut session
= Session
::new(config
, Some(&mut out
));
323 let result
= session
.format_input_inner(input
, is_macro_def
);
325 session
.errors
.has_macro_format_failure
326 || session
.out
.as_ref().unwrap().is_empty() && !snippet
.is_empty()
328 || (is_macro_def
&& session
.has_unformatted_code_errors()),
332 if formatting_error
{
335 String
::from_utf8(out
).ok().map(|snippet
| FormattedSnippet
{
337 non_formatted_ranges
: result
.unwrap().non_formatted_ranges
,
341 // Discard panics encountered while formatting the snippet
342 // The ? operator is needed to remove the extra Option
346 /// Format the given code block. Mainly targeted for code block in comment.
347 /// The code block may be incomplete (i.e., parser may be unable to parse it).
348 /// To avoid panic in parser, we wrap the code block with a dummy function.
349 /// The returned code block does **not** end with newline.
350 fn format_code_block(
354 ) -> Option
<FormattedSnippet
> {
355 const FN_MAIN_PREFIX
: &str = "fn main() {\n";
357 fn enclose_in_main_block(s
: &str, config
: &Config
) -> String
{
358 let indent
= Indent
::from_width(config
, config
.tab_spaces());
359 let mut result
= String
::with_capacity(s
.len() * 2);
360 result
.push_str(FN_MAIN_PREFIX
);
361 let mut need_indent
= true;
362 for (kind
, line
) in LineClasses
::new(s
) {
364 result
.push_str(&indent
.to_string(config
));
366 result
.push_str(&line
);
368 need_indent
= indent_next_line(kind
, &line
, config
);
374 // Wrap the given code block with `fn main()` if it does not have one.
375 let snippet
= enclose_in_main_block(code_snippet
, config
);
376 let mut result
= String
::with_capacity(snippet
.len());
377 let mut is_first
= true;
379 // While formatting the code, ignore the config's newline style setting and always use "\n"
380 // instead of "\r\n" for the newline characters. This is ok because the output here is
381 // not directly outputted by rustfmt command, but used by the comment formatter's input.
382 // We have output-file-wide "\n" ==> "\r\n" conversion process after here if it's necessary.
383 let mut config_with_unix_newline
= config
.clone();
384 config_with_unix_newline
386 .newline_style(NewlineStyle
::Unix
);
387 let mut formatted
= format_snippet(&snippet
, &config_with_unix_newline
, is_macro_def
)?
;
388 // Remove wrapping main block
389 formatted
.unwrap_code_block();
391 // Trim "fn main() {" on the first line and "}" on the last line,
392 // then unindent the whole code block.
393 let block_len
= formatted
396 .unwrap_or_else(|| formatted
.snippet
.len());
397 let mut is_indented
= true;
398 let indent_str
= Indent
::from_width(config
, config
.tab_spaces()).to_string(config
);
399 for (kind
, ref line
) in LineClasses
::new(&formatted
.snippet
[FN_MAIN_PREFIX
.len()..block_len
]) {
405 let trimmed_line
= if !is_indented
{
407 } else if line
.len() > config
.max_width() {
408 // If there are lines that are larger than max width, we cannot tell
409 // whether we have succeeded but have some comments or strings that
410 // are too long, or we have failed to format code block. We will be
411 // conservative and just return `None` in this case.
413 } else if line
.len() > indent_str
.len() {
414 // Make sure that the line has leading whitespaces.
415 if line
.starts_with(indent_str
.as_ref()) {
416 let offset
= if config
.hard_tabs() {
428 result
.push_str(trimmed_line
);
429 is_indented
= indent_next_line(kind
, line
, config
);
431 Some(FormattedSnippet
{
433 non_formatted_ranges
: formatted
.non_formatted_ranges
,
437 /// A session is a run of rustfmt across a single or multiple inputs.
438 pub struct Session
<'b
, T
: Write
> {
440 pub out
: Option
<&'b
mut T
>,
441 pub(crate) errors
: ReportedErrors
,
442 source_file
: SourceFile
,
443 emitter
: Box
<dyn Emitter
+ 'b
>,
446 impl<'b
, T
: Write
+ 'b
> Session
<'b
, T
> {
447 pub fn new(config
: Config
, mut out
: Option
<&'b
mut T
>) -> Session
<'b
, T
> {
448 let emitter
= create_emitter(&config
);
450 if let Some(ref mut out
) = out
{
451 let _
= emitter
.emit_header(out
);
458 errors
: ReportedErrors
::default(),
459 source_file
: SourceFile
::new(),
463 /// The main entry point for Rustfmt. Formats the given input according to the
464 /// given config. `out` is only necessary if required by the configuration.
465 pub fn format(&mut self, input
: Input
) -> Result
<FormatReport
, ErrorKind
> {
466 self.format_input_inner(input
, false)
469 pub fn override_config
<F
, U
>(&mut self, mut config
: Config
, f
: F
) -> U
471 F
: FnOnce(&mut Session
<'b
, T
>) -> U
,
473 mem
::swap(&mut config
, &mut self.config
);
474 let result
= f(self);
475 mem
::swap(&mut config
, &mut self.config
);
479 pub fn add_operational_error(&mut self) {
480 self.errors
.has_operational_errors
= true;
483 pub fn has_operational_errors(&self) -> bool
{
484 self.errors
.has_operational_errors
487 pub fn has_parsing_errors(&self) -> bool
{
488 self.errors
.has_parsing_errors
491 pub fn has_formatting_errors(&self) -> bool
{
492 self.errors
.has_formatting_errors
495 pub fn has_check_errors(&self) -> bool
{
496 self.errors
.has_check_errors
499 pub fn has_diff(&self) -> bool
{
503 pub fn has_unformatted_code_errors(&self) -> bool
{
504 self.errors
.has_unformatted_code_errors
507 pub fn has_no_errors(&self) -> bool
{
508 !(self.has_operational_errors()
509 || self.has_parsing_errors()
510 || self.has_formatting_errors()
511 || self.has_check_errors()
513 || self.has_unformatted_code_errors()
514 || self.errors
.has_macro_format_failure
)
518 pub(crate) fn create_emitter
<'a
>(config
: &Config
) -> Box
<dyn Emitter
+ 'a
> {
519 match config
.emit_mode() {
520 EmitMode
::Files
if config
.make_backup() => {
521 Box
::new(emitter
::FilesWithBackupEmitter
::default())
523 EmitMode
::Files
=> Box
::new(emitter
::FilesEmitter
::new(
524 config
.print_misformatted_file_names(),
526 EmitMode
::Stdout
| EmitMode
::Coverage
=> {
527 Box
::new(emitter
::StdoutEmitter
::new(config
.verbose()))
529 EmitMode
::Json
=> Box
::new(emitter
::JsonEmitter
::default()),
530 EmitMode
::ModifiedLines
=> Box
::new(emitter
::ModifiedLinesEmitter
::default()),
531 EmitMode
::Checkstyle
=> Box
::new(emitter
::CheckstyleEmitter
::default()),
532 EmitMode
::Diff
=> Box
::new(emitter
::DiffEmitter
::new(config
.clone())),
536 impl<'b
, T
: Write
+ 'b
> Drop
for Session
<'b
, T
> {
538 if let Some(ref mut out
) = self.out
{
539 let _
= self.emitter
.emit_footer(out
);
551 fn file_name(&self) -> FileName
{
553 Input
::File(ref file
) => FileName
::Real(file
.clone()),
554 Input
::Text(..) => FileName
::Stdin
,
558 fn to_directory_ownership(&self) -> Option
<DirectoryOwnership
> {
560 Input
::File(ref file
) => {
561 // If there exists a directory with the same name as an input,
562 // then the input should be parsed as a sub module.
563 let file_stem
= file
.file_stem()?
;
564 if file
.parent()?
.to_path_buf().join(file_stem
).is_dir() {
565 Some(DirectoryOwnership
::Owned
{
566 relative
: file_stem
.to_str().map(symbol
::Ident
::from_str
),
582 fn test_no_panic_on_format_snippet_and_format_code_block() {
583 // `format_snippet()` and `format_code_block()` should not panic
584 // even when we cannot parse the given snippet.
586 assert
!(format_snippet(snippet
, &Config
::default(), false).is_none());
587 assert
!(format_code_block(snippet
, &Config
::default(), false).is_none());
590 fn test_format_inner
<F
>(formatter
: F
, input
: &str, expected
: &str) -> bool
592 F
: Fn(&str, &Config
, bool
) -> Option
<FormattedSnippet
>,
594 let output
= formatter(input
, &Config
::default(), false);
595 output
.is_some() && output
.unwrap().snippet
== expected
599 fn test_format_snippet() {
600 let snippet
= "fn main() { println!(\"hello, world\"); }";
602 let expected
= "fn main() {\n \
603 println!(\"hello, world\");\n\
606 let expected
= "fn main() {\r\n \
607 println!(\"hello, world\");\r\n\
609 assert
!(test_format_inner(format_snippet
, snippet
, expected
));
613 fn test_format_code_block_fail() {
615 let code_block
= "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
616 assert
!(format_code_block(code_block
, &Config
::default(), false).is_none());
620 fn test_format_code_block() {
622 let code_block
= "let x=3;";
623 let expected
= "let x = 3;";
624 assert
!(test_format_inner(format_code_block
, code_block
, expected
));
626 // more complex code block, taken from chains.rs.
628 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
630 chain_indent(context, shape.add_offset(parent_rewrite.len())),
631 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
633 } else if is_block_expr(context, &parent, &parent_rewrite) {
634 match context.config.indent_style() {
635 // Try to put the first child on the same line with parent's last line
636 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
637 // The parent is a block, so align the rest of the chain with the closing
639 IndentStyle::Visual => (parent_shape, false),
643 chain_indent(context, shape.add_offset(parent_rewrite.len())),
649 "let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
651 chain_indent(context, shape.add_offset(parent_rewrite.len())),
652 context.config.indent_style() == IndentStyle::Visual || is_small_parent,
654 } else if is_block_expr(context, &parent, &parent_rewrite) {
655 match context.config.indent_style() {
656 // Try to put the first child on the same line with parent's last line
657 IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
658 // The parent is a block, so align the rest of the chain with the closing
660 IndentStyle::Visual => (parent_shape, false),
664 chain_indent(context, shape.add_offset(parent_rewrite.len())),
668 assert
!(test_format_inner(format_code_block
, code_block
, expected
));