Skip to content

Commit 645043a

Browse files
committed
Move formatting-related modules under formatting
1 parent 9e26fea commit 645043a

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+1063
-791
lines changed

rustfmt-core/rustfmt-lib/Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ emitter = [
2525
"diff",
2626
"serde",
2727
"serde_json",
28+
"term",
2829
]
2930

3031
[dependencies]
@@ -37,7 +38,6 @@ itertools = "0.8"
3738
lazy_static = "1.0.0"
3839
log = "0.4"
3940
regex = "1.0"
40-
term = "0.6"
4141
thiserror = "1.0"
4242
unicode_categories = "0.1.1"
4343
unicode-segmentation = "1.0.0"
@@ -49,6 +49,7 @@ dirs = { version = "2.0", optional = true }
4949
rustfmt-config_proc_macro = { version = "0.5", path = "config_proc_macro", optional = true }
5050
serde = { version = "1.0", features = ["derive"], optional = true }
5151
serde_json = { version = "1.0", optional = true }
52+
term = { version = "0.6", optional = true }
5253
toml = { version = "0.5", optional = true }
5354

5455
[target.'cfg(windows)'.dependencies]

rustfmt-core/rustfmt-lib/src/emitter.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use std::rc::Rc;
1212

1313
use thiserror::Error;
1414

15-
use crate::syntux::session::ParseSess;
15+
use crate::formatting::ParseSess;
1616
use crate::{config::FileName, FormatReport, FormatResult, NewlineStyle};
1717

1818
pub mod checkstyle;
@@ -165,7 +165,7 @@ where
165165
let mut has_diff = false;
166166

167167
emitter.emit_header(out)?;
168-
for (filename, format_result) in format_report.format_result.borrow().iter() {
168+
for (filename, format_result) in format_report.format_result_as_rc().borrow().iter() {
169169
has_diff |= write_file(None, filename, &format_result, out, &mut *emitter)?.has_diff;
170170
}
171171
emitter.emit_footer(out)?;
@@ -200,10 +200,10 @@ where
200200
// source map instead of hitting the file system. This also supports getting
201201
// original text for `FileName::Stdin`.
202202
let original_text =
203-
if formatted_result.newline_style != NewlineStyle::Auto && *filename != FileName::Stdin {
203+
if formatted_result.newline_style() != NewlineStyle::Auto && *filename != FileName::Stdin {
204204
Rc::new(fs::read_to_string(ensure_real_path(filename))?)
205205
} else {
206-
match &formatted_result.original_snippet {
206+
match formatted_result.original_text() {
207207
Some(original_snippet) => Rc::new(original_snippet.to_owned()),
208208
None => match parse_sess.and_then(|sess| sess.get_original_snippet(filename)) {
209209
Some(ori) => ori,
@@ -215,7 +215,7 @@ where
215215
let formatted_file = FormattedFile {
216216
filename,
217217
original_text: original_text.as_str(),
218-
formatted_text: &formatted_result.formatted_snippet.snippet,
218+
formatted_text: formatted_result.formatted_text(),
219219
};
220220

221221
emitter.emit_formatted_file(out, formatted_file)

rustfmt-core/rustfmt-lib/src/format_report_formatter.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,8 @@ impl<'a> Display for FormatReportFormatter<'a> {
4949
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5050
let formatter = DisplayListFormatter::new(self.enable_colors, false);
5151

52-
for (file, errors) in self.report.format_result.borrow().iter() {
53-
for error in errors.errors() {
52+
for (file, errors) in self.report.format_result_as_rc().borrow().iter() {
53+
for error in errors.errors_excluding_macro() {
5454
let snippet = formatting_error_to_snippet(file, error);
5555
writeln!(f, "{}\n", formatter.format(&DisplayList::from(snippet)))?;
5656
}
@@ -92,26 +92,26 @@ fn formatting_error_to_snippet(file: &FileName, error: &FormatError) -> Snippet
9292
}
9393

9494
fn snippet_title(error: &FormatError) -> Annotation {
95-
let annotation_type = error_kind_to_snippet_annotation_type(&error.kind);
95+
let annotation_type = error_kind_to_snippet_annotation_type(&error.kind());
9696

9797
Annotation {
9898
id: None,
99-
label: Some(error.kind.to_string()),
99+
label: Some(error.kind().to_string()),
100100
annotation_type,
101101
}
102102
}
103103

104104
fn snippet_code_slice(file: &FileName, error: &FormatError) -> Slice {
105105
let annotations = slice_annotation(error).into_iter().collect();
106106
let origin = error
107-
.line_num
107+
.line_num()
108108
.as_ref()
109109
.map(|line_num| format!("{}:{}", file, line_num));
110-
let source = error.line_str.clone().unwrap_or_else(|| String::new());
110+
let source = error.line_str().unwrap_or("").to_owned();
111111

112112
Slice {
113113
source,
114-
line_start: error.line_num.unwrap_or(0),
114+
line_start: error.line_num().unwrap_or(0),
115115
origin,
116116
fold: false,
117117
annotations,

rustfmt-core/rustfmt-lib/src/formatting.rs

Lines changed: 103 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,56 @@ use std::time::{Duration, Instant};
55

66
use rustc_ast::ast;
77

8+
pub(crate) use syntux::session::ParseSess;
9+
810
use self::newline_style::apply_newline_style;
9-
use crate::comment::{CharClasses, FullCodeCharKind};
11+
use crate::formatting::{
12+
comment::{CharClasses, FullCodeCharKind},
13+
report::NonFormattedRange,
14+
syntux::parser::{DirectoryOwnership, Parser, ParserError},
15+
utils::count_newlines,
16+
visitor::FmtVisitor,
17+
};
1018
use crate::config::{Config, FileName};
11-
use crate::syntux::parser::{DirectoryOwnership, Parser, ParserError};
12-
use crate::syntux::session::ParseSess;
13-
use crate::utils::count_newlines;
14-
use crate::visitor::FmtVisitor;
19+
use crate::result::OperationError;
1520
use crate::{
16-
modules, ErrorKind, FormatError, FormatReport, FormatResult, Input, NonFormattedRange,
17-
OperationError, OperationSetting, Verbosity,
21+
ErrorKind, FormatError, FormatReport, FormatResult, Input, OperationSetting, Verbosity,
1822
};
1923

24+
#[macro_use]
25+
mod utils;
26+
27+
mod attr;
28+
mod chains;
29+
mod closures;
30+
mod comment;
31+
mod expr;
32+
mod imports;
33+
mod items;
34+
mod lists;
35+
mod macros;
36+
mod matches;
37+
mod missed_spans;
38+
pub(crate) mod modules;
2039
mod newline_style;
40+
mod overflow;
41+
mod pairs;
42+
mod patterns;
43+
mod reorder;
44+
mod rewrite;
45+
mod shape;
46+
mod skip;
47+
pub(crate) mod source_map;
48+
mod spanned;
49+
mod stmt;
50+
mod string;
51+
mod syntux;
52+
mod types;
53+
mod vertical;
54+
pub(crate) mod visitor;
55+
56+
pub(crate) mod report;
57+
pub(crate) mod util;
2158

2259
pub(crate) fn format_input_inner(
2360
input: Input,
@@ -32,6 +69,7 @@ pub(crate) fn format_input_inner(
3269
format_project(input, config, operation_setting)
3370
})
3471
}
72+
3573
fn format_project(
3674
input: Input,
3775
config: &Config,
@@ -412,3 +450,61 @@ where
412450
f();
413451
}
414452
}
453+
454+
/// Result of formatting a snippet of code along with ranges of lines that didn't get formatted,
455+
/// i.e., that got returned as they were originally.
456+
#[derive(Debug, Clone, Default)]
457+
pub(crate) struct FormattedSnippet {
458+
snippet: String,
459+
non_formatted_ranges: Vec<NonFormattedRange>,
460+
}
461+
462+
impl FormattedSnippet {
463+
/// In case the snippet needed to be wrapped in a function, this shifts down the ranges of
464+
/// non-formatted code.
465+
fn unwrap_code_block(&mut self) {
466+
self.non_formatted_ranges.iter_mut().for_each(|range| {
467+
*range = range.shift_up();
468+
});
469+
}
470+
471+
/// Returns `true` if the line n did not get formatted.
472+
pub(crate) fn is_line_non_formatted(&self, n: usize) -> bool {
473+
self.non_formatted_ranges
474+
.iter()
475+
.any(|range| range.contains(n))
476+
}
477+
}
478+
479+
impl AsRef<str> for FormattedSnippet {
480+
fn as_ref(&self) -> &str {
481+
self.snippet.as_str()
482+
}
483+
}
484+
485+
impl Input {
486+
fn file_name(&self) -> FileName {
487+
match *self {
488+
Input::File(ref file) => FileName::Real(file.clone()),
489+
Input::Text(..) => FileName::Stdin,
490+
}
491+
}
492+
493+
fn to_directory_ownership(&self) -> Option<DirectoryOwnership> {
494+
match self {
495+
Input::File(ref file) => {
496+
// If there exists a directory with the same name as an input,
497+
// then the input should be parsed as a sub module.
498+
let file_stem = file.file_stem()?;
499+
if file.parent()?.to_path_buf().join(file_stem).is_dir() {
500+
Some(DirectoryOwnership::Owned {
501+
relative: file_stem.to_str().map(ast::Ident::from_str),
502+
})
503+
} else {
504+
None
505+
}
506+
}
507+
_ => None,
508+
}
509+
}
510+
}

rustfmt-core/rustfmt-lib/src/attr.rs renamed to rustfmt-core/rustfmt-lib/src/formatting/attr.rs

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,22 @@ use rustc_ast::ast;
44
use rustc_ast::attr::HasAttrs;
55
use rustc_span::{symbol::sym, Span};
66

7-
use self::doc_comment::DocCommentFormatter;
8-
use crate::comment::{contains_comment, rewrite_doc_comment, CommentStyle};
9-
use crate::config::lists::*;
10-
use crate::config::IndentStyle;
11-
use crate::expr::rewrite_literal;
12-
use crate::lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
13-
use crate::overflow;
14-
use crate::rewrite::{Rewrite, RewriteContext};
15-
use crate::shape::Shape;
16-
use crate::types::{rewrite_path, PathContext};
17-
use crate::utils::{count_newlines, mk_sp};
7+
use doc_comment::DocCommentFormatter;
8+
use crate::config::{
9+
lists::*,
10+
IndentStyle,
11+
};
12+
13+
use crate::formatting::{
14+
comment::{contains_comment, rewrite_doc_comment, CommentStyle, recover_missing_comment_in_span},
15+
expr::{rewrite_literal, span_ends_with_comma},
16+
lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator},
17+
overflow,
18+
rewrite::{Rewrite, RewriteContext},
19+
shape::Shape,
20+
types::{rewrite_path, PathContext},
21+
utils::{count_newlines, mk_sp},
22+
};
1823

1924
mod doc_comment;
2025

@@ -279,7 +284,7 @@ impl Rewrite for ast::MetaItem {
279284
}
280285
ast::MetaItemKind::List(ref list) => {
281286
let path = rewrite_path(context, PathContext::Type, None, &self.path, shape)?;
282-
let has_trailing_comma = crate::expr::span_ends_with_comma(context, self.span);
287+
let has_trailing_comma = span_ends_with_comma(context, self.span);
283288
overflow::rewrite_with_parens(
284289
context,
285290
&path,
@@ -398,7 +403,7 @@ impl<'a> Rewrite for [ast::Attribute] {
398403
if let Some(missing_span) = missing_span {
399404
let snippet = context.snippet(missing_span);
400405
let (mla, mlb) = has_newlines_before_after_comment(snippet);
401-
let comment = crate::comment::recover_missing_comment_in_span(
406+
let comment = recover_missing_comment_in_span(
402407
missing_span,
403408
shape.with_max_width(context.config),
404409
context,
@@ -428,7 +433,7 @@ impl<'a> Rewrite for [ast::Attribute] {
428433
.get(derives.len())
429434
.map(|next| mk_sp(attrs[derives.len() - 1].span.hi(), next.span.lo()));
430435
if let Some(missing_span) = missing_span {
431-
let comment = crate::comment::recover_missing_comment_in_span(
436+
let comment = recover_missing_comment_in_span(
432437
missing_span,
433438
shape.with_max_width(context.config),
434439
context,
@@ -461,7 +466,7 @@ impl<'a> Rewrite for [ast::Attribute] {
461466
.get(1)
462467
.map(|next| mk_sp(attrs[0].span.hi(), next.span.lo()));
463468
if let Some(missing_span) = missing_span {
464-
let comment = crate::comment::recover_missing_comment_in_span(
469+
let comment = recover_missing_comment_in_span(
465470
missing_span,
466471
shape.with_max_width(context.config),
467472
context,

rustfmt-core/rustfmt-lib/src/attr/doc_comment.rs renamed to rustfmt-core/rustfmt-lib/src/formatting/attr/doc_comment.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
use crate::comment::CommentStyle;
21
use std::fmt::{self, Display};
32

3+
use crate::formatting::comment::CommentStyle;
4+
45
/// Formats a string as a doc comment using the given [`CommentStyle`].
56
pub(super) struct DocCommentFormatter<'a> {
67
literal: &'a str,

rustfmt-core/rustfmt-lib/src/chains.rs renamed to rustfmt-core/rustfmt-lib/src/formatting/chains.rs

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -61,17 +61,19 @@ use std::cmp::min;
6161
use rustc_ast::{ast, ptr};
6262
use rustc_span::{symbol, BytePos, Span};
6363

64-
use crate::comment::{rewrite_comment, CharClasses, FullCodeCharKind, RichChar};
6564
use crate::config::IndentStyle;
66-
use crate::expr::rewrite_call;
67-
use crate::lists::extract_pre_comment;
68-
use crate::macros::convert_try_mac;
69-
use crate::rewrite::{Rewrite, RewriteContext};
70-
use crate::shape::Shape;
71-
use crate::source_map::SpanUtils;
72-
use crate::utils::{
73-
self, first_line_width, last_line_extendable, last_line_width, mk_sp, rewrite_ident,
74-
trimmed_last_line_width, wrap_str,
65+
use crate::formatting::{
66+
comment::{rewrite_comment, CharClasses, FullCodeCharKind, RichChar},
67+
expr::rewrite_call,
68+
lists::extract_pre_comment,
69+
macros::convert_try_mac,
70+
rewrite::{Rewrite, RewriteContext},
71+
shape::Shape,
72+
source_map::SpanUtils,
73+
utils::{
74+
self, first_line_width, last_line_extendable, last_line_width, mk_sp, rewrite_ident,
75+
trimmed_last_line_width, wrap_str,
76+
},
7577
};
7678

7779
pub(crate) fn rewrite_chain(

rustfmt-core/rustfmt-lib/src/closures.rs renamed to rustfmt-core/rustfmt-lib/src/formatting/closures.rs

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,23 @@
11
use rustc_ast::{ast, ptr};
22
use rustc_span::Span;
33

4-
use crate::attr::get_attrs_from_stmt;
5-
use crate::config::lists::*;
6-
use crate::config::{IndentStyle, SeparatorTactic};
7-
use crate::expr::{block_contains_comment, is_simple_block, is_unsafe_block, rewrite_cond};
8-
use crate::items::{span_hi_for_param, span_lo_for_param};
9-
use crate::lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
10-
use crate::overflow::OverflowableItem;
11-
use crate::rewrite::{Rewrite, RewriteContext};
12-
use crate::shape::Shape;
13-
use crate::source_map::SpanUtils;
14-
use crate::utils::{last_line_width, left_most_sub_expr, stmt_expr, NodeIdExt};
4+
use crate::config::{
5+
lists::*,
6+
IndentStyle,
7+
SeparatorTactic,
8+
};
9+
use crate::formatting::{
10+
attr::get_attrs_from_stmt,
11+
expr::{block_contains_comment, is_simple_block, is_unsafe_block, rewrite_cond,
12+
rewrite_block_with_visitor},
13+
items::{span_hi_for_param, span_lo_for_param},
14+
lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator},
15+
overflow::OverflowableItem,
16+
rewrite::{Rewrite, RewriteContext},
17+
shape::Shape,
18+
source_map::SpanUtils,
19+
utils::{last_line_width, left_most_sub_expr, stmt_expr, NodeIdExt},
20+
};
1521

1622
// This module is pretty messy because of the rules around closures and blocks:
1723
// FIXME - the below is probably no longer true in full.
@@ -156,7 +162,7 @@ fn rewrite_closure_with_block(
156162
rules: ast::BlockCheckMode::Default,
157163
span: body.span,
158164
};
159-
let block = crate::expr::rewrite_block_with_visitor(
165+
let block = rewrite_block_with_visitor(
160166
context,
161167
"",
162168
&block,

0 commit comments

Comments
 (0)