2021-02-16 21:25:41 -06:00
|
|
|
#![feature(rustc_private)]
|
2019-02-09 00:55:17 -06:00
|
|
|
#![deny(rust_2018_idioms)]
|
2019-05-09 13:37:51 -05:00
|
|
|
#![warn(unreachable_pub)]
|
2021-06-29 23:13:34 -05:00
|
|
|
#![recursion_limit = "256"]
|
2021-07-25 22:57:19 -05:00
|
|
|
#![allow(clippy::match_like_matches_macro)]
|
2021-07-25 22:38:16 -05:00
|
|
|
#![allow(unreachable_pub)]
|
2019-02-09 00:55:17 -06:00
|
|
|
|
2021-01-19 12:40:58 -06:00
|
|
|
#[cfg(test)]
|
2018-04-20 04:08:20 -05:00
|
|
|
#[macro_use]
|
|
|
|
extern crate lazy_static;
|
2015-03-07 16:46:35 -06:00
|
|
|
#[macro_use]
|
2023-10-22 20:21:44 -05:00
|
|
|
extern crate tracing;
|
2015-09-03 22:38:12 -05:00
|
|
|
|
2021-02-16 21:25:41 -06:00
|
|
|
// N.B. these crates are loaded from the sysroot, so they need extern crate.
|
|
|
|
extern crate rustc_ast;
|
|
|
|
extern crate rustc_ast_pretty;
|
2021-12-29 20:49:39 -06:00
|
|
|
extern crate rustc_builtin_macros;
|
2021-02-16 21:25:41 -06:00
|
|
|
extern crate rustc_data_structures;
|
|
|
|
extern crate rustc_errors;
|
|
|
|
extern crate rustc_expand;
|
|
|
|
extern crate rustc_parse;
|
|
|
|
extern crate rustc_session;
|
|
|
|
extern crate rustc_span;
|
2022-11-22 18:55:16 -06:00
|
|
|
extern crate thin_vec;
|
2021-02-16 21:25:41 -06:00
|
|
|
|
2022-12-12 13:37:28 -06:00
|
|
|
// Necessary to pull in object code as the rest of the rustc crates are shipped only as rmeta
|
|
|
|
// files.
|
|
|
|
#[allow(unused_extern_crates)]
|
|
|
|
extern crate rustc_driver;
|
|
|
|
|
2018-05-14 01:01:53 -05:00
|
|
|
use std::cell::RefCell;
|
2023-10-22 20:21:44 -05:00
|
|
|
use std::cmp::min;
|
2017-07-13 04:42:14 -05:00
|
|
|
use std::collections::HashMap;
|
|
|
|
use std::fmt;
|
2018-05-20 22:09:17 -05:00
|
|
|
use std::io::{self, Write};
|
2018-07-22 21:52:02 -05:00
|
|
|
use std::mem;
|
2018-10-17 00:21:04 -05:00
|
|
|
use std::panic;
|
2017-12-08 07:16:47 -06:00
|
|
|
use std::path::PathBuf;
|
2016-03-01 16:27:19 -06:00
|
|
|
use std::rc::Rc;
|
2017-07-13 04:42:14 -05:00
|
|
|
|
2020-03-27 22:29:12 -05:00
|
|
|
use rustc_ast::ast;
|
2021-09-08 12:40:32 -05:00
|
|
|
use rustc_span::symbol;
|
2019-12-02 18:20:17 -06:00
|
|
|
use thiserror::Error;
|
2019-02-04 04:30:43 -06:00
|
|
|
|
|
|
|
use crate::comment::LineClasses;
|
2019-06-12 16:59:20 -05:00
|
|
|
use crate::emitter::Emitter;
|
2019-02-04 04:30:43 -06:00
|
|
|
use crate::formatting::{FormatErrorMap, FormattingError, ReportedErrors, SourceFile};
|
2020-06-11 21:11:18 -05:00
|
|
|
use crate::modules::ModuleResolutionError;
|
2021-12-29 20:49:39 -06:00
|
|
|
use crate::parse::parser::DirectoryOwnership;
|
2019-02-04 04:30:43 -06:00
|
|
|
use crate::shape::Indent;
|
2019-02-06 17:05:05 -06:00
|
|
|
use crate::utils::indent_next_line;
|
2016-04-14 18:51:50 -05:00
|
|
|
|
2019-02-04 04:30:43 -06:00
|
|
|
pub use crate::config::{
|
2018-10-23 00:33:36 -05:00
|
|
|
load_config, CliOptions, Color, Config, Edition, EmitMode, FileLines, FileName, NewlineStyle,
|
2019-02-09 07:23:54 -06:00
|
|
|
Range, Verbosity,
|
2018-05-20 19:01:31 -05:00
|
|
|
};
|
2018-04-20 04:08:20 -05:00
|
|
|
|
2019-04-17 07:33:36 -05:00
|
|
|
pub use crate::format_report_formatter::{FormatReportFormatter, FormatReportFormatterBuilder};
|
|
|
|
|
2019-03-01 12:20:57 -06:00
|
|
|
pub use crate::rustfmt_diff::{ModifiedChunk, ModifiedLines};
|
2019-03-01 10:59:38 -06:00
|
|
|
|
2015-06-08 13:23:24 -05:00
|
|
|
#[macro_use]
|
|
|
|
mod utils;
|
2018-02-17 10:06:54 -06:00
|
|
|
|
2018-02-23 07:30:05 -06:00
|
|
|
mod attr;
|
2018-01-29 07:00:07 -06:00
|
|
|
mod chains;
|
2017-11-12 20:26:33 -06:00
|
|
|
mod closures;
|
2018-01-29 07:00:07 -06:00
|
|
|
mod comment;
|
2018-04-20 04:08:20 -05:00
|
|
|
pub(crate) mod config;
|
2019-07-17 09:07:12 -05:00
|
|
|
mod coverage;
|
2019-06-12 16:59:20 -05:00
|
|
|
mod emitter;
|
2015-04-21 04:01:19 -05:00
|
|
|
mod expr;
|
2019-04-17 07:33:36 -05:00
|
|
|
mod format_report_formatter;
|
2018-07-22 19:45:41 -05:00
|
|
|
pub(crate) mod formatting;
|
2019-04-14 05:30:44 -05:00
|
|
|
mod ignore_path;
|
2015-04-21 04:01:19 -05:00
|
|
|
mod imports;
|
2018-01-29 07:00:07 -06:00
|
|
|
mod items;
|
|
|
|
mod lists;
|
2015-09-14 15:53:30 -05:00
|
|
|
mod macros;
|
2018-03-21 08:02:18 -05:00
|
|
|
mod matches;
|
2018-01-29 07:00:07 -06:00
|
|
|
mod missed_spans;
|
2018-04-20 04:08:20 -05:00
|
|
|
pub(crate) mod modules;
|
2018-03-07 00:40:52 -06:00
|
|
|
mod overflow;
|
2018-06-27 19:02:05 -05:00
|
|
|
mod pairs;
|
2021-12-29 20:49:39 -06:00
|
|
|
mod parse;
|
2015-10-17 08:56:53 -05:00
|
|
|
mod patterns;
|
2019-08-18 20:56:32 -05:00
|
|
|
mod release_channel;
|
2018-02-17 10:06:54 -06:00
|
|
|
mod reorder;
|
2018-01-29 07:00:07 -06:00
|
|
|
mod rewrite;
|
2018-04-20 04:08:20 -05:00
|
|
|
pub(crate) mod rustfmt_diff;
|
2018-01-29 07:00:07 -06:00
|
|
|
mod shape;
|
2019-07-16 19:40:33 -05:00
|
|
|
mod skip;
|
2018-08-23 16:14:19 -05:00
|
|
|
pub(crate) mod source_file;
|
|
|
|
pub(crate) mod source_map;
|
2018-01-29 07:00:07 -06:00
|
|
|
mod spanned;
|
2019-06-16 18:53:39 -05:00
|
|
|
mod stmt;
|
2018-01-29 07:00:07 -06:00
|
|
|
mod string;
|
2018-04-20 04:08:20 -05:00
|
|
|
#[cfg(test)]
|
|
|
|
mod test;
|
2018-01-29 07:00:07 -06:00
|
|
|
mod types;
|
2017-07-03 04:54:41 -05:00
|
|
|
mod vertical;
|
2018-04-20 04:08:20 -05:00
|
|
|
pub(crate) mod visitor;
|
2015-03-07 16:46:35 -06:00
|
|
|
|
2018-05-20 22:54:56 -05:00
|
|
|
/// The various errors that can occur during formatting. Note that not all of
|
|
|
|
/// these can currently be propagated to clients.
|
2019-12-02 18:20:17 -06:00
|
|
|
#[derive(Error, Debug)]
|
2015-09-17 13:21:06 -05:00
|
|
|
pub enum ErrorKind {
|
2018-05-20 22:54:56 -05:00
|
|
|
/// Line has exceeded character limit (found, maximum).
|
2019-12-02 18:20:17 -06:00
|
|
|
#[error(
|
|
|
|
"line formatted, but exceeded maximum width \
|
|
|
|
(maximum: {1} (see `max_width` option), found: {0})"
|
2018-04-24 03:10:09 -05:00
|
|
|
)]
|
2017-01-08 20:57:11 -06:00
|
|
|
LineOverflow(usize, usize),
|
2018-05-20 22:54:56 -05:00
|
|
|
/// Line ends in whitespace.
|
2019-12-02 18:20:17 -06:00
|
|
|
#[error("left behind trailing whitespace")]
|
2015-06-08 18:42:29 -05:00
|
|
|
TrailingWhitespace,
|
2018-05-20 22:54:56 -05:00
|
|
|
/// Used deprecated skip attribute.
|
2019-12-02 18:20:17 -06:00
|
|
|
#[error("`rustfmt_skip` is deprecated; use `rustfmt::skip`")]
|
2018-05-14 01:01:53 -05:00
|
|
|
DeprecatedAttr,
|
2019-03-20 11:33:40 -05:00
|
|
|
/// Used a rustfmt:: attribute other than skip or skip::macros.
|
2019-12-02 18:20:17 -06:00
|
|
|
#[error("invalid attribute")]
|
2018-05-14 01:01:53 -05:00
|
|
|
BadAttr,
|
2018-05-20 22:54:56 -05:00
|
|
|
/// An io error during reading or writing.
|
2019-12-02 18:20:17 -06:00
|
|
|
#[error("io error: {0}")]
|
2018-05-18 23:11:30 -05:00
|
|
|
IoError(io::Error),
|
2020-06-11 21:11:18 -05:00
|
|
|
/// Error during module resolution.
|
|
|
|
#[error("{0}")]
|
|
|
|
ModuleResolutionError(#[from] ModuleResolutionError),
|
2018-10-18 17:44:14 -05:00
|
|
|
/// Parse error occurred when parsing the input.
|
2019-12-02 18:20:17 -06:00
|
|
|
#[error("parse error")]
|
2018-06-09 09:25:06 -05:00
|
|
|
ParseError,
|
2018-05-20 22:54:56 -05:00
|
|
|
/// The user mandated a version and the current version of Rustfmt does not
|
|
|
|
/// satisfy that requirement.
|
2019-12-02 18:20:17 -06:00
|
|
|
#[error("version mismatch")]
|
2018-05-20 22:09:17 -05:00
|
|
|
VersionMismatch,
|
2018-07-19 21:42:48 -05:00
|
|
|
/// If we had formatted the given node, then we would have lost a comment.
|
2019-12-02 18:20:17 -06:00
|
|
|
#[error("not formatted because a comment would be lost")]
|
2018-07-19 21:42:48 -05:00
|
|
|
LostComment,
|
2019-04-14 05:30:44 -05:00
|
|
|
/// Invalid glob pattern in `ignore` configuration option.
|
2019-12-02 18:20:17 -06:00
|
|
|
#[error("Invalid glob pattern found in ignore list: {0}")]
|
2019-04-14 05:30:44 -05:00
|
|
|
InvalidGlobPattern(ignore::Error),
|
2018-07-19 21:42:48 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
impl ErrorKind {
|
|
|
|
fn is_comment(&self) -> bool {
|
2021-07-25 22:57:19 -05:00
|
|
|
matches!(self, ErrorKind::LostComment)
|
2018-07-19 21:42:48 -05:00
|
|
|
}
|
2018-05-18 23:11:30 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
impl From<io::Error> for ErrorKind {
|
|
|
|
fn from(e: io::Error) -> ErrorKind {
|
|
|
|
ErrorKind::IoError(e)
|
|
|
|
}
|
2015-06-08 18:42:29 -05:00
|
|
|
}
|
|
|
|
|
2018-10-23 18:24:56 -05:00
|
|
|
/// Result of formatting a snippet of code along with ranges of lines that didn't get formatted,
|
|
|
|
/// i.e., that got returned as they were originally.
|
|
|
|
#[derive(Debug)]
|
|
|
|
struct FormattedSnippet {
|
|
|
|
snippet: String,
|
|
|
|
non_formatted_ranges: Vec<(usize, usize)>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl FormattedSnippet {
|
|
|
|
/// In case the snippet needed to be wrapped in a function, this shifts down the ranges of
|
|
|
|
/// non-formatted code.
|
|
|
|
fn unwrap_code_block(&mut self) {
|
|
|
|
self.non_formatted_ranges
|
|
|
|
.iter_mut()
|
|
|
|
.for_each(|(low, high)| {
|
|
|
|
*low -= 1;
|
|
|
|
*high -= 1;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2019-02-18 20:56:42 -06:00
|
|
|
/// Returns `true` if the line n did not get formatted.
|
2018-10-23 18:24:56 -05:00
|
|
|
fn is_line_non_formatted(&self, n: usize) -> bool {
|
|
|
|
self.non_formatted_ranges
|
|
|
|
.iter()
|
|
|
|
.any(|(low, high)| *low <= n && n <= *high)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-05-20 22:54:56 -05:00
|
|
|
/// Reports on any issues that occurred during a run of Rustfmt.
|
|
|
|
///
|
2019-04-17 07:33:36 -05:00
|
|
|
/// Can be reported to the user using the `Display` impl on [`FormatReportFormatter`].
|
2018-05-14 01:01:53 -05:00
|
|
|
#[derive(Clone)]
|
2018-05-20 22:09:17 -05:00
|
|
|
pub struct FormatReport {
|
2015-09-17 13:21:06 -05:00
|
|
|
// Maps stringified file paths to their associated formatting errors.
|
2018-05-17 22:30:32 -05:00
|
|
|
internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
|
2018-10-23 18:24:56 -05:00
|
|
|
non_formatted_ranges: Vec<(usize, usize)>,
|
2018-05-17 22:30:32 -05:00
|
|
|
}
|
|
|
|
|
2015-09-17 13:21:06 -05:00
|
|
|
impl FormatReport {
|
2016-04-14 18:51:50 -05:00
|
|
|
fn new() -> FormatReport {
|
2017-07-03 04:54:26 -05:00
|
|
|
FormatReport {
|
2018-05-17 22:30:32 -05:00
|
|
|
internal: Rc::new(RefCell::new((HashMap::new(), ReportedErrors::default()))),
|
2018-10-23 18:24:56 -05:00
|
|
|
non_formatted_ranges: Vec::new(),
|
2017-07-03 04:54:26 -05:00
|
|
|
}
|
2016-04-14 18:51:50 -05:00
|
|
|
}
|
|
|
|
|
2018-10-23 18:24:56 -05:00
|
|
|
fn add_non_formatted_ranges(&mut self, mut ranges: Vec<(usize, usize)>) {
|
|
|
|
self.non_formatted_ranges.append(&mut ranges);
|
|
|
|
}
|
|
|
|
|
2018-05-14 01:01:53 -05:00
|
|
|
fn append(&self, f: FileName, mut v: Vec<FormattingError>) {
|
2018-05-17 22:30:32 -05:00
|
|
|
self.track_errors(&v);
|
|
|
|
self.internal
|
2018-05-14 01:01:53 -05:00
|
|
|
.borrow_mut()
|
2018-05-17 22:30:32 -05:00
|
|
|
.0
|
2018-05-14 01:01:53 -05:00
|
|
|
.entry(f)
|
|
|
|
.and_modify(|fe| fe.append(&mut v))
|
|
|
|
.or_insert(v);
|
|
|
|
}
|
|
|
|
|
2018-05-17 22:30:32 -05:00
|
|
|
fn track_errors(&self, new_errors: &[FormattingError]) {
|
|
|
|
let errs = &mut self.internal.borrow_mut().1;
|
2018-07-24 04:41:49 -05:00
|
|
|
if !new_errors.is_empty() {
|
|
|
|
errs.has_formatting_errors = true;
|
|
|
|
}
|
2021-02-16 08:35:47 -06:00
|
|
|
if errs.has_operational_errors && errs.has_check_errors && errs.has_unformatted_code_errors
|
|
|
|
{
|
2018-05-17 22:30:32 -05:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
for err in new_errors {
|
|
|
|
match err.kind {
|
2021-02-16 08:35:47 -06:00
|
|
|
ErrorKind::LineOverflow(..) => {
|
2018-05-17 22:30:32 -05:00
|
|
|
errs.has_operational_errors = true;
|
|
|
|
}
|
2021-02-16 08:35:47 -06:00
|
|
|
ErrorKind::TrailingWhitespace => {
|
|
|
|
errs.has_operational_errors = true;
|
|
|
|
errs.has_unformatted_code_errors = true;
|
|
|
|
}
|
|
|
|
ErrorKind::LostComment => {
|
|
|
|
errs.has_unformatted_code_errors = true;
|
|
|
|
}
|
2022-06-12 22:03:05 -05:00
|
|
|
ErrorKind::DeprecatedAttr | ErrorKind::BadAttr | ErrorKind::VersionMismatch => {
|
2018-05-17 22:30:32 -05:00
|
|
|
errs.has_check_errors = true;
|
|
|
|
}
|
2018-05-18 23:11:30 -05:00
|
|
|
_ => {}
|
2018-05-17 22:30:32 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-24 04:41:49 -05:00
|
|
|
fn add_diff(&mut self) {
|
|
|
|
self.internal.borrow_mut().1.has_diff = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
fn add_macro_format_failure(&mut self) {
|
|
|
|
self.internal.borrow_mut().1.has_macro_format_failure = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
fn add_parsing_error(&mut self) {
|
|
|
|
self.internal.borrow_mut().1.has_parsing_errors = true;
|
|
|
|
}
|
|
|
|
|
2018-04-20 04:08:20 -05:00
|
|
|
fn warning_count(&self) -> usize {
|
2018-05-17 22:30:32 -05:00
|
|
|
self.internal
|
2018-05-14 01:01:53 -05:00
|
|
|
.borrow()
|
2018-05-17 22:30:32 -05:00
|
|
|
.0
|
2017-03-06 14:40:08 -06:00
|
|
|
.iter()
|
|
|
|
.map(|(_, errors)| errors.len())
|
2018-01-25 23:53:28 -06:00
|
|
|
.sum()
|
2015-09-17 13:21:06 -05:00
|
|
|
}
|
2016-04-14 18:51:50 -05:00
|
|
|
|
2018-05-20 22:54:56 -05:00
|
|
|
/// Whether any warnings or errors are present in the report.
|
2018-05-20 22:09:17 -05:00
|
|
|
pub fn has_warnings(&self) -> bool {
|
2018-07-24 04:41:49 -05:00
|
|
|
self.internal.borrow().1.has_formatting_errors
|
2016-04-14 18:51:50 -05:00
|
|
|
}
|
2017-08-15 02:54:18 -05:00
|
|
|
|
2018-05-20 22:54:56 -05:00
|
|
|
/// Print the report to a terminal using colours and potentially other
|
|
|
|
/// fancy output.
|
2019-04-17 07:33:36 -05:00
|
|
|
#[deprecated(note = "Use FormatReportFormatter with colors enabled instead")]
|
2018-05-20 22:09:17 -05:00
|
|
|
pub fn fancy_print(
|
2017-08-15 02:54:18 -05:00
|
|
|
&self,
|
2019-02-09 01:14:30 -06:00
|
|
|
mut t: Box<dyn term::Terminal<Output = io::Stderr>>,
|
2017-08-15 02:54:18 -05:00
|
|
|
) -> Result<(), term::Error> {
|
2019-04-17 07:33:36 -05:00
|
|
|
writeln!(
|
|
|
|
t,
|
|
|
|
"{}",
|
2021-11-07 20:37:34 -06:00
|
|
|
FormatReportFormatterBuilder::new(self)
|
2019-04-17 07:33:36 -05:00
|
|
|
.enable_colors(true)
|
|
|
|
.build()
|
|
|
|
)?;
|
2017-08-15 02:54:18 -05:00
|
|
|
Ok(())
|
|
|
|
}
|
2015-09-17 13:21:06 -05:00
|
|
|
}
|
|
|
|
|
2020-11-05 19:30:56 -06:00
|
|
|
/// Deprecated - Use FormatReportFormatter instead
|
|
|
|
// https://github.com/rust-lang/rust/issues/78625
|
|
|
|
// https://github.com/rust-lang/rust/issues/39935
|
2015-06-08 18:42:29 -05:00
|
|
|
impl fmt::Display for FormatReport {
|
|
|
|
// Prints all the formatting errors.
|
2019-02-09 01:14:30 -06:00
|
|
|
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
2021-11-07 20:37:34 -06:00
|
|
|
write!(fmt, "{}", FormatReportFormatterBuilder::new(self).build())?;
|
2015-06-08 18:42:29 -05:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-24 08:40:53 -06:00
|
|
|
/// Format the given snippet. The snippet is expected to be *complete* code.
|
|
|
|
/// When we cannot parse the given snippet, this function returns `None`.
|
2020-11-10 20:07:42 -06:00
|
|
|
fn format_snippet(snippet: &str, config: &Config, is_macro_def: bool) -> Option<FormattedSnippet> {
|
2017-12-24 08:40:53 -06:00
|
|
|
let mut config = config.clone();
|
2018-10-23 18:24:56 -05:00
|
|
|
panic::catch_unwind(|| {
|
2018-10-17 00:21:04 -05:00
|
|
|
let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
|
|
|
|
config.set().emit_mode(config::EmitMode::Stdout);
|
|
|
|
config.set().verbose(Verbosity::Quiet);
|
|
|
|
config.set().hide_parse_errors(true);
|
2021-02-16 08:35:47 -06:00
|
|
|
if is_macro_def {
|
|
|
|
config.set().error_on_unformatted(true);
|
|
|
|
}
|
2018-10-23 18:24:56 -05:00
|
|
|
|
|
|
|
let (formatting_error, result) = {
|
2018-10-17 00:21:04 -05:00
|
|
|
let input = Input::Text(snippet.into());
|
|
|
|
let mut session = Session::new(config, Some(&mut out));
|
2020-11-10 20:07:42 -06:00
|
|
|
let result = session.format_input_inner(input, is_macro_def);
|
2018-10-23 18:24:56 -05:00
|
|
|
(
|
|
|
|
session.errors.has_macro_format_failure
|
|
|
|
|| session.out.as_ref().unwrap().is_empty() && !snippet.is_empty()
|
2021-02-16 08:35:47 -06:00
|
|
|
|| result.is_err()
|
|
|
|
|| (is_macro_def && session.has_unformatted_code_errors()),
|
2018-10-23 18:24:56 -05:00
|
|
|
result,
|
|
|
|
)
|
2018-10-17 00:21:04 -05:00
|
|
|
};
|
|
|
|
if formatting_error {
|
|
|
|
None
|
|
|
|
} else {
|
2018-10-23 18:24:56 -05:00
|
|
|
String::from_utf8(out).ok().map(|snippet| FormattedSnippet {
|
|
|
|
snippet,
|
|
|
|
non_formatted_ranges: result.unwrap().non_formatted_ranges,
|
|
|
|
})
|
2018-07-22 21:52:02 -05:00
|
|
|
}
|
2018-10-17 00:21:04 -05:00
|
|
|
})
|
2018-10-23 18:24:56 -05:00
|
|
|
// Discard panics encountered while formatting the snippet
|
|
|
|
// The ? operator is needed to remove the extra Option
|
|
|
|
.ok()?
|
2017-12-24 08:40:53 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Format the given code block. Mainly targeted for code block in comment.
|
2019-02-18 20:56:42 -06:00
|
|
|
/// The code block may be incomplete (i.e., parser may be unable to parse it).
|
2017-12-24 08:40:53 -06:00
|
|
|
/// To avoid panic in parser, we wrap the code block with a dummy function.
|
2019-02-18 20:56:42 -06:00
|
|
|
/// The returned code block does **not** end with newline.
|
2020-11-10 20:07:42 -06:00
|
|
|
fn format_code_block(
|
|
|
|
code_snippet: &str,
|
|
|
|
config: &Config,
|
|
|
|
is_macro_def: bool,
|
|
|
|
) -> Option<FormattedSnippet> {
|
2018-07-22 19:45:41 -05:00
|
|
|
const FN_MAIN_PREFIX: &str = "fn main() {\n";
|
|
|
|
|
|
|
|
fn enclose_in_main_block(s: &str, config: &Config) -> String {
|
|
|
|
let indent = Indent::from_width(config, config.tab_spaces());
|
|
|
|
let mut result = String::with_capacity(s.len() * 2);
|
|
|
|
result.push_str(FN_MAIN_PREFIX);
|
|
|
|
let mut need_indent = true;
|
|
|
|
for (kind, line) in LineClasses::new(s) {
|
|
|
|
if need_indent {
|
|
|
|
result.push_str(&indent.to_string(config));
|
|
|
|
}
|
|
|
|
result.push_str(&line);
|
|
|
|
result.push('\n');
|
2019-02-06 17:05:05 -06:00
|
|
|
need_indent = indent_next_line(kind, &line, config);
|
2018-07-22 19:45:41 -05:00
|
|
|
}
|
|
|
|
result.push('}');
|
|
|
|
result
|
|
|
|
}
|
|
|
|
|
2017-12-24 08:40:53 -06:00
|
|
|
// Wrap the given code block with `fn main()` if it does not have one.
|
2018-03-09 02:10:20 -06:00
|
|
|
let snippet = enclose_in_main_block(code_snippet, config);
|
2018-02-13 14:10:43 -06:00
|
|
|
let mut result = String::with_capacity(snippet.len());
|
|
|
|
let mut is_first = true;
|
2017-12-24 08:40:53 -06:00
|
|
|
|
2018-06-13 07:54:06 -05:00
|
|
|
// While formatting the code, ignore the config's newline style setting and always use "\n"
|
2019-02-18 20:56:42 -06:00
|
|
|
// instead of "\r\n" for the newline characters. This is ok because the output here is
|
2018-06-13 07:54:06 -05:00
|
|
|
// not directly outputted by rustfmt command, but used by the comment formatter's input.
|
2018-10-18 17:44:14 -05:00
|
|
|
// We have output-file-wide "\n" ==> "\r\n" conversion process after here if it's necessary.
|
2018-06-13 07:54:06 -05:00
|
|
|
let mut config_with_unix_newline = config.clone();
|
|
|
|
config_with_unix_newline
|
|
|
|
.set()
|
|
|
|
.newline_style(NewlineStyle::Unix);
|
2020-11-10 20:07:42 -06:00
|
|
|
let mut formatted = format_snippet(&snippet, &config_with_unix_newline, is_macro_def)?;
|
2018-10-23 18:24:56 -05:00
|
|
|
// Remove wrapping main block
|
|
|
|
formatted.unwrap_code_block();
|
2018-06-13 07:54:06 -05:00
|
|
|
|
2017-12-24 08:40:53 -06:00
|
|
|
// Trim "fn main() {" on the first line and "}" on the last line,
|
|
|
|
// then unindent the whole code block.
|
2018-10-23 18:24:56 -05:00
|
|
|
let block_len = formatted
|
|
|
|
.snippet
|
|
|
|
.rfind('}')
|
2019-04-11 06:48:13 -05:00
|
|
|
.unwrap_or_else(|| formatted.snippet.len());
|
2023-10-22 20:21:44 -05:00
|
|
|
|
|
|
|
// It's possible that `block_len < FN_MAIN_PREFIX.len()`. This can happen if the code block was
|
|
|
|
// formatted into the empty string, leading to the enclosing `fn main() {\n}` being formatted
|
|
|
|
// into `fn main() {}`. In this case no unindentation is done.
|
|
|
|
let block_start = min(FN_MAIN_PREFIX.len(), block_len);
|
|
|
|
|
2018-04-02 09:10:37 -05:00
|
|
|
let mut is_indented = true;
|
2020-05-10 06:54:46 -05:00
|
|
|
let indent_str = Indent::from_width(config, config.tab_spaces()).to_string(config);
|
2023-10-22 20:21:44 -05:00
|
|
|
for (kind, ref line) in LineClasses::new(&formatted.snippet[block_start..block_len]) {
|
2018-02-13 14:10:43 -06:00
|
|
|
if !is_first {
|
|
|
|
result.push('\n');
|
|
|
|
} else {
|
|
|
|
is_first = false;
|
|
|
|
}
|
2018-04-02 09:10:37 -05:00
|
|
|
let trimmed_line = if !is_indented {
|
|
|
|
line
|
|
|
|
} else if line.len() > config.max_width() {
|
2018-02-13 14:10:43 -06:00
|
|
|
// If there are lines that are larger than max width, we cannot tell
|
|
|
|
// whether we have succeeded but have some comments or strings that
|
|
|
|
// are too long, or we have failed to format code block. We will be
|
|
|
|
// conservative and just return `None` in this case.
|
|
|
|
return None;
|
2020-05-10 06:54:46 -05:00
|
|
|
} else if line.len() > indent_str.len() {
|
2018-02-13 14:10:43 -06:00
|
|
|
// Make sure that the line has leading whitespaces.
|
|
|
|
if line.starts_with(indent_str.as_ref()) {
|
|
|
|
let offset = if config.hard_tabs() {
|
|
|
|
1
|
2017-12-24 08:40:53 -06:00
|
|
|
} else {
|
2018-02-13 14:10:43 -06:00
|
|
|
config.tab_spaces()
|
|
|
|
};
|
|
|
|
&line[offset..]
|
|
|
|
} else {
|
|
|
|
line
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
line
|
|
|
|
};
|
|
|
|
result.push_str(trimmed_line);
|
2019-02-06 17:05:05 -06:00
|
|
|
is_indented = indent_next_line(kind, line, config);
|
2018-02-13 14:10:43 -06:00
|
|
|
}
|
2018-10-23 18:24:56 -05:00
|
|
|
Some(FormattedSnippet {
|
|
|
|
snippet: result,
|
|
|
|
non_formatted_ranges: formatted.non_formatted_ranges,
|
|
|
|
})
|
2017-12-24 08:40:53 -06:00
|
|
|
}
|
|
|
|
|
2018-07-22 21:52:02 -05:00
|
|
|
/// A session is a run of rustfmt across a single or multiple inputs.
|
2019-02-09 01:14:30 -06:00
|
|
|
pub struct Session<'b, T: Write> {
|
2018-07-22 21:52:02 -05:00
|
|
|
pub config: Config,
|
|
|
|
pub out: Option<&'b mut T>,
|
2018-07-24 04:41:49 -05:00
|
|
|
pub(crate) errors: ReportedErrors,
|
2018-08-23 16:10:46 -05:00
|
|
|
source_file: SourceFile,
|
2019-06-12 16:59:20 -05:00
|
|
|
emitter: Box<dyn Emitter + 'b>,
|
2018-05-20 22:09:17 -05:00
|
|
|
}
|
|
|
|
|
2018-07-22 21:52:02 -05:00
|
|
|
impl<'b, T: Write + 'b> Session<'b, T> {
|
2019-06-12 16:59:20 -05:00
|
|
|
pub fn new(config: Config, mut out: Option<&'b mut T>) -> Session<'b, T> {
|
|
|
|
let emitter = create_emitter(&config);
|
|
|
|
|
|
|
|
if let Some(ref mut out) = out {
|
|
|
|
let _ = emitter.emit_header(out);
|
2018-07-22 21:52:02 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
Session {
|
|
|
|
config,
|
|
|
|
out,
|
2019-06-12 16:59:20 -05:00
|
|
|
emitter,
|
2018-07-24 04:41:49 -05:00
|
|
|
errors: ReportedErrors::default(),
|
2018-08-23 16:10:46 -05:00
|
|
|
source_file: SourceFile::new(),
|
2018-07-22 21:52:02 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// The main entry point for Rustfmt. Formats the given input according to the
|
|
|
|
/// given config. `out` is only necessary if required by the configuration.
|
|
|
|
pub fn format(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
|
2020-11-10 20:07:42 -06:00
|
|
|
self.format_input_inner(input, false)
|
2018-05-20 22:09:17 -05:00
|
|
|
}
|
|
|
|
|
2018-07-22 21:52:02 -05:00
|
|
|
pub fn override_config<F, U>(&mut self, mut config: Config, f: F) -> U
|
|
|
|
where
|
|
|
|
F: FnOnce(&mut Session<'b, T>) -> U,
|
|
|
|
{
|
|
|
|
mem::swap(&mut config, &mut self.config);
|
|
|
|
let result = f(self);
|
|
|
|
mem::swap(&mut config, &mut self.config);
|
|
|
|
result
|
|
|
|
}
|
2018-07-24 04:41:49 -05:00
|
|
|
|
|
|
|
pub fn add_operational_error(&mut self) {
|
|
|
|
self.errors.has_operational_errors = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn has_operational_errors(&self) -> bool {
|
|
|
|
self.errors.has_operational_errors
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn has_parsing_errors(&self) -> bool {
|
|
|
|
self.errors.has_parsing_errors
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn has_formatting_errors(&self) -> bool {
|
|
|
|
self.errors.has_formatting_errors
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn has_check_errors(&self) -> bool {
|
|
|
|
self.errors.has_check_errors
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn has_diff(&self) -> bool {
|
|
|
|
self.errors.has_diff
|
|
|
|
}
|
|
|
|
|
2021-02-16 08:35:47 -06:00
|
|
|
pub fn has_unformatted_code_errors(&self) -> bool {
|
|
|
|
self.errors.has_unformatted_code_errors
|
|
|
|
}
|
|
|
|
|
2018-07-24 04:41:49 -05:00
|
|
|
pub fn has_no_errors(&self) -> bool {
|
|
|
|
!(self.has_operational_errors()
|
|
|
|
|| self.has_parsing_errors()
|
|
|
|
|| self.has_formatting_errors()
|
|
|
|
|| self.has_check_errors()
|
2021-02-16 08:35:47 -06:00
|
|
|
|| self.has_diff()
|
|
|
|
|| self.has_unformatted_code_errors()
|
|
|
|
|| self.errors.has_macro_format_failure)
|
2018-07-24 04:41:49 -05:00
|
|
|
}
|
2018-07-22 21:52:02 -05:00
|
|
|
}
|
|
|
|
|
2019-06-12 16:59:20 -05:00
|
|
|
pub(crate) fn create_emitter<'a>(config: &Config) -> Box<dyn Emitter + 'a> {
|
|
|
|
match config.emit_mode() {
|
|
|
|
EmitMode::Files if config.make_backup() => {
|
|
|
|
Box::new(emitter::FilesWithBackupEmitter::default())
|
|
|
|
}
|
2019-08-18 21:04:40 -05:00
|
|
|
EmitMode::Files => Box::new(emitter::FilesEmitter::new(
|
|
|
|
config.print_misformatted_file_names(),
|
|
|
|
)),
|
2019-06-12 16:59:20 -05:00
|
|
|
EmitMode::Stdout | EmitMode::Coverage => {
|
|
|
|
Box::new(emitter::StdoutEmitter::new(config.verbose()))
|
|
|
|
}
|
2019-08-15 21:14:53 -05:00
|
|
|
EmitMode::Json => Box::new(emitter::JsonEmitter::default()),
|
2019-06-12 16:59:20 -05:00
|
|
|
EmitMode::ModifiedLines => Box::new(emitter::ModifiedLinesEmitter::default()),
|
|
|
|
EmitMode::Checkstyle => Box::new(emitter::CheckstyleEmitter::default()),
|
|
|
|
EmitMode::Diff => Box::new(emitter::DiffEmitter::new(config.clone())),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-22 21:52:02 -05:00
|
|
|
impl<'b, T: Write + 'b> Drop for Session<'b, T> {
|
|
|
|
fn drop(&mut self) {
|
2019-06-12 16:59:20 -05:00
|
|
|
if let Some(ref mut out) = self.out {
|
|
|
|
let _ = self.emitter.emit_footer(out);
|
2018-07-22 21:52:02 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub enum Input {
|
|
|
|
File(PathBuf),
|
|
|
|
Text(String),
|
2018-03-15 04:55:52 -05:00
|
|
|
}
|
|
|
|
|
2018-07-23 03:01:45 -05:00
|
|
|
impl Input {
|
2018-07-23 21:25:17 -05:00
|
|
|
fn file_name(&self) -> FileName {
|
|
|
|
match *self {
|
|
|
|
Input::File(ref file) => FileName::Real(file.clone()),
|
|
|
|
Input::Text(..) => FileName::Stdin,
|
|
|
|
}
|
|
|
|
}
|
2019-03-16 22:25:59 -05:00
|
|
|
|
|
|
|
fn to_directory_ownership(&self) -> Option<DirectoryOwnership> {
|
|
|
|
match self {
|
|
|
|
Input::File(ref file) => {
|
|
|
|
// If there exists a directory with the same name as an input,
|
|
|
|
// then the input should be parsed as a sub module.
|
|
|
|
let file_stem = file.file_stem()?;
|
|
|
|
if file.parent()?.to_path_buf().join(file_stem).is_dir() {
|
|
|
|
Some(DirectoryOwnership::Owned {
|
2020-05-19 03:31:28 -05:00
|
|
|
relative: file_stem.to_str().map(symbol::Ident::from_str),
|
2019-03-16 22:25:59 -05:00
|
|
|
})
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
_ => None,
|
|
|
|
}
|
|
|
|
}
|
2018-07-23 03:01:45 -05:00
|
|
|
}
|
|
|
|
|
2017-12-24 08:40:53 -06:00
|
|
|
#[cfg(test)]
|
2018-04-20 04:08:20 -05:00
|
|
|
mod unit_tests {
|
2018-07-22 19:45:41 -05:00
|
|
|
use super::*;
|
2017-12-24 08:40:53 -06:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_no_panic_on_format_snippet_and_format_code_block() {
|
|
|
|
// `format_snippet()` and `format_code_block()` should not panic
|
|
|
|
// even when we cannot parse the given snippet.
|
|
|
|
let snippet = "let";
|
2020-11-10 20:07:42 -06:00
|
|
|
assert!(format_snippet(snippet, &Config::default(), false).is_none());
|
|
|
|
assert!(format_code_block(snippet, &Config::default(), false).is_none());
|
2017-12-24 08:40:53 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
fn test_format_inner<F>(formatter: F, input: &str, expected: &str) -> bool
|
|
|
|
where
|
2020-11-10 20:07:42 -06:00
|
|
|
F: Fn(&str, &Config, bool) -> Option<FormattedSnippet>,
|
2017-12-24 08:40:53 -06:00
|
|
|
{
|
2020-11-10 20:07:42 -06:00
|
|
|
let output = formatter(input, &Config::default(), false);
|
2018-10-23 18:24:56 -05:00
|
|
|
output.is_some() && output.unwrap().snippet == expected
|
2017-12-24 08:40:53 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_format_snippet() {
|
|
|
|
let snippet = "fn main() { println!(\"hello, world\"); }";
|
2018-07-02 16:43:54 -05:00
|
|
|
#[cfg(not(windows))]
|
2017-12-24 08:40:53 -06:00
|
|
|
let expected = "fn main() {\n \
|
|
|
|
println!(\"hello, world\");\n\
|
|
|
|
}\n";
|
2018-07-02 16:43:54 -05:00
|
|
|
#[cfg(windows)]
|
|
|
|
let expected = "fn main() {\r\n \
|
|
|
|
println!(\"hello, world\");\r\n\
|
|
|
|
}\r\n";
|
2017-12-24 08:40:53 -06:00
|
|
|
assert!(test_format_inner(format_snippet, snippet, expected));
|
|
|
|
}
|
|
|
|
|
2018-02-13 14:10:43 -06:00
|
|
|
#[test]
|
|
|
|
fn test_format_code_block_fail() {
|
2018-05-13 23:25:10 -05:00
|
|
|
#[rustfmt::skip]
|
2018-02-13 14:10:43 -06:00
|
|
|
let code_block = "this_line_is_100_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(x, y, z);";
|
2020-11-10 20:07:42 -06:00
|
|
|
assert!(format_code_block(code_block, &Config::default(), false).is_none());
|
2018-02-13 14:10:43 -06:00
|
|
|
}
|
|
|
|
|
2017-12-24 08:40:53 -06:00
|
|
|
#[test]
|
|
|
|
fn test_format_code_block() {
|
|
|
|
// simple code block
|
|
|
|
let code_block = "let x=3;";
|
|
|
|
let expected = "let x = 3;";
|
|
|
|
assert!(test_format_inner(format_code_block, code_block, expected));
|
|
|
|
|
|
|
|
// more complex code block, taken from chains.rs.
|
|
|
|
let code_block =
|
|
|
|
"let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
|
|
|
|
(
|
|
|
|
chain_indent(context, shape.add_offset(parent_rewrite.len())),
|
|
|
|
context.config.indent_style() == IndentStyle::Visual || is_small_parent,
|
|
|
|
)
|
|
|
|
} else if is_block_expr(context, &parent, &parent_rewrite) {
|
|
|
|
match context.config.indent_style() {
|
|
|
|
// Try to put the first child on the same line with parent's last line
|
|
|
|
IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
|
|
|
|
// The parent is a block, so align the rest of the chain with the closing
|
|
|
|
// brace.
|
|
|
|
IndentStyle::Visual => (parent_shape, false),
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
(
|
|
|
|
chain_indent(context, shape.add_offset(parent_rewrite.len())),
|
|
|
|
false,
|
|
|
|
)
|
|
|
|
};
|
|
|
|
";
|
|
|
|
let expected =
|
|
|
|
"let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
|
|
|
|
(
|
|
|
|
chain_indent(context, shape.add_offset(parent_rewrite.len())),
|
|
|
|
context.config.indent_style() == IndentStyle::Visual || is_small_parent,
|
|
|
|
)
|
|
|
|
} else if is_block_expr(context, &parent, &parent_rewrite) {
|
|
|
|
match context.config.indent_style() {
|
|
|
|
// Try to put the first child on the same line with parent's last line
|
|
|
|
IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
|
|
|
|
// The parent is a block, so align the rest of the chain with the closing
|
|
|
|
// brace.
|
|
|
|
IndentStyle::Visual => (parent_shape, false),
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
(
|
|
|
|
chain_indent(context, shape.add_offset(parent_rewrite.len())),
|
|
|
|
false,
|
|
|
|
)
|
|
|
|
};";
|
|
|
|
assert!(test_format_inner(format_code_block, code_block, expected));
|
|
|
|
}
|
|
|
|
}
|