Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parallel formatting to increase speed #6095

Open
wants to merge 23 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Pass printer down the stack
  • Loading branch information
MarcusGrass committed Feb 26, 2024
commit 75151ccbd5315d36690df64920d90df22f582b71
6 changes: 4 additions & 2 deletions src/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ fn format_derive(
.tactic(tactic)
.trailing_separator(trailing_separator)
.ends_with_newline(false);
let item_str = write_list(&all_items, &fmt)?;
let item_str = write_list(&all_items, &fmt, context.printer)?;

debug!("item_str: '{}'", item_str);

Expand Down Expand Up @@ -235,6 +235,7 @@ fn rewrite_initial_doc_comments(
&snippet,
shape.comment(context.config),
context.config,
context.printer,
)?),
));
}
Expand Down Expand Up @@ -318,7 +319,7 @@ impl Rewrite for ast::Attribute {
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
let snippet = context.snippet(self.span);
if self.is_doc_comment() {
rewrite_doc_comment(snippet, shape.comment(context.config), context.config)
rewrite_doc_comment(snippet, shape.comment(context.config), context.config, context.printer)
} else {
let should_skip = self
.ident()
Expand Down Expand Up @@ -347,6 +348,7 @@ impl Rewrite for ast::Attribute {
&doc_comment,
shape.comment(context.config),
context.config,
context.printer,
);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ fn format(
}
}

let num_cpus = 16;
let num_cpus = 32;
let (send, recv) = std::sync::mpsc::channel();

let mut exit_code = 0;
Expand Down
2 changes: 1 addition & 1 deletion src/chains.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ impl Rewrite for ChainItem {
),
ChainItemKind::Await => ".await".to_owned(),
ChainItemKind::Comment(ref comment, _) => {
rewrite_comment(comment, false, shape, context.config)?
rewrite_comment(comment, false, shape, context.config, context.printer)?
}
};
Some(format!("{rewrite}{}", "?".repeat(self.tries)))
Expand Down
2 changes: 1 addition & 1 deletion src/closures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,7 @@ fn rewrite_closure_fn_decl(
let fmt = ListFormatting::new(param_shape, context.config)
.tactic(tactic)
.preserve_newline(true);
let list_str = write_list(&item_vec, &fmt)?;
let list_str = write_list(&item_vec, &fmt, context.printer)?;
let mut prefix = format!("{binder}{const_}{immovable}{coro}{mover}|{list_str}|");

if !ret_str.is_empty() {
Expand Down
19 changes: 13 additions & 6 deletions src/comment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use crate::utils::{
trimmed_last_line_width, unicode_str_width,
};
use crate::{ErrorKind, FormattingError};
use crate::print::Printer;

lazy_static! {
/// A regex matching reference doc links.
Expand Down Expand Up @@ -248,17 +249,18 @@ pub(crate) fn combine_strs_with_missing_comments(
Some(result)
}

pub(crate) fn rewrite_doc_comment(orig: &str, shape: Shape, config: &Config) -> Option<String> {
identify_comment(orig, false, shape, config, true)
pub(crate) fn rewrite_doc_comment(orig: &str, shape: Shape, config: &Config, printer: &Printer) -> Option<String> {
identify_comment(orig, false, shape, config, true, printer)
}

pub(crate) fn rewrite_comment(
orig: &str,
block_style: bool,
shape: Shape,
config: &Config,
printer: &Printer,
) -> Option<String> {
identify_comment(orig, block_style, shape, config, false)
identify_comment(orig, block_style, shape, config, false, printer)
}

fn identify_comment(
Expand All @@ -267,6 +269,7 @@ fn identify_comment(
shape: Shape,
config: &Config,
is_doc_comment: bool,
printer: &Printer,
) -> Option<String> {
let style = comment_style(orig, false);

Expand Down Expand Up @@ -377,6 +380,7 @@ fn identify_comment(
shape,
config,
is_doc_comment || style.is_doc_comment(),
printer,
)?
};
if rest.is_empty() {
Expand All @@ -388,6 +392,7 @@ fn identify_comment(
shape,
config,
is_doc_comment,
printer,
)
.map(|rest_str| {
format!(
Expand Down Expand Up @@ -725,6 +730,7 @@ impl<'a> CommentRewrite<'a> {
line: &'a str,
has_leading_whitespace: bool,
is_doc_comment: bool,
printer: &Printer,
) -> bool {
let num_newlines = count_newlines(orig);
let is_last = i == num_newlines;
Expand Down Expand Up @@ -776,7 +782,7 @@ impl<'a> CommentRewrite<'a> {
.min(config.max_width());
config.set().max_width(comment_max_width);
if let Some(s) =
crate::format_code_block(&self.code_block_buffer, &config, false)
crate::format_code_block(&self.code_block_buffer, &config, false, printer)
{
trim_custom_comment_prefix(&s.snippet)
} else {
Expand Down Expand Up @@ -912,6 +918,7 @@ fn rewrite_comment_inner(
shape: Shape,
config: &Config,
is_doc_comment: bool,
printer: &Printer,
) -> Option<String> {
let mut rewriter = CommentRewrite::new(orig, block_style, shape, config);

Expand Down Expand Up @@ -941,7 +948,7 @@ fn rewrite_comment_inner(
});

for (i, (line, has_leading_whitespace)) in lines.enumerate() {
if rewriter.handle_line(orig, i, line, has_leading_whitespace, is_doc_comment) {
if rewriter.handle_line(orig, i, line, has_leading_whitespace, is_doc_comment, printer) {
break;
}
}
Expand Down Expand Up @@ -1008,7 +1015,7 @@ pub(crate) fn rewrite_missing_comment(
// check the span starts with a comment
let pos = trimmed_snippet.find('/');
if !trimmed_snippet.is_empty() && pos.is_some() {
rewrite_comment(trimmed_snippet, false, shape, context.config)
rewrite_comment(trimmed_snippet, false, shape, context.config, context.printer)
} else {
Some(String::new())
}
Expand Down
5 changes: 3 additions & 2 deletions src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -496,6 +496,7 @@ fn block_prefix(context: &RewriteContext<'_>, block: &ast::Block, shape: Shape)
true,
Shape::legacy(budget, shape.indent + 7),
context.config,
context.printer,
)?
)
} else {
Expand Down Expand Up @@ -1688,7 +1689,7 @@ fn rewrite_struct_lit<'a>(
force_no_trailing_comma || has_base_or_rest || !context.use_block_indent(),
);

write_list(&item_vec, &fmt)?
write_list(&item_vec, &fmt, context.printer)?
};

let fields_str =
Expand Down Expand Up @@ -1835,7 +1836,7 @@ fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>(
let fmt = ListFormatting::new(nested_shape, context.config)
.tactic(tactic)
.ends_with_newline(false);
let list_str = write_list(&item_vec, &fmt)?;
let list_str = write_list(&item_vec, &fmt, context.printer)?;

Some(format!("({list_str})"))
}
Expand Down
10 changes: 8 additions & 2 deletions src/formatting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use crate::parse::session::ParseSess;
use crate::utils::{contains_skip, count_newlines};
use crate::visitor::FmtVisitor;
use crate::{modules, source_file, ErrorKind, FormatReport, Input, Session};
use crate::print::Printer;

mod generated;
mod newline_style;
Expand Down Expand Up @@ -45,7 +46,7 @@ impl<'b, T: Write + 'b> Session<'b, T> {
}

let config = &self.config.clone();
let format_result = format_project(input, config, self, is_macro_def);
let format_result = format_project(input, config, self, is_macro_def, self.printer);

format_result.map(|report| {
self.errors.add(&report.internal.borrow().1);
Expand Down Expand Up @@ -103,6 +104,7 @@ fn format_project<T: FormatHandler>(
config: &Config,
handler: &mut T,
is_macro_def: bool,
printer: &Printer,
) -> Result<FormatReport, ErrorKind> {
let mut timer = Timer::start();

Expand Down Expand Up @@ -130,7 +132,7 @@ fn format_project<T: FormatHandler>(
}
};

let mut context = FormatContext::new(&krate, report, parse_session, config, handler);
let mut context = FormatContext::new(&krate, report, parse_session, config, handler, printer);
let files = modules::ModResolver::new(
&context.parse_session,
directory_ownership.unwrap_or(DirectoryOwnership::UnownedViaBlock),
Expand Down Expand Up @@ -181,6 +183,7 @@ struct FormatContext<'a, T: FormatHandler> {
parse_session: ParseSess,
config: &'a Config,
handler: &'a mut T,
printer: &'a Printer,
}

impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
Expand All @@ -190,13 +193,15 @@ impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
parse_session: ParseSess,
config: &'a Config,
handler: &'a mut T,
printer: &'a Printer,
) -> Self {
FormatContext {
krate,
report,
parse_session,
config,
handler,
printer,
}
}

Expand All @@ -216,6 +221,7 @@ impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
&self.parse_session,
self.config,
&snippet_provider,
&self.printer,
self.report.clone(),
);
visitor.skip_context.update_with_attrs(&self.krate.attrs);
Expand Down
2 changes: 1 addition & 1 deletion src/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1030,7 +1030,7 @@ fn rewrite_nested_use_tree(
.preserve_newline(true)
.nested(has_nested_list);

let list_str = write_list(&list_items, &fmt)?;
let list_str = write_list(&list_items, &fmt, context.printer)?;

let result = if (list_str.contains('\n')
|| list_str.len() > remaining_width
Expand Down
8 changes: 4 additions & 4 deletions src/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -635,7 +635,7 @@ impl<'a> FmtVisitor<'a> {
.trailing_separator(self.config.trailing_comma())
.preserve_newline(true);

let list = write_list(&items, &fmt)?;
let list = write_list(&items, &fmt, self.printer)?;
result.push_str(&list);
result.push_str(&original_offset.to_string_with_newline(self.config));
result.push('}');
Expand Down Expand Up @@ -2769,7 +2769,7 @@ fn rewrite_params(
.trailing_separator(trailing_separator)
.ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
.preserve_newline(true);
write_list(&param_items, &fmt)
write_list(&param_items, &fmt, context.printer)
}

fn compute_budgets_for_params(
Expand Down Expand Up @@ -3026,7 +3026,7 @@ fn rewrite_bounds_on_where_clause(
.tactic(shape_tactic)
.trailing_separator(comma_tactic)
.preserve_newline(preserve_newline);
write_list(&items.collect::<Vec<_>>(), &fmt)
write_list(&items.collect::<Vec<_>>(), &fmt, context.printer)
}

fn rewrite_where_clause(
Expand Down Expand Up @@ -3102,7 +3102,7 @@ fn rewrite_where_clause(
.trailing_separator(comma_tactic)
.ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
.preserve_newline(true);
let preds_str = write_list(&item_vec, &fmt)?;
let preds_str = write_list(&item_vec, &fmt, context.printer)?;

let end_length = if terminator == "{" {
// If the brace is on the next line we don't need to count it otherwise it needs two
Expand Down
13 changes: 9 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ pub use crate::config::{
};

pub use crate::format_report_formatter::{FormatReportFormatter, FormatReportFormatterBuilder};
use crate::print::Printer;

pub use crate::rustfmt_diff::{ModifiedChunk, ModifiedLines};

Expand Down Expand Up @@ -99,6 +100,7 @@ mod test;
mod types;
mod vertical;
pub(crate) mod visitor;
mod print;

/// The various errors that can occur during formatting. Note that not all of
/// these can currently be propagated to clients.
Expand Down Expand Up @@ -298,7 +300,7 @@ impl fmt::Display for FormatReport {

/// Format the given snippet. The snippet is expected to be *complete* code.
/// When we cannot parse the given snippet, this function returns `None`.
fn format_snippet(snippet: &str, config: &Config, is_macro_def: bool) -> Option<FormattedSnippet> {
fn format_snippet(snippet: &str, config: &Config, is_macro_def: bool, printer: &Printer) -> Option<FormattedSnippet> {
let mut config = config.clone();
panic::catch_unwind(|| {
let mut out: Vec<u8> = Vec::with_capacity(snippet.len() * 2);
Expand All @@ -311,7 +313,7 @@ fn format_snippet(snippet: &str, config: &Config, is_macro_def: bool) -> Option<

let (formatting_error, result) = {
let input = Input::Text(snippet.into());
let mut session = Session::new(config, Some(&mut out));
let mut session = Session::new(config, Some(&mut out), printer);
let result = session.format_input_inner(input, is_macro_def);
(
session.errors.has_macro_format_failure
Expand Down Expand Up @@ -343,6 +345,7 @@ fn format_code_block(
code_snippet: &str,
config: &Config,
is_macro_def: bool,
printer: &Printer,
) -> Option<FormattedSnippet> {
const FN_MAIN_PREFIX: &str = "fn main() {\n";

Expand Down Expand Up @@ -376,7 +379,7 @@ fn format_code_block(
config_with_unix_newline
.set()
.newline_style(NewlineStyle::Unix);
let mut formatted = format_snippet(&snippet, &config_with_unix_newline, is_macro_def)?;
let mut formatted = format_snippet(&snippet, &config_with_unix_newline, is_macro_def, printer)?;
// Remove wrapping main block
formatted.unwrap_code_block();

Expand Down Expand Up @@ -436,13 +439,14 @@ fn format_code_block(
pub struct Session<'b, T: Write> {
pub config: Config,
pub out: Option<&'b mut T>,
pub printer: &'b Printer,
pub(crate) errors: ReportedErrors,
source_file: SourceFile,
emitter: Box<dyn Emitter + 'b>,
}

impl<'b, T: Write + 'b> Session<'b, T> {
pub fn new(config: Config, mut out: Option<&'b mut T>) -> Session<'b, T> {
pub fn new(config: Config, mut out: Option<&'b mut T>, printer: &'b Printer) -> Session<'b, T> {
let emitter = create_emitter(&config);

if let Some(ref mut out) = out {
Expand All @@ -455,6 +459,7 @@ impl<'b, T: Write + 'b> Session<'b, T> {
emitter,
errors: ReportedErrors::default(),
source_file: SourceFile::new(),
printer,
}
}

Expand Down
Loading