diff --git a/src/attr.rs b/src/attr.rs index 3379bf2369b1..498d6e4d8511 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -15,7 +15,7 @@ use crate::types::{rewrite_path, PathContext}; use crate::utils::{count_newlines, mk_sp}; /// Returns attributes on the given statement. -pub fn get_attrs_from_stmt(stmt: &ast::Stmt) -> &[ast::Attribute] { +pub(crate) fn get_attrs_from_stmt(stmt: &ast::Stmt) -> &[ast::Attribute] { match stmt.node { ast::StmtKind::Local(ref local) => &local.attrs, ast::StmtKind::Item(ref item) => &item.attrs, @@ -24,7 +24,7 @@ pub fn get_attrs_from_stmt(stmt: &ast::Stmt) -> &[ast::Attribute] { } } -pub fn get_span_without_attrs(stmt: &ast::Stmt) -> Span { +pub(crate) fn get_span_without_attrs(stmt: &ast::Stmt) -> Span { match stmt.node { ast::StmtKind::Local(ref local) => local.span, ast::StmtKind::Item(ref item) => item.span, @@ -37,7 +37,10 @@ pub fn get_span_without_attrs(stmt: &ast::Stmt) -> Span { } /// Returns attributes that are within `outer_span`. -pub fn filter_inline_attrs(attrs: &[ast::Attribute], outer_span: Span) -> Vec { +pub(crate) fn filter_inline_attrs( + attrs: &[ast::Attribute], + outer_span: Span, +) -> Vec { attrs .iter() .filter(|a| outer_span.lo() <= a.span.lo() && a.span.hi() <= outer_span.hi()) diff --git a/src/chains.rs b/src/chains.rs index 5ea3953a2c75..c4941141a64a 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -74,7 +74,7 @@ use crate::utils::{ trimmed_last_line_width, wrap_str, }; -pub fn rewrite_chain( +pub(crate) fn rewrite_chain( expr: &ast::Expr, context: &RewriteContext<'_>, shape: Shape, diff --git a/src/checkstyle.rs b/src/checkstyle.rs index 169a3741be46..79c59bb1e8ca 100644 --- a/src/checkstyle.rs +++ b/src/checkstyle.rs @@ -7,7 +7,7 @@ use crate::rustfmt_diff::{DiffLine, Mismatch}; /// /// Note that emitting checkstyle output is not stable and may removed in a /// future version of Rustfmt. -pub fn header() -> String { +pub(crate) fn header() -> String { let mut xml_heading = String::new(); xml_heading.push_str(""); xml_heading.push_str("\n"); @@ -19,11 +19,11 @@ pub fn header() -> String { /// /// Note that emitting checkstyle output is not stable and may removed in a /// future version of Rustfmt. -pub fn footer() -> String { +pub(crate) fn footer() -> String { "\n".to_owned() } -pub fn output_checkstyle_file( +pub(crate) fn output_checkstyle_file( mut writer: T, filename: &Path, diff: Vec, diff --git a/src/closures.rs b/src/closures.rs index d88b73340346..8a7f47af44b3 100644 --- a/src/closures.rs +++ b/src/closures.rs @@ -23,7 +23,7 @@ use crate::utils::{last_line_width, left_most_sub_expr, stmt_expr, NodeIdExt}; // statement without needing a semi-colon), then adding or removing braces // can change whether it is treated as an expression or statement. -pub fn rewrite_closure( +pub(crate) fn rewrite_closure( capture: ast::CaptureBy, asyncness: ast::IsAsync, movability: ast::Movability, @@ -286,7 +286,7 @@ fn rewrite_closure_fn_decl( // Rewriting closure which is placed at the end of the function call's arg. // Returns `None` if the reformatted closure 'looks bad'. -pub fn rewrite_last_closure( +pub(crate) fn rewrite_last_closure( context: &RewriteContext<'_>, expr: &ast::Expr, shape: Shape, @@ -351,7 +351,7 @@ pub fn rewrite_last_closure( } /// Returns `true` if the given vector of arguments has more than one `ast::ExprKind::Closure`. -pub fn args_have_many_closure(args: &[OverflowableItem<'_>]) -> bool { +pub(crate) fn args_have_many_closure(args: &[OverflowableItem<'_>]) -> bool { args.iter() .filter_map(OverflowableItem::to_expr) .filter(|expr| match expr.node { diff --git a/src/comment.rs b/src/comment.rs index 797f75fc580a..7f7dce1166d0 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -25,7 +25,7 @@ fn is_custom_comment(comment: &str) -> bool { } #[derive(Copy, Clone, PartialEq, Eq)] -pub enum CommentStyle<'a> { +pub(crate) enum CommentStyle<'a> { DoubleSlash, TripleSlash, Doc, @@ -45,7 +45,7 @@ fn custom_opener(s: &str) -> &str { impl<'a> CommentStyle<'a> { /// Returns `true` if the commenting style covers a line only. - pub fn is_line_comment(&self) -> bool { + pub(crate) fn is_line_comment(&self) -> bool { match *self { CommentStyle::DoubleSlash | CommentStyle::TripleSlash @@ -56,7 +56,7 @@ impl<'a> CommentStyle<'a> { } /// Returns `true` if the commenting style can span over multiple lines. - pub fn is_block_comment(&self) -> bool { + pub(crate) fn is_block_comment(&self) -> bool { match *self { CommentStyle::SingleBullet | CommentStyle::DoubleBullet | CommentStyle::Exclamation => { true @@ -66,14 +66,14 @@ impl<'a> CommentStyle<'a> { } /// Returns `true` if the commenting style is for documentation. - pub fn is_doc_comment(&self) -> bool { + pub(crate) fn is_doc_comment(&self) -> bool { match *self { CommentStyle::TripleSlash | CommentStyle::Doc => true, _ => false, } } - pub fn opener(&self) -> &'a str { + pub(crate) fn opener(&self) -> &'a str { match *self { CommentStyle::DoubleSlash => "// ", CommentStyle::TripleSlash => "/// ", @@ -85,7 +85,7 @@ impl<'a> CommentStyle<'a> { } } - pub fn closer(&self) -> &'a str { + pub(crate) fn closer(&self) -> &'a str { match *self { CommentStyle::DoubleSlash | CommentStyle::TripleSlash @@ -96,7 +96,7 @@ impl<'a> CommentStyle<'a> { } } - pub fn line_start(&self) -> &'a str { + pub(crate) fn line_start(&self) -> &'a str { match *self { CommentStyle::DoubleSlash => "// ", CommentStyle::TripleSlash => "/// ", @@ -107,7 +107,7 @@ impl<'a> CommentStyle<'a> { } } - pub fn to_str_tuplet(&self) -> (&'a str, &'a str, &'a str) { + pub(crate) fn to_str_tuplet(&self) -> (&'a str, &'a str, &'a str) { (self.opener(), self.closer(), self.line_start()) } } @@ -143,7 +143,7 @@ fn comment_style(orig: &str, normalize_comments: bool) -> CommentStyle<'_> { } /// Returns true if the last line of the passed string finishes with a block-comment. -pub fn is_last_comment_block(s: &str) -> bool { +pub(crate) fn is_last_comment_block(s: &str) -> bool { s.trim_end().ends_with("*/") } @@ -152,7 +152,7 @@ pub fn is_last_comment_block(s: &str) -> bool { /// recovered. If `allow_extend` is true and there is no comment between the two /// strings, then they will be put on a single line as long as doing so does not /// exceed max width. -pub fn combine_strs_with_missing_comments( +pub(crate) fn combine_strs_with_missing_comments( context: &RewriteContext<'_>, prev_str: &str, next_str: &str, @@ -239,11 +239,11 @@ pub fn combine_strs_with_missing_comments( Some(result) } -pub fn rewrite_doc_comment(orig: &str, shape: Shape, config: &Config) -> Option { +pub(crate) fn rewrite_doc_comment(orig: &str, shape: Shape, config: &Config) -> Option { identify_comment(orig, false, shape, config, true) } -pub fn rewrite_comment( +pub(crate) fn rewrite_comment( orig: &str, block_style: bool, shape: Shape, @@ -845,7 +845,7 @@ fn has_url(s: &str) -> bool { /// Given the span, rewrite the missing comment inside it if available. /// Note that the given span must only include comments (or leading/trailing whitespaces). -pub fn rewrite_missing_comment( +pub(crate) fn rewrite_missing_comment( span: Span, shape: Shape, context: &RewriteContext<'_>, @@ -862,7 +862,7 @@ pub fn rewrite_missing_comment( /// Recover the missing comments in the specified span, if available. /// The layout of the comments will be preserved as long as it does not break the code /// and its total width does not exceed the max width. -pub fn recover_missing_comment_in_span( +pub(crate) fn recover_missing_comment_in_span( span: Span, shape: Shape, context: &RewriteContext<'_>, @@ -964,7 +964,7 @@ fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle<'_>) -> (&'a s } } -pub trait FindUncommented { +pub(crate) trait FindUncommented { fn find_uncommented(&self, pat: &str) -> Option; } @@ -997,7 +997,7 @@ impl FindUncommented for str { // is expected to be prefixed by a comment, including delimiters. // Good: `/* /* inner */ outer */ code();` // Bad: `code(); // hello\n world!` -pub fn find_comment_end(s: &str) -> Option { +pub(crate) fn find_comment_end(s: &str) -> Option { let mut iter = CharClasses::new(s.char_indices()); for (kind, (i, _c)) in &mut iter { if kind == FullCodeCharKind::Normal || kind == FullCodeCharKind::InString { @@ -1014,11 +1014,11 @@ pub fn find_comment_end(s: &str) -> Option { } /// Returns `true` if text contains any comment. -pub fn contains_comment(text: &str) -> bool { +pub(crate) fn contains_comment(text: &str) -> bool { CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment()) } -pub struct CharClasses +pub(crate) struct CharClasses where T: Iterator, T::Item: RichChar, @@ -1027,7 +1027,7 @@ where status: CharClassesStatus, } -pub trait RichChar { +pub(crate) trait RichChar { fn get_char(&self) -> char; } @@ -1073,7 +1073,7 @@ enum CharClassesStatus { /// Distinguish between functional part of code and comments #[derive(PartialEq, Eq, Debug, Clone, Copy)] -pub enum CodeCharKind { +pub(crate) enum CodeCharKind { Normal, Comment, } @@ -1082,7 +1082,7 @@ pub enum CodeCharKind { /// describing opening and closing of comments for ease when chunking /// code from tagged characters #[derive(PartialEq, Eq, Debug, Clone, Copy)] -pub enum FullCodeCharKind { +pub(crate) enum FullCodeCharKind { Normal, /// The first character of a comment, there is only one for a comment (always '/') StartComment, @@ -1106,7 +1106,7 @@ pub enum FullCodeCharKind { } impl FullCodeCharKind { - pub fn is_comment(self) -> bool { + pub(crate) fn is_comment(self) -> bool { match self { FullCodeCharKind::StartComment | FullCodeCharKind::InComment @@ -1119,7 +1119,7 @@ impl FullCodeCharKind { } /// Returns true if the character is inside a comment - pub fn inside_comment(self) -> bool { + pub(crate) fn inside_comment(self) -> bool { match self { FullCodeCharKind::InComment | FullCodeCharKind::StartStringCommented @@ -1129,12 +1129,12 @@ impl FullCodeCharKind { } } - pub fn is_string(self) -> bool { + pub(crate) fn is_string(self) -> bool { self == FullCodeCharKind::InString || self == FullCodeCharKind::StartString } /// Returns true if the character is within a commented string - pub fn is_commented_string(self) -> bool { + pub(crate) fn is_commented_string(self) -> bool { self == FullCodeCharKind::InStringCommented || self == FullCodeCharKind::StartStringCommented } @@ -1153,7 +1153,7 @@ where T: Iterator, T::Item: RichChar, { - pub fn new(base: T) -> CharClasses { + pub(crate) fn new(base: T) -> CharClasses { CharClasses { base: multipeek(base), status: CharClassesStatus::Normal, @@ -1336,13 +1336,13 @@ where /// An iterator over the lines of a string, paired with the char kind at the /// end of the line. -pub struct LineClasses<'a> { +pub(crate) struct LineClasses<'a> { base: iter::Peekable>>, kind: FullCodeCharKind, } impl<'a> LineClasses<'a> { - pub fn new(s: &'a str) -> Self { + pub(crate) fn new(s: &'a str) -> Self { LineClasses { base: CharClasses::new(s.chars()).peekable(), kind: FullCodeCharKind::Normal, @@ -1458,14 +1458,14 @@ impl<'a> Iterator for UngroupedCommentCodeSlices<'a> { /// Iterator over an alternating sequence of functional and commented parts of /// a string. The first item is always a, possibly zero length, subslice of /// functional text. Line style comments contain their ending newlines. -pub struct CommentCodeSlices<'a> { +pub(crate) struct CommentCodeSlices<'a> { slice: &'a str, last_slice_kind: CodeCharKind, last_slice_end: usize, } impl<'a> CommentCodeSlices<'a> { - pub fn new(slice: &'a str) -> CommentCodeSlices<'a> { + pub(crate) fn new(slice: &'a str) -> CommentCodeSlices<'a> { CommentCodeSlices { slice, last_slice_kind: CodeCharKind::Comment, @@ -1536,7 +1536,7 @@ impl<'a> Iterator for CommentCodeSlices<'a> { /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text /// (if it fits in the width/offset, else return `None`), else return `new` -pub fn recover_comment_removed( +pub(crate) fn recover_comment_removed( new: String, span: Span, context: &RewriteContext<'_>, @@ -1560,7 +1560,7 @@ pub fn recover_comment_removed( } } -pub fn filter_normal_code(code: &str) -> String { +pub(crate) fn filter_normal_code(code: &str) -> String { let mut buffer = String::with_capacity(code.len()); LineClasses::new(code).for_each(|(kind, line)| match kind { FullCodeCharKind::Normal diff --git a/src/config/config_type.rs b/src/config/config_type.rs index 82a19c5898f1..d14969418ad1 100644 --- a/src/config/config_type.rs +++ b/src/config/config_type.rs @@ -2,7 +2,7 @@ use crate::config::file_lines::FileLines; use crate::config::options::{IgnoreList, WidthHeuristics}; /// Trait for types that can be used in `Config`. -pub trait ConfigType: Sized { +pub(crate) trait ConfigType: Sized { /// Returns hint text for use in `Config::print_docs()`. For enum types, this is a /// pipe-separated list of variants; for other types it returns "". fn doc_hint() -> String; @@ -75,6 +75,7 @@ macro_rules! create_config { use serde::{Deserialize, Serialize}; #[derive(Clone)] + #[allow(unreachable_pub)] pub struct Config { // if a license_template_path has been specified, successfully read, parsed and compiled // into a regex, it will be stored here @@ -91,6 +92,7 @@ macro_rules! create_config { // We first parse into `PartialConfig`, then create a default `Config` // and overwrite the properties with corresponding values from `PartialConfig`. #[derive(Deserialize, Serialize, Clone)] + #[allow(unreachable_pub)] pub struct PartialConfig { $(pub $i: Option<$ty>),+ } @@ -100,10 +102,12 @@ macro_rules! create_config { // `config.set().option(false)`. It's pretty ugly. Consider replacing // with `config.set_option(false)` if we ever get a stable/usable // `concat_idents!()`. + #[allow(unreachable_pub)] pub struct ConfigSetter<'a>(&'a mut Config); impl<'a> ConfigSetter<'a> { $( + #[allow(unreachable_pub)] pub fn $i(&mut self, value: $ty) { (self.0).$i.2 = value; match stringify!($i) { @@ -117,10 +121,12 @@ macro_rules! create_config { // Query each option, returns true if the user set the option, false if // a default was used. + #[allow(unreachable_pub)] pub struct ConfigWasSet<'a>(&'a Config); impl<'a> ConfigWasSet<'a> { $( + #[allow(unreachable_pub)] pub fn $i(&self) -> bool { (self.0).$i.1 } @@ -129,16 +135,19 @@ macro_rules! create_config { impl Config { $( + #[allow(unreachable_pub)] pub fn $i(&self) -> $ty { self.$i.0.set(true); self.$i.2.clone() } )+ + #[allow(unreachable_pub)] pub fn set(&mut self) -> ConfigSetter<'_> { ConfigSetter(self) } + #[allow(unreachable_pub)] pub fn was_set(&self) -> ConfigWasSet<'_> { ConfigWasSet(self) } @@ -185,6 +194,7 @@ macro_rules! create_config { } } + #[allow(unreachable_pub)] pub fn used_options(&self) -> PartialConfig { PartialConfig { $( @@ -197,6 +207,7 @@ macro_rules! create_config { } } + #[allow(unreachable_pub)] pub fn all_options(&self) -> PartialConfig { PartialConfig { $( @@ -205,6 +216,7 @@ macro_rules! create_config { } } + #[allow(unreachable_pub)] pub fn override_value(&mut self, key: &str, val: &str) { match key { @@ -228,12 +240,14 @@ macro_rules! create_config { } } + #[allow(unreachable_pub)] pub fn is_hidden_option(name: &str) -> bool { const HIDE_OPTIONS: [&str; 4] = ["verbose", "verbose_diff", "file_lines", "width_heuristics"]; HIDE_OPTIONS.contains(&name) } + #[allow(unreachable_pub)] pub fn print_docs(out: &mut dyn Write, include_unstable: bool) { use std::cmp; let max = 0; @@ -293,6 +307,7 @@ macro_rules! create_config { self.ignore.2.add_prefix(dir); } + #[allow(unreachable_pub)] /// Returns `true` if the config key was explicitly set and is the default value. pub fn is_default(&self, key: &str) -> bool { $( diff --git a/src/config/license.rs b/src/config/license.rs index 7adaecf9d5c1..2eb23bbcec7f 100644 --- a/src/config/license.rs +++ b/src/config/license.rs @@ -7,7 +7,7 @@ use regex; use regex::Regex; #[derive(Debug)] -pub enum LicenseError { +pub(crate) enum LicenseError { IO(io::Error), Regex(regex::Error), Parse(String), @@ -47,7 +47,7 @@ enum ParsingState { use self::ParsingState::*; -pub struct TemplateParser { +pub(crate) struct TemplateParser { parsed: String, buffer: String, state: ParsingState, @@ -110,7 +110,7 @@ impl TemplateParser { /// " /// ); /// ``` - pub fn parse(template: &str) -> Result { + pub(crate) fn parse(template: &str) -> Result { let mut parser = Self::new(); for chr in template.chars() { if chr == '\n' { @@ -212,7 +212,7 @@ impl TemplateParser { } } -pub fn load_and_compile_template(path: &str) -> Result { +pub(crate) fn load_and_compile_template(path: &str) -> Result { let mut lt_file = File::open(&path)?; let mut lt_str = String::new(); lt_file.read_to_string(&mut lt_str)?; diff --git a/src/config/mod.rs b/src/config/mod.rs index c0221e93e025..82a7f5fc39a2 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -8,18 +8,21 @@ use std::{env, fs}; use regex::Regex; use crate::config::config_type::ConfigType; +#[allow(unreachable_pub)] pub use crate::config::file_lines::{FileLines, FileName, Range}; +#[allow(unreachable_pub)] pub use crate::config::lists::*; +#[allow(unreachable_pub)] pub use crate::config::options::*; #[macro_use] -pub mod config_type; +pub(crate) mod config_type; #[macro_use] -pub mod options; +pub(crate) mod options; -pub mod file_lines; -pub mod license; -pub mod lists; +pub(crate) mod file_lines; +pub(crate) mod license; +pub(crate) mod lists; // This macro defines configuration options used in rustfmt. Each option // is defined as follows: diff --git a/src/expr.rs b/src/expr.rs index da1b035ad1ca..c4c41fb69574 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -44,12 +44,12 @@ impl Rewrite for ast::Expr { } #[derive(Copy, Clone, PartialEq)] -pub enum ExprType { +pub(crate) enum ExprType { Statement, SubExpression, } -pub fn format_expr( +pub(crate) fn format_expr( expr: &ast::Expr, expr_type: ExprType, context: &RewriteContext<'_>, @@ -386,7 +386,7 @@ pub fn format_expr( }) } -pub fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>( +pub(crate) fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>( name: &'a str, exprs: impl Iterator, span: Span, @@ -492,7 +492,7 @@ fn rewrite_single_line_block( None } -pub fn rewrite_block_with_visitor( +pub(crate) fn rewrite_block_with_visitor( context: &RewriteContext<'_>, prefix: &str, block: &ast::Block, @@ -581,7 +581,7 @@ impl Rewrite for ast::Stmt { } // Rewrite condition if the given expression has one. -pub fn rewrite_cond( +pub(crate) fn rewrite_cond( context: &RewriteContext<'_>, expr: &ast::Expr, shape: Shape, @@ -1128,7 +1128,7 @@ fn extract_comment(span: Span, context: &RewriteContext<'_>, shape: Shape) -> Op } } -pub fn block_contains_comment(block: &ast::Block, source_map: &SourceMap) -> bool { +pub(crate) fn block_contains_comment(block: &ast::Block, source_map: &SourceMap) -> bool { let snippet = source_map.span_to_snippet(block.span).unwrap(); contains_comment(&snippet) } @@ -1137,7 +1137,7 @@ pub fn block_contains_comment(block: &ast::Block, source_map: &SourceMap) -> boo // attributes. // FIXME: incorrectly returns false when comment is contained completely within // the expression. -pub fn is_simple_block( +pub(crate) fn is_simple_block( block: &ast::Block, attrs: Option<&[ast::Attribute]>, source_map: &SourceMap, @@ -1150,7 +1150,7 @@ pub fn is_simple_block( /// Checks whether a block contains at most one statement or expression, and no /// comments or attributes. -pub fn is_simple_block_stmt( +pub(crate) fn is_simple_block_stmt( block: &ast::Block, attrs: Option<&[ast::Attribute]>, source_map: &SourceMap, @@ -1162,7 +1162,7 @@ pub fn is_simple_block_stmt( /// Checks whether a block contains no statements, expressions, comments, or /// inner attributes. -pub fn is_empty_block( +pub(crate) fn is_empty_block( block: &ast::Block, attrs: Option<&[ast::Attribute]>, source_map: &SourceMap, @@ -1172,7 +1172,7 @@ pub fn is_empty_block( && attrs.map_or(true, |a| inner_attributes(a).is_empty()) } -pub fn stmt_is_expr(stmt: &ast::Stmt) -> bool { +pub(crate) fn stmt_is_expr(stmt: &ast::Stmt) -> bool { match stmt.node { ast::StmtKind::Expr(..) => true, _ => false, @@ -1189,7 +1189,7 @@ pub(crate) fn stmt_is_if(stmt: &ast::Stmt) -> bool { } } -pub fn is_unsafe_block(block: &ast::Block) -> bool { +pub(crate) fn is_unsafe_block(block: &ast::Block) -> bool { if let ast::BlockCheckMode::Unsafe(..) = block.rules { true } else { @@ -1197,7 +1197,7 @@ pub fn is_unsafe_block(block: &ast::Block) -> bool { } } -pub fn rewrite_multiple_patterns( +pub(crate) fn rewrite_multiple_patterns( context: &RewriteContext<'_>, pats: &[&ast::Pat], shape: Shape, @@ -1230,7 +1230,11 @@ pub fn rewrite_multiple_patterns( write_list(&items, &fmt) } -pub fn rewrite_literal(context: &RewriteContext<'_>, l: &ast::Lit, shape: Shape) -> Option { +pub(crate) fn rewrite_literal( + context: &RewriteContext<'_>, + l: &ast::Lit, + shape: Shape, +) -> Option { match l.node { ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape), _ => wrap_str( @@ -1297,7 +1301,7 @@ fn choose_separator_tactic(context: &RewriteContext<'_>, span: Span) -> Option, callee: &str, args: &[ptr::P], @@ -1315,7 +1319,7 @@ pub fn rewrite_call( ) } -pub fn is_simple_expr(expr: &ast::Expr) -> bool { +pub(crate) fn is_simple_expr(expr: &ast::Expr) -> bool { match expr.node { ast::ExprKind::Lit(..) => true, ast::ExprKind::Path(ref qself, ref path) => qself.is_none() && path.segments.len() <= 1, @@ -1333,11 +1337,11 @@ pub fn is_simple_expr(expr: &ast::Expr) -> bool { } } -pub fn is_every_expr_simple(lists: &[OverflowableItem<'_>]) -> bool { +pub(crate) fn is_every_expr_simple(lists: &[OverflowableItem<'_>]) -> bool { lists.iter().all(OverflowableItem::is_simple) } -pub fn can_be_overflowed_expr( +pub(crate) fn can_be_overflowed_expr( context: &RewriteContext<'_>, expr: &ast::Expr, args_len: usize, @@ -1388,7 +1392,7 @@ pub fn can_be_overflowed_expr( } } -pub fn is_nested_call(expr: &ast::Expr) -> bool { +pub(crate) fn is_nested_call(expr: &ast::Expr) -> bool { match expr.node { ast::ExprKind::Call(..) | ast::ExprKind::Mac(..) => true, ast::ExprKind::AddrOf(_, ref expr) @@ -1403,7 +1407,7 @@ pub fn is_nested_call(expr: &ast::Expr) -> bool { /// Returns `true` if a function call or a method call represented by the given span ends with a /// trailing comma. This function is used when rewriting macro, as adding or removing a trailing /// comma from macro can potentially break the code. -pub fn span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool { +pub(crate) fn span_ends_with_comma(context: &RewriteContext<'_>, span: Span) -> bool { let mut result: bool = Default::default(); let mut prev_char: char = Default::default(); let closing_delimiters = &[')', '}', ']']; @@ -1667,7 +1671,7 @@ fn rewrite_struct_lit<'a>( // of space, we should fall back to BlockIndent. } -pub fn wrap_struct_field( +pub(crate) fn wrap_struct_field( context: &RewriteContext<'_>, fields_str: &str, shape: Shape, @@ -1691,11 +1695,11 @@ pub fn wrap_struct_field( } } -pub fn struct_lit_field_separator(config: &Config) -> &str { +pub(crate) fn struct_lit_field_separator(config: &Config) -> &str { colon_spaces(config) } -pub fn rewrite_field( +pub(crate) fn rewrite_field( context: &RewriteContext<'_>, field: &ast::Field, shape: Shape, @@ -1792,7 +1796,7 @@ fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>( Some(format!("({})", list_str)) } -pub fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>( +pub(crate) fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>( context: &'a RewriteContext<'_>, items: impl Iterator, span: Span, @@ -1827,7 +1831,7 @@ pub fn rewrite_tuple<'a, T: 'a + IntoOverflowableItem<'a>>( } } -pub fn rewrite_unary_prefix( +pub(crate) fn rewrite_unary_prefix( context: &RewriteContext<'_>, prefix: &str, rewrite: &R, @@ -1840,7 +1844,7 @@ pub fn rewrite_unary_prefix( // FIXME: this is probably not correct for multi-line Rewrites. we should // subtract suffix.len() from the last line budget, not the first! -pub fn rewrite_unary_suffix( +pub(crate) fn rewrite_unary_suffix( context: &RewriteContext<'_>, suffix: &str, rewrite: &R, @@ -1885,7 +1889,7 @@ fn rewrite_assignment( /// Controls where to put the rhs. #[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub enum RhsTactics { +pub(crate) enum RhsTactics { /// Use heuristics. Default, /// Put the rhs on the next line if it uses multiple line, without extra indentation. @@ -1894,7 +1898,7 @@ pub enum RhsTactics { // The left hand side must contain everything up to, and including, the // assignment operator. -pub fn rewrite_assign_rhs, R: Rewrite>( +pub(crate) fn rewrite_assign_rhs, R: Rewrite>( context: &RewriteContext<'_>, lhs: S, ex: &R, @@ -1903,7 +1907,7 @@ pub fn rewrite_assign_rhs, R: Rewrite>( rewrite_assign_rhs_with(context, lhs, ex, shape, RhsTactics::Default) } -pub fn rewrite_assign_rhs_with, R: Rewrite>( +pub(crate) fn rewrite_assign_rhs_with, R: Rewrite>( context: &RewriteContext<'_>, lhs: S, ex: &R, @@ -1989,7 +1993,11 @@ fn shape_from_rhs_tactic( } } -pub fn prefer_next_line(orig_rhs: &str, next_line_rhs: &str, rhs_tactics: RhsTactics) -> bool { +pub(crate) fn prefer_next_line( + orig_rhs: &str, + next_line_rhs: &str, + rhs_tactics: RhsTactics, +) -> bool { rhs_tactics == RhsTactics::ForceNextLineWithoutIndent || !next_line_rhs.contains('\n') || count_newlines(orig_rhs) > count_newlines(next_line_rhs) + 1 @@ -2011,7 +2019,7 @@ fn rewrite_expr_addrof( rewrite_unary_prefix(context, operator_str, expr, shape) } -pub fn is_method_call(expr: &ast::Expr) -> bool { +pub(crate) fn is_method_call(expr: &ast::Expr) -> bool { match expr.node { ast::ExprKind::MethodCall(..) => true, ast::ExprKind::AddrOf(_, ref expr) diff --git a/src/formatting.rs b/src/formatting.rs index 3ae73ea1c990..eff7b552fabe 100644 --- a/src/formatting.rs +++ b/src/formatting.rs @@ -353,7 +353,7 @@ pub(crate) struct ReportedErrors { impl ReportedErrors { /// Combine two summaries together. - pub fn add(&mut self, other: &ReportedErrors) { + pub(crate) fn add(&mut self, other: &ReportedErrors) { self.has_operational_errors |= other.has_operational_errors; self.has_parsing_errors |= other.has_parsing_errors; self.has_formatting_errors |= other.has_formatting_errors; diff --git a/src/ignore_path.rs b/src/ignore_path.rs index 844ea427f495..d8974e12b8f5 100644 --- a/src/ignore_path.rs +++ b/src/ignore_path.rs @@ -2,12 +2,12 @@ use ignore::{self, gitignore}; use crate::config::{FileName, IgnoreList}; -pub struct IgnorePathSet { +pub(crate) struct IgnorePathSet { ignore_set: gitignore::Gitignore, } impl IgnorePathSet { - pub fn from_ignore_list(ignore_list: &IgnoreList) -> Result { + pub(crate) fn from_ignore_list(ignore_list: &IgnoreList) -> Result { let mut ignore_builder = gitignore::GitignoreBuilder::new(ignore_list.rustfmt_toml_path()); for ignore_path in ignore_list { @@ -19,7 +19,7 @@ impl IgnorePathSet { }) } - pub fn is_match(&self, file_name: &FileName) -> bool { + pub(crate) fn is_match(&self, file_name: &FileName) -> bool { match file_name { FileName::Stdin => false, FileName::Real(p) => self diff --git a/src/imports.rs b/src/imports.rs index 08647dee490b..1d9eba7b1efc 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -20,12 +20,12 @@ use crate::visitor::FmtVisitor; /// Returns a name imported by a `use` declaration. /// E.g., returns `Ordering` for `std::cmp::Ordering` and `self` for `std::cmp::self`. -pub fn path_to_imported_ident(path: &ast::Path) -> ast::Ident { +pub(crate) fn path_to_imported_ident(path: &ast::Path) -> ast::Ident { path.segments.last().unwrap().ident } impl<'a> FmtVisitor<'a> { - pub fn format_import(&mut self, item: &ast::Item, tree: &ast::UseTree) { + pub(crate) fn format_import(&mut self, item: &ast::Item, tree: &ast::UseTree) { let span = item.span(); let shape = self.shape(); let rw = UseTree::from_ast( @@ -84,7 +84,7 @@ impl<'a> FmtVisitor<'a> { // FIXME we do a lot of allocation to make our own representation. #[derive(Clone, Eq, PartialEq)] -pub enum UseSegment { +pub(crate) enum UseSegment { Ident(String, Option), Slf(Option), Super(Option), @@ -94,11 +94,11 @@ pub enum UseSegment { } #[derive(Clone)] -pub struct UseTree { - pub path: Vec, - pub span: Span, +pub(crate) struct UseTree { + pub(crate) path: Vec, + pub(crate) span: Span, // Comment information within nested use tree. - pub list_item: Option, + pub(crate) list_item: Option, // Additional fields for top level use items. // Should we have another struct for top-level use items rather than reusing this? visibility: Option, @@ -156,7 +156,7 @@ impl UseSegment { } } -pub fn merge_use_trees(use_trees: Vec) -> Vec { +pub(crate) fn merge_use_trees(use_trees: Vec) -> Vec { let mut result = Vec::with_capacity(use_trees.len()); for use_tree in use_trees { if use_tree.has_comment() || use_tree.attrs.is_some() { @@ -229,7 +229,11 @@ impl fmt::Display for UseTree { impl UseTree { // Rewrite use tree with `use ` and a trailing `;`. - pub fn rewrite_top_level(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { + pub(crate) fn rewrite_top_level( + &self, + context: &RewriteContext<'_>, + shape: Shape, + ) -> Option { let vis = self.visibility.as_ref().map_or(Cow::from(""), |vis| { crate::utils::format_visibility(context, &vis) }); @@ -285,7 +289,7 @@ impl UseTree { } } - pub fn from_ast_with_normalization( + pub(crate) fn from_ast_with_normalization( context: &RewriteContext<'_>, item: &ast::Item, ) -> Option { @@ -416,7 +420,7 @@ impl UseTree { } // Do the adjustments that rustfmt does elsewhere to use paths. - pub fn normalize(mut self) -> UseTree { + pub(crate) fn normalize(mut self) -> UseTree { let mut last = self.path.pop().expect("Empty use tree?"); // Hack around borrow checker. let mut normalize_sole_list = false; diff --git a/src/issues.rs b/src/issues.rs index c89469bff794..d369b75541ef 100644 --- a/src/issues.rs +++ b/src/issues.rs @@ -65,14 +65,14 @@ enum IssueClassification { None, } -pub struct BadIssueSeeker { +pub(crate) struct BadIssueSeeker { state: Seeking, report_todo: ReportTactic, report_fixme: ReportTactic, } impl BadIssueSeeker { - pub fn new(report_todo: ReportTactic, report_fixme: ReportTactic) -> BadIssueSeeker { + pub(crate) fn new(report_todo: ReportTactic, report_fixme: ReportTactic) -> BadIssueSeeker { BadIssueSeeker { state: Seeking::Issue { todo_idx: 0, @@ -83,13 +83,13 @@ impl BadIssueSeeker { } } - pub fn is_disabled(&self) -> bool { + pub(crate) fn is_disabled(&self) -> bool { !is_enabled(self.report_todo) && !is_enabled(self.report_fixme) } // Check whether or not the current char is conclusive evidence for an // unnumbered TO-DO or FIX-ME. - pub fn inspect(&mut self, c: char) -> Option { + pub(crate) fn inspect(&mut self, c: char) -> Option { match self.state { Seeking::Issue { todo_idx, diff --git a/src/items.rs b/src/items.rs index c7f95557ea3b..17e67b3f79fb 100644 --- a/src/items.rs +++ b/src/items.rs @@ -157,7 +157,7 @@ enum BodyElement<'a> { } /// Represents a fn's signature. -pub struct FnSig<'a> { +pub(crate) struct FnSig<'a> { decl: &'a ast::FnDecl, generics: &'a ast::Generics, abi: abi::Abi, @@ -169,7 +169,7 @@ pub struct FnSig<'a> { } impl<'a> FnSig<'a> { - pub fn new( + pub(crate) fn new( decl: &'a ast::FnDecl, generics: &'a ast::Generics, vis: ast::Visibility, @@ -186,7 +186,7 @@ impl<'a> FnSig<'a> { } } - pub fn from_method_sig( + pub(crate) fn from_method_sig( method_sig: &'a ast::MethodSig, generics: &'a ast::Generics, ) -> FnSig<'a> { @@ -202,7 +202,7 @@ impl<'a> FnSig<'a> { } } - pub fn from_fn_kind( + pub(crate) fn from_fn_kind( fn_kind: &'a visit::FnKind<'_>, generics: &'a ast::Generics, decl: &'a ast::FnDecl, @@ -287,7 +287,7 @@ impl<'a> FmtVisitor<'a> { } } - pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) { + pub(crate) fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) { let item = Item::from_foreign_mod(fm, span, self.config); self.format_item(&item); } @@ -298,7 +298,7 @@ impl<'a> FmtVisitor<'a> { self.last_pos = item.span.hi(); } - pub fn rewrite_fn( + pub(crate) fn rewrite_fn( &mut self, indent: Indent, ident: ast::Ident, @@ -341,7 +341,7 @@ impl<'a> FmtVisitor<'a> { } } - pub fn rewrite_required_fn( + pub(crate) fn rewrite_required_fn( &mut self, indent: Indent, ident: ast::Ident, @@ -416,19 +416,19 @@ impl<'a> FmtVisitor<'a> { } } - pub fn visit_static(&mut self, static_parts: &StaticParts<'_>) { + pub(crate) fn visit_static(&mut self, static_parts: &StaticParts<'_>) { let rewrite = rewrite_static(&self.get_context(), static_parts, self.block_indent); self.push_rewrite(static_parts.span, rewrite); } - pub fn visit_struct(&mut self, struct_parts: &StructParts<'_>) { + pub(crate) fn visit_struct(&mut self, struct_parts: &StructParts<'_>) { let is_tuple = struct_parts.def.is_tuple(); let rewrite = format_struct(&self.get_context(), struct_parts, self.block_indent, None) .map(|s| if is_tuple { s + ";" } else { s }); self.push_rewrite(struct_parts.span, rewrite); } - pub fn visit_enum( + pub(crate) fn visit_enum( &mut self, ident: ast::Ident, vis: &ast::Visibility, @@ -660,7 +660,7 @@ impl<'a> FmtVisitor<'a> { } } -pub fn format_impl( +pub(crate) fn format_impl( context: &RewriteContext<'_>, item: &ast::Item, offset: Indent, @@ -928,7 +928,7 @@ fn rewrite_trait_ref( )) } -pub struct StructParts<'a> { +pub(crate) struct StructParts<'a> { prefix: &'a str, ident: ast::Ident, vis: &'a ast::Visibility, @@ -953,7 +953,7 @@ impl<'a> StructParts<'a> { } } - pub fn from_item(item: &'a ast::Item) -> Self { + pub(crate) fn from_item(item: &'a ast::Item) -> Self { let (prefix, def, generics) = match item.node { ast::ItemKind::Struct(ref def, ref generics) => ("struct ", def, generics), ast::ItemKind::Union(ref def, ref generics) => ("union ", def, generics), @@ -987,7 +987,7 @@ fn format_struct( } } -pub fn format_trait( +pub(crate) fn format_trait( context: &RewriteContext<'_>, item: &ast::Item, offset: Indent, @@ -1149,7 +1149,7 @@ pub fn format_trait( } } -pub fn format_trait_alias( +pub(crate) fn format_trait_alias( context: &RewriteContext<'_>, ident: ast::Ident, vis: &ast::Visibility, @@ -1191,7 +1191,7 @@ fn format_unit_struct( Some(format!("{}{};", header_str, generics_str)) } -pub fn format_struct_struct( +pub(crate) fn format_struct_struct( context: &RewriteContext<'_>, struct_parts: &StructParts<'_>, fields: &[ast::StructField], @@ -1495,7 +1495,7 @@ fn rewrite_type_item( rewrite_assign_rhs(context, result, rhs, rhs_shape).map(|s| s + ";") } -pub fn rewrite_type_alias( +pub(crate) fn rewrite_type_alias( context: &RewriteContext<'_>, indent: Indent, ident: ast::Ident, @@ -1506,7 +1506,7 @@ pub fn rewrite_type_alias( rewrite_type_item(context, indent, "type", " =", ident, ty, generics, vis) } -pub fn rewrite_existential_type( +pub(crate) fn rewrite_existential_type( context: &RewriteContext<'_>, indent: Indent, ident: ast::Ident, @@ -1533,7 +1533,7 @@ fn type_annotation_spacing(config: &Config) -> (&str, &str) { ) } -pub fn rewrite_struct_field_prefix( +pub(crate) fn rewrite_struct_field_prefix( context: &RewriteContext<'_>, field: &ast::StructField, ) -> Option { @@ -1556,7 +1556,7 @@ impl Rewrite for ast::StructField { } } -pub fn rewrite_struct_field( +pub(crate) fn rewrite_struct_field( context: &RewriteContext<'_>, field: &ast::StructField, shape: Shape, @@ -1620,7 +1620,7 @@ pub fn rewrite_struct_field( combine_strs_with_missing_comments(context, &attrs_str, field_str, missing_span, shape, false) } -pub struct StaticParts<'a> { +pub(crate) struct StaticParts<'a> { prefix: &'a str, vis: &'a ast::Visibility, ident: ast::Ident, @@ -1632,7 +1632,7 @@ pub struct StaticParts<'a> { } impl<'a> StaticParts<'a> { - pub fn from_item(item: &'a ast::Item) -> Self { + pub(crate) fn from_item(item: &'a ast::Item) -> Self { let (prefix, ty, mutability, expr) = match item.node { ast::ItemKind::Static(ref ty, mutability, ref expr) => ("static", ty, mutability, expr), ast::ItemKind::Const(ref ty, ref expr) => { @@ -1652,7 +1652,7 @@ impl<'a> StaticParts<'a> { } } - pub fn from_trait_item(ti: &'a ast::TraitItem) -> Self { + pub(crate) fn from_trait_item(ti: &'a ast::TraitItem) -> Self { let (ty, expr_opt) = match ti.node { ast::TraitItemKind::Const(ref ty, ref expr_opt) => (ty, expr_opt), _ => unreachable!(), @@ -1669,7 +1669,7 @@ impl<'a> StaticParts<'a> { } } - pub fn from_impl_item(ii: &'a ast::ImplItem) -> Self { + pub(crate) fn from_impl_item(ii: &'a ast::ImplItem) -> Self { let (ty, expr) = match ii.node { ast::ImplItemKind::Const(ref ty, ref expr) => (ty, expr), _ => unreachable!(), @@ -1739,7 +1739,7 @@ fn rewrite_static( } } -pub fn rewrite_associated_type( +pub(crate) fn rewrite_associated_type( ident: ast::Ident, ty_opt: Option<&ptr::P>, generics: &ast::Generics, @@ -1775,7 +1775,7 @@ pub fn rewrite_associated_type( } } -pub fn rewrite_existential_impl_type( +pub(crate) fn rewrite_existential_impl_type( context: &RewriteContext<'_>, ident: ast::Ident, generics: &ast::Generics, @@ -1786,7 +1786,7 @@ pub fn rewrite_existential_impl_type( .map(|s| format!("existential {}", s)) } -pub fn rewrite_associated_impl_type( +pub(crate) fn rewrite_associated_impl_type( ident: ast::Ident, defaultness: ast::Defaultness, ty_opt: Option<&ptr::P>, @@ -1922,7 +1922,7 @@ fn rewrite_explicit_self( } } -pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos { +pub(crate) fn span_lo_for_arg(arg: &ast::Arg) -> BytePos { if is_named_arg(arg) { arg.pat.span.lo() } else { @@ -1930,7 +1930,7 @@ pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos { } } -pub fn span_hi_for_arg(context: &RewriteContext<'_>, arg: &ast::Arg) -> BytePos { +pub(crate) fn span_hi_for_arg(context: &RewriteContext<'_>, arg: &ast::Arg) -> BytePos { match arg.ty.node { ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(), ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(), @@ -1938,7 +1938,7 @@ pub fn span_hi_for_arg(context: &RewriteContext<'_>, arg: &ast::Arg) -> BytePos } } -pub fn is_named_arg(arg: &ast::Arg) -> bool { +pub(crate) fn is_named_arg(arg: &ast::Arg) -> bool { if let ast::PatKind::Ident(_, ident, _) = arg.pat.node { ident != symbol::keywords::Invalid.ident() } else { @@ -2245,7 +2245,7 @@ struct WhereClauseOption { } impl WhereClauseOption { - pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption { + fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption { WhereClauseOption { suppress_comma, snuggle, @@ -2253,7 +2253,7 @@ impl WhereClauseOption { } } - pub fn snuggled(current: &str) -> WhereClauseOption { + fn snuggled(current: &str) -> WhereClauseOption { WhereClauseOption { suppress_comma: false, snuggle: last_line_width(current) == 1, @@ -2261,15 +2261,15 @@ impl WhereClauseOption { } } - pub fn suppress_comma(&mut self) { + fn suppress_comma(&mut self) { self.suppress_comma = true } - pub fn compress_where(&mut self) { + fn compress_where(&mut self) { self.compress_where = true } - pub fn snuggle(&mut self) { + fn snuggle(&mut self) { self.snuggle = true } } @@ -2434,7 +2434,11 @@ fn rewrite_generics( overflow::rewrite_with_angle_brackets(context, ident, params, shape, generics.span) } -pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option { +pub(crate) fn generics_shape_from_config( + config: &Config, + shape: Shape, + offset: usize, +) -> Option { match config.indent_style() { IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2), IndentStyle::Block => { @@ -2858,7 +2862,7 @@ impl Rewrite for ast::ForeignItem { } /// Rewrite an inline mod. -pub fn rewrite_mod(context: &RewriteContext<'_>, item: &ast::Item) -> String { +pub(crate) fn rewrite_mod(context: &RewriteContext<'_>, item: &ast::Item) -> String { let mut result = String::with_capacity(32); result.push_str(&*format_visibility(context, &item.vis)); result.push_str("mod "); @@ -2868,7 +2872,10 @@ pub fn rewrite_mod(context: &RewriteContext<'_>, item: &ast::Item) -> String { } /// Rewrite `extern crate foo;` WITHOUT attributes. -pub fn rewrite_extern_crate(context: &RewriteContext<'_>, item: &ast::Item) -> Option { +pub(crate) fn rewrite_extern_crate( + context: &RewriteContext<'_>, + item: &ast::Item, +) -> Option { assert!(is_extern_crate(item)); let new_str = context.snippet(item.span); Some(if contains_comment(new_str) { @@ -2880,21 +2887,21 @@ pub fn rewrite_extern_crate(context: &RewriteContext<'_>, item: &ast::Item) -> O } /// Returns `true` for `mod foo;`, false for `mod foo { .. }`. -pub fn is_mod_decl(item: &ast::Item) -> bool { +pub(crate) fn is_mod_decl(item: &ast::Item) -> bool { match item.node { ast::ItemKind::Mod(ref m) => m.inner.hi() != item.span.hi(), _ => false, } } -pub fn is_use_item(item: &ast::Item) -> bool { +pub(crate) fn is_use_item(item: &ast::Item) -> bool { match item.node { ast::ItemKind::Use(_) => true, _ => false, } } -pub fn is_extern_crate(item: &ast::Item) -> bool { +pub(crate) fn is_extern_crate(item: &ast::Item) -> bool { match item.node { ast::ItemKind::ExternCrate(..) => true, _ => false, diff --git a/src/lib.rs b/src/lib.rs index 788fa1335465..efd88357088b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,5 @@ #![deny(rust_2018_idioms)] +#![warn(unreachable_pub)] #[macro_use] extern crate derive_new; diff --git a/src/lists.rs b/src/lists.rs index 97592f893a52..f57a78f9874e 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -13,7 +13,7 @@ use crate::shape::{Indent, Shape}; use crate::utils::{count_newlines, first_line_width, last_line_width, mk_sp, starts_with_newline}; use crate::visitor::SnippetProvider; -pub struct ListFormatting<'a> { +pub(crate) struct ListFormatting<'a> { tactic: DefinitiveListTactic, separator: &'a str, trailing_separator: SeparatorTactic, @@ -32,7 +32,7 @@ pub struct ListFormatting<'a> { } impl<'a> ListFormatting<'a> { - pub fn new(shape: Shape, config: &'a Config) -> Self { + pub(crate) fn new(shape: Shape, config: &'a Config) -> Self { ListFormatting { tactic: DefinitiveListTactic::Vertical, separator: ",", @@ -47,47 +47,47 @@ impl<'a> ListFormatting<'a> { } } - pub fn tactic(mut self, tactic: DefinitiveListTactic) -> Self { + pub(crate) fn tactic(mut self, tactic: DefinitiveListTactic) -> Self { self.tactic = tactic; self } - pub fn separator(mut self, separator: &'a str) -> Self { + pub(crate) fn separator(mut self, separator: &'a str) -> Self { self.separator = separator; self } - pub fn trailing_separator(mut self, trailing_separator: SeparatorTactic) -> Self { + pub(crate) fn trailing_separator(mut self, trailing_separator: SeparatorTactic) -> Self { self.trailing_separator = trailing_separator; self } - pub fn separator_place(mut self, separator_place: SeparatorPlace) -> Self { + pub(crate) fn separator_place(mut self, separator_place: SeparatorPlace) -> Self { self.separator_place = separator_place; self } - pub fn ends_with_newline(mut self, ends_with_newline: bool) -> Self { + pub(crate) fn ends_with_newline(mut self, ends_with_newline: bool) -> Self { self.ends_with_newline = ends_with_newline; self } - pub fn preserve_newline(mut self, preserve_newline: bool) -> Self { + pub(crate) fn preserve_newline(mut self, preserve_newline: bool) -> Self { self.preserve_newline = preserve_newline; self } - pub fn nested(mut self, nested: bool) -> Self { + pub(crate) fn nested(mut self, nested: bool) -> Self { self.nested = nested; self } - pub fn align_comments(mut self, align_comments: bool) -> Self { + pub(crate) fn align_comments(mut self, align_comments: bool) -> Self { self.align_comments = align_comments; self } - pub fn needs_trailing_separator(&self) -> bool { + pub(crate) fn needs_trailing_separator(&self) -> bool { match self.trailing_separator { // We always put separator in front. SeparatorTactic::Always => true, @@ -106,7 +106,7 @@ impl AsRef for ListItem { } #[derive(PartialEq, Eq, Debug, Copy, Clone)] -pub enum ListItemCommentStyle { +pub(crate) enum ListItemCommentStyle { // Try to keep the comment on the same line with the item. SameLine, // Put the comment on the previous or the next line of the item. @@ -116,20 +116,20 @@ pub enum ListItemCommentStyle { } #[derive(Debug, Clone)] -pub struct ListItem { +pub(crate) struct ListItem { // None for comments mean that they are not present. - pub pre_comment: Option, - pub pre_comment_style: ListItemCommentStyle, + pub(crate) pre_comment: Option, + pub(crate) pre_comment_style: ListItemCommentStyle, // Item should include attributes and doc comments. None indicates a failed // rewrite. - pub item: Option, - pub post_comment: Option, + pub(crate) item: Option, + pub(crate) post_comment: Option, // Whether there is extra whitespace before this item. - pub new_lines: bool, + pub(crate) new_lines: bool, } impl ListItem { - pub fn empty() -> ListItem { + pub(crate) fn empty() -> ListItem { ListItem { pre_comment: None, pre_comment_style: ListItemCommentStyle::None, @@ -139,11 +139,11 @@ impl ListItem { } } - pub fn inner_as_ref(&self) -> &str { + pub(crate) fn inner_as_ref(&self) -> &str { self.item.as_ref().map_or("", |s| s) } - pub fn is_different_group(&self) -> bool { + pub(crate) fn is_different_group(&self) -> bool { self.inner_as_ref().contains('\n') || self.pre_comment.is_some() || self @@ -152,7 +152,7 @@ impl ListItem { .map_or(false, |s| s.contains('\n')) } - pub fn is_multiline(&self) -> bool { + pub(crate) fn is_multiline(&self) -> bool { self.inner_as_ref().contains('\n') || self .pre_comment @@ -164,7 +164,7 @@ impl ListItem { .map_or(false, |s| s.contains('\n')) } - pub fn has_single_line_comment(&self) -> bool { + pub(crate) fn has_single_line_comment(&self) -> bool { self.pre_comment .as_ref() .map_or(false, |comment| comment.trim_start().starts_with("//")) @@ -174,11 +174,11 @@ impl ListItem { .map_or(false, |comment| comment.trim_start().starts_with("//")) } - pub fn has_comment(&self) -> bool { + pub(crate) fn has_comment(&self) -> bool { self.pre_comment.is_some() || self.post_comment.is_some() } - pub fn from_str>(s: S) -> ListItem { + pub(crate) fn from_str>(s: S) -> ListItem { ListItem { pre_comment: None, pre_comment_style: ListItemCommentStyle::None, @@ -203,13 +203,13 @@ impl ListItem { /// The type of separator for lists. #[derive(Copy, Clone, Eq, PartialEq, Debug)] -pub enum Separator { +pub(crate) enum Separator { Comma, VerticalBar, } impl Separator { - pub fn len(self) -> usize { + pub(crate) fn len(self) -> usize { match self { // 2 = `, ` Separator::Comma => 2, @@ -219,7 +219,7 @@ impl Separator { } } -pub fn definitive_tactic( +pub(crate) fn definitive_tactic( items: I, tactic: ListTactic, sep: Separator, @@ -260,7 +260,7 @@ where } // Format a list of commented items into a string. -pub fn write_list(items: I, formatting: &ListFormatting<'_>) -> Option +pub(crate) fn write_list(items: I, formatting: &ListFormatting<'_>) -> Option where I: IntoIterator + Clone, T: AsRef, @@ -556,7 +556,7 @@ fn post_comment_alignment(item_max_width: Option, inner_item_len: usize) item_max_width.unwrap_or(0).saturating_sub(inner_item_len) } -pub struct ListItems<'a, I, F1, F2, F3> +pub(crate) struct ListItems<'a, I, F1, F2, F3> where I: Iterator, { @@ -572,7 +572,7 @@ where leave_last: bool, } -pub fn extract_pre_comment(pre_snippet: &str) -> (Option, ListItemCommentStyle) { +pub(crate) fn extract_pre_comment(pre_snippet: &str) -> (Option, ListItemCommentStyle) { let trimmed_pre_snippet = pre_snippet.trim(); let has_block_comment = trimmed_pre_snippet.ends_with("*/"); let has_single_line_comment = trimmed_pre_snippet.starts_with("//"); @@ -599,7 +599,7 @@ pub fn extract_pre_comment(pre_snippet: &str) -> (Option, ListItemCommen } } -pub fn extract_post_comment( +pub(crate) fn extract_post_comment( post_snippet: &str, comment_end: usize, separator: &str, @@ -629,7 +629,7 @@ pub fn extract_post_comment( } } -pub fn get_comment_end( +pub(crate) fn get_comment_end( post_snippet: &str, separator: &str, terminator: &str, @@ -682,7 +682,7 @@ pub fn get_comment_end( // Account for extra whitespace between items. This is fiddly // because of the way we divide pre- and post- comments. -pub fn has_extra_newline(post_snippet: &str, comment_end: usize) -> bool { +pub(crate) fn has_extra_newline(post_snippet: &str, comment_end: usize) -> bool { if post_snippet.is_empty() || comment_end == 0 { return false; } @@ -764,7 +764,7 @@ where #[allow(clippy::too_many_arguments)] // Creates an iterator over a list's items with associated comments. -pub fn itemize_list<'a, T, I, F1, F2, F3>( +pub(crate) fn itemize_list<'a, T, I, F1, F2, F3>( snippet_provider: &'a SnippetProvider<'_>, inner: I, terminator: &'a str, @@ -808,7 +808,7 @@ where .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l)) } -pub fn total_item_width(item: &ListItem) -> usize { +pub(crate) fn total_item_width(item: &ListItem) -> usize { comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..])) + comment_len(item.post_comment.as_ref().map(|x| &(*x)[..])) + item.item.as_ref().map_or(0, String::len) @@ -830,7 +830,7 @@ fn comment_len(comment: Option<&str>) -> usize { } // Compute horizontal and vertical shapes for a struct-lit-like thing. -pub fn struct_lit_shape( +pub(crate) fn struct_lit_shape( shape: Shape, context: &RewriteContext<'_>, prefix_width: usize, @@ -859,7 +859,7 @@ pub fn struct_lit_shape( } // Compute the tactic for the internals of a struct-lit-like thing. -pub fn struct_lit_tactic( +pub(crate) fn struct_lit_tactic( h_shape: Option, context: &RewriteContext<'_>, items: &[ListItem], @@ -878,7 +878,7 @@ pub fn struct_lit_tactic( // Given a tactic and possible shapes for horizontal and vertical layout, // come up with the actual shape to use. -pub fn shape_for_tactic( +pub(crate) fn shape_for_tactic( tactic: DefinitiveListTactic, h_shape: Option, v_shape: Shape, @@ -891,7 +891,7 @@ pub fn shape_for_tactic( // Create a ListFormatting object for formatting the internals of a // struct-lit-like thing, that is a series of fields. -pub fn struct_lit_formatting<'a>( +pub(crate) fn struct_lit_formatting<'a>( shape: Shape, tactic: DefinitiveListTactic, context: &'a RewriteContext<'_>, diff --git a/src/macros.rs b/src/macros.rs index 05a70ae9d4ec..478b55b4920c 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -41,7 +41,7 @@ use crate::visitor::FmtVisitor; const FORCED_BRACKET_MACROS: &[&str] = &["vec!"]; #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum MacroPosition { +pub(crate) enum MacroPosition { Item, Statement, Expression, @@ -49,7 +49,7 @@ pub enum MacroPosition { } #[derive(Debug)] -pub enum MacroArg { +pub(crate) enum MacroArg { Expr(ptr::P), Ty(ptr::P), Pat(ptr::P), @@ -201,7 +201,7 @@ impl<'a> Drop for InsideMacroGuard<'a> { } } -pub fn rewrite_macro( +pub(crate) fn rewrite_macro( mac: &ast::Mac, extra_ident: Option, context: &RewriteContext<'_>, @@ -242,7 +242,7 @@ fn check_keyword<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option { None } -pub fn rewrite_macro_inner( +fn rewrite_macro_inner( mac: &ast::Mac, extra_ident: Option, context: &RewriteContext<'_>, @@ -453,7 +453,7 @@ pub fn rewrite_macro_inner( } } -pub fn rewrite_macro_def( +pub(crate) fn rewrite_macro_def( context: &RewriteContext<'_>, shape: Shape, indent: Indent, @@ -736,7 +736,7 @@ struct ParsedMacroArg { } impl ParsedMacroArg { - pub fn rewrite( + fn rewrite( &self, context: &RewriteContext<'_>, shape: Shape, @@ -772,7 +772,7 @@ fn last_tok(tt: &TokenTree) -> Token { } impl MacroArgParser { - pub fn new() -> MacroArgParser { + fn new() -> MacroArgParser { MacroArgParser { lo: BytePos(0), hi: BytePos(0), @@ -932,7 +932,7 @@ impl MacroArgParser { } /// Returns a collection of parsed macro def's arguments. - pub fn parse(mut self, tokens: TokenStream) -> Option> { + fn parse(mut self, tokens: TokenStream) -> Option> { let mut iter = tokens.trees(); while let Some(tok) = iter.next() { @@ -1136,7 +1136,7 @@ fn next_space(tok: &Token) -> SpaceState { /// Tries to convert a macro use into a short hand try expression. Returns `None` /// when the macro is not an instance of `try!` (or parsing the inner expression /// failed). -pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext<'_>) -> Option { +pub(crate) fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext<'_>) -> Option { if &mac.node.path.to_string() == "try" { let ts: TokenStream = mac.node.tts.clone(); let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect()); diff --git a/src/matches.rs b/src/matches.rs index c09949cf2e86..2e2c54776168 100644 --- a/src/matches.rs +++ b/src/matches.rs @@ -24,20 +24,16 @@ use crate::utils::{ /// A simple wrapper type against `ast::Arm`. Used inside `write_list()`. struct ArmWrapper<'a> { - pub arm: &'a ast::Arm, + arm: &'a ast::Arm, /// `true` if the arm is the last one in match expression. Used to decide on whether we should /// add trailing comma to the match arm when `config.trailing_comma() == Never`. - pub is_last: bool, + is_last: bool, /// Holds a byte position of `|` at the beginning of the arm pattern, if available. - pub beginning_vert: Option, + beginning_vert: Option, } impl<'a> ArmWrapper<'a> { - pub fn new( - arm: &'a ast::Arm, - is_last: bool, - beginning_vert: Option, - ) -> ArmWrapper<'a> { + fn new(arm: &'a ast::Arm, is_last: bool, beginning_vert: Option) -> ArmWrapper<'a> { ArmWrapper { arm, is_last, @@ -62,7 +58,7 @@ impl<'a> Rewrite for ArmWrapper<'a> { } } -pub fn rewrite_match( +pub(crate) fn rewrite_match( context: &RewriteContext<'_>, cond: &ast::Expr, arms: &[ast::Arm], diff --git a/src/missed_spans.rs b/src/missed_spans.rs index 0f459571d422..84246e3ed515 100644 --- a/src/missed_spans.rs +++ b/src/missed_spans.rs @@ -34,7 +34,7 @@ impl<'a> FmtVisitor<'a> { self.buffer.is_empty() } - pub fn format_missing(&mut self, end: BytePos) { + pub(crate) fn format_missing(&mut self, end: BytePos) { // HACK(topecongiro): we use `format_missing()` to extract a missing comment between // a macro (or similar) and a trailing semicolon. Here we just try to avoid calling // `format_missing_inner` in the common case where there is no such comment. @@ -50,7 +50,7 @@ impl<'a> FmtVisitor<'a> { self.format_missing_inner(end, |this, last_snippet, _| this.push_str(last_snippet)) } - pub fn format_missing_with_indent(&mut self, end: BytePos) { + pub(crate) fn format_missing_with_indent(&mut self, end: BytePos) { let config = self.config; self.format_missing_inner(end, |this, last_snippet, snippet| { this.push_str(last_snippet.trim_end()); @@ -63,7 +63,7 @@ impl<'a> FmtVisitor<'a> { }) } - pub fn format_missing_no_indent(&mut self, end: BytePos) { + pub(crate) fn format_missing_no_indent(&mut self, end: BytePos) { self.format_missing_inner(end, |this, last_snippet, _| { this.push_str(last_snippet.trim_end()); }) diff --git a/src/modules.rs b/src/modules.rs index 01a0784c6f41..3d009b2098bf 100644 --- a/src/modules.rs +++ b/src/modules.rs @@ -13,7 +13,7 @@ use crate::utils::contains_skip; type FileModMap<'a> = BTreeMap; /// Maps each module to the corresponding file. -pub struct ModResolver<'a, 'b> { +pub(crate) struct ModResolver<'a, 'b> { source_map: &'b source_map::SourceMap, directory: Directory, file_map: FileModMap<'a>, @@ -28,7 +28,7 @@ struct Directory { impl<'a, 'b> ModResolver<'a, 'b> { /// Creates a new `ModResolver`. - pub fn new( + pub(crate) fn new( source_map: &'b source_map::SourceMap, directory_ownership: DirectoryOwnership, is_input_stdin: bool, @@ -45,7 +45,7 @@ impl<'a, 'b> ModResolver<'a, 'b> { } /// Creates a map that maps a file name to the module in AST. - pub fn visit_crate(mut self, krate: &'a ast::Crate) -> Result, String> { + pub(crate) fn visit_crate(mut self, krate: &'a ast::Crate) -> Result, String> { let root_filename = self.source_map.span_to_filename(krate.span); self.directory.path = match root_filename { source_map::FileName::Real(ref path) => path diff --git a/src/overflow.rs b/src/overflow.rs index 8bc32fcbbc88..3fe2a2fd25b4 100644 --- a/src/overflow.rs +++ b/src/overflow.rs @@ -68,7 +68,7 @@ const SPECIAL_ATTR_WHITELIST: &[(&str, usize)] = &[ ]; #[derive(Debug)] -pub enum OverflowableItem<'a> { +pub(crate) enum OverflowableItem<'a> { Expr(&'a ast::Expr), GenericParam(&'a ast::GenericParam), MacroArg(&'a MacroArg), @@ -103,7 +103,7 @@ impl<'a> OverflowableItem<'a> { } } - pub fn map(&self, f: F) -> T + pub(crate) fn map(&self, f: F) -> T where F: Fn(&dyn IntoOverflowableItem<'a>) -> T, { @@ -119,7 +119,7 @@ impl<'a> OverflowableItem<'a> { } } - pub fn is_simple(&self) -> bool { + pub(crate) fn is_simple(&self) -> bool { match self { OverflowableItem::Expr(expr) => is_simple_expr(expr), OverflowableItem::MacroArg(MacroArg::Expr(expr)) => is_simple_expr(expr), @@ -134,7 +134,7 @@ impl<'a> OverflowableItem<'a> { } } - pub fn is_expr(&self) -> bool { + pub(crate) fn is_expr(&self) -> bool { match self { OverflowableItem::Expr(..) => true, OverflowableItem::MacroArg(MacroArg::Expr(..)) => true, @@ -142,7 +142,7 @@ impl<'a> OverflowableItem<'a> { } } - pub fn is_nested_call(&self) -> bool { + pub(crate) fn is_nested_call(&self) -> bool { match self { OverflowableItem::Expr(expr) => is_nested_call(expr), OverflowableItem::MacroArg(MacroArg::Expr(expr)) => is_nested_call(expr), @@ -150,7 +150,7 @@ impl<'a> OverflowableItem<'a> { } } - pub fn to_expr(&self) -> Option<&'a ast::Expr> { + pub(crate) fn to_expr(&self) -> Option<&'a ast::Expr> { match self { OverflowableItem::Expr(expr) => Some(expr), OverflowableItem::MacroArg(macro_arg) => match macro_arg { @@ -161,7 +161,7 @@ impl<'a> OverflowableItem<'a> { } } - pub fn can_be_overflowed(&self, context: &RewriteContext<'_>, len: usize) -> bool { + pub(crate) fn can_be_overflowed(&self, context: &RewriteContext<'_>, len: usize) -> bool { match self { OverflowableItem::Expr(expr) => can_be_overflowed_expr(context, expr, len), OverflowableItem::MacroArg(macro_arg) => match macro_arg { @@ -196,7 +196,7 @@ impl<'a> OverflowableItem<'a> { } } -pub trait IntoOverflowableItem<'a>: Rewrite + Spanned { +pub(crate) trait IntoOverflowableItem<'a>: Rewrite + Spanned { fn into_overflowable_item(&'a self) -> OverflowableItem<'a>; } @@ -240,7 +240,7 @@ macro_rules! impl_into_overflowable_item_for_rustfmt_types { impl_into_overflowable_item_for_ast_node!(Expr, GenericParam, NestedMetaItem, StructField, Ty); impl_into_overflowable_item_for_rustfmt_types!([MacroArg], [SegmentParam, TuplePatField]); -pub fn into_overflowable_list<'a, T>( +pub(crate) fn into_overflowable_list<'a, T>( iter: impl Iterator, ) -> impl Iterator> where @@ -249,7 +249,7 @@ where iter.map(|x| IntoOverflowableItem::into_overflowable_item(x)) } -pub fn rewrite_with_parens<'a, T: 'a + IntoOverflowableItem<'a>>( +pub(crate) fn rewrite_with_parens<'a, T: 'a + IntoOverflowableItem<'a>>( context: &'a RewriteContext<'_>, ident: &'a str, items: impl Iterator, @@ -273,7 +273,7 @@ pub fn rewrite_with_parens<'a, T: 'a + IntoOverflowableItem<'a>>( .rewrite(shape) } -pub fn rewrite_with_angle_brackets<'a, T: 'a + IntoOverflowableItem<'a>>( +pub(crate) fn rewrite_with_angle_brackets<'a, T: 'a + IntoOverflowableItem<'a>>( context: &'a RewriteContext<'_>, ident: &'a str, items: impl Iterator, @@ -295,7 +295,7 @@ pub fn rewrite_with_angle_brackets<'a, T: 'a + IntoOverflowableItem<'a>>( .rewrite(shape) } -pub fn rewrite_with_square_brackets<'a, T: 'a + IntoOverflowableItem<'a>>( +pub(crate) fn rewrite_with_square_brackets<'a, T: 'a + IntoOverflowableItem<'a>>( context: &'a RewriteContext<'_>, name: &'a str, items: impl Iterator, @@ -340,7 +340,7 @@ struct Context<'a> { } impl<'a> Context<'a> { - pub fn new>( + fn new>( context: &'a RewriteContext<'_>, items: impl Iterator, ident: &'a str, @@ -766,7 +766,7 @@ fn no_long_items(list: &[ListItem]) -> bool { } /// In case special-case style is required, returns an offset from which we start horizontal layout. -pub fn maybe_get_args_offset( +pub(crate) fn maybe_get_args_offset( callee_str: &str, args: &[OverflowableItem<'_>], ) -> Option<(bool, usize)> { diff --git a/src/patterns.rs b/src/patterns.rs index 2140b8d870f9..73ff2c0f7ab0 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -30,7 +30,7 @@ use crate::utils::{format_mutability, mk_sp, rewrite_ident}; /// - `[small, ntp]` /// - unary tuple constructor `([small, ntp])` /// - `&[small]` -pub fn is_short_pattern(pat: &ast::Pat, pat_str: &str) -> bool { +pub(crate) fn is_short_pattern(pat: &ast::Pat, pat_str: &str) -> bool { // We also require that the pattern is reasonably 'small' with its literal width. pat_str.len() <= 20 && !pat_str.contains('\n') && is_short_pattern_inner(pat) } @@ -256,7 +256,7 @@ impl Rewrite for FieldPat { } #[derive(Debug)] -pub enum TuplePatField<'a> { +pub(crate) enum TuplePatField<'a> { Pat(&'a ptr::P), Dotdot(Span), } @@ -279,7 +279,7 @@ impl<'a> Spanned for TuplePatField<'a> { } } -pub fn can_be_overflowed_pat( +pub(crate) fn can_be_overflowed_pat( context: &RewriteContext<'_>, pat: &TuplePatField<'_>, len: usize, diff --git a/src/reorder.rs b/src/reorder.rs index 49a4638f33fc..2423fffcbea0 100644 --- a/src/reorder.rs +++ b/src/reorder.rs @@ -272,7 +272,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { /// Visits and format the given items. Items are reordered If they are /// consecutive and reorderable. - pub fn visit_items_with_reordering(&mut self, mut items: &[&ast::Item]) { + pub(crate) fn visit_items_with_reordering(&mut self, mut items: &[&ast::Item]) { while !items.is_empty() { // If the next item is a `use`, `extern crate` or `mod`, then extract it and any // subsequent items that have the same item kind to be reordered within diff --git a/src/rewrite.rs b/src/rewrite.rs index c736c2535a61..9a955dbd91b8 100644 --- a/src/rewrite.rs +++ b/src/rewrite.rs @@ -11,7 +11,7 @@ use crate::shape::Shape; use crate::visitor::SnippetProvider; use crate::FormatReport; -pub trait Rewrite { +pub(crate) trait Rewrite { /// Rewrite self into shape. fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option; } @@ -23,44 +23,44 @@ impl Rewrite for ptr::P { } #[derive(Clone)] -pub struct RewriteContext<'a> { - pub parse_session: &'a ParseSess, - pub source_map: &'a SourceMap, - pub config: &'a Config, - pub inside_macro: RefCell, +pub(crate) struct RewriteContext<'a> { + pub(crate) parse_session: &'a ParseSess, + pub(crate) source_map: &'a SourceMap, + pub(crate) config: &'a Config, + pub(crate) inside_macro: RefCell, // Force block indent style even if we are using visual indent style. - pub use_block: RefCell, + pub(crate) use_block: RefCell, // When `is_if_else_block` is true, unindent the comment on top // of the `else` or `else if`. - pub is_if_else_block: RefCell, + pub(crate) is_if_else_block: RefCell, // When rewriting chain, veto going multi line except the last element - pub force_one_line_chain: RefCell, - pub snippet_provider: &'a SnippetProvider<'a>, + pub(crate) force_one_line_chain: RefCell, + pub(crate) snippet_provider: &'a SnippetProvider<'a>, // Used for `format_snippet` pub(crate) macro_rewrite_failure: RefCell, pub(crate) report: FormatReport, - pub skip_macro_names: RefCell>, + pub(crate) skip_macro_names: RefCell>, } impl<'a> RewriteContext<'a> { - pub fn snippet(&self, span: Span) -> &str { + pub(crate) fn snippet(&self, span: Span) -> &str { self.snippet_provider.span_to_snippet(span).unwrap() } /// Returns `true` if we should use block indent style for rewriting function call. - pub fn use_block_indent(&self) -> bool { + pub(crate) fn use_block_indent(&self) -> bool { self.config.indent_style() == IndentStyle::Block || *self.use_block.borrow() } - pub fn budget(&self, used_width: usize) -> usize { + pub(crate) fn budget(&self, used_width: usize) -> usize { self.config.max_width().saturating_sub(used_width) } - pub fn inside_macro(&self) -> bool { + pub(crate) fn inside_macro(&self) -> bool { *self.inside_macro.borrow() } - pub fn is_if_else_block(&self) -> bool { + pub(crate) fn is_if_else_block(&self) -> bool { *self.is_if_else_block.borrow() } } diff --git a/src/rustfmt_diff.rs b/src/rustfmt_diff.rs index c83eb1080a63..fd332b124036 100644 --- a/src/rustfmt_diff.rs +++ b/src/rustfmt_diff.rs @@ -146,14 +146,14 @@ impl std::str::FromStr for ModifiedLines { // This struct handles writing output to stdout and abstracts away the logic // of printing in color, if it's possible in the executing environment. -pub struct OutputWriter { +pub(crate) struct OutputWriter { terminal: Option>>, } impl OutputWriter { // Create a new OutputWriter instance based on the caller's preference // for colorized output and the capabilities of the terminal. - pub fn new(color: Color) -> Self { + pub(crate) fn new(color: Color) -> Self { if let Some(t) = term::stdout() { if color.use_colored_tty() && t.supports_color() { return OutputWriter { terminal: Some(t) }; @@ -165,7 +165,7 @@ impl OutputWriter { // Write output in the optionally specified color. The output is written // in the specified color if this OutputWriter instance contains a // Terminal in its `terminal` field. - pub fn writeln(&mut self, msg: &str, color: Option) { + pub(crate) fn writeln(&mut self, msg: &str, color: Option) { match &mut self.terminal { Some(ref mut t) => { if let Some(color) = color { @@ -182,7 +182,7 @@ impl OutputWriter { } // Produces a diff between the expected output and actual output of rustfmt. -pub fn make_diff(expected: &str, actual: &str, context_size: usize) -> Vec { +pub(crate) fn make_diff(expected: &str, actual: &str, context_size: usize) -> Vec { let mut line_number = 1; let mut line_number_orig = 1; let mut context_queue: VecDeque<&str> = VecDeque::with_capacity(context_size); @@ -250,7 +250,7 @@ pub fn make_diff(expected: &str, actual: &str, context_size: usize) -> Vec(diff: Vec, get_section_title: F, config: &Config) +pub(crate) fn print_diff(diff: Vec, get_section_title: F, config: &Config) where F: Fn(u32) -> String, { diff --git a/src/shape.rs b/src/shape.rs index 5524a21f4b7f..d8971e05ef93 100644 --- a/src/shape.rs +++ b/src/shape.rs @@ -5,12 +5,12 @@ use std::ops::{Add, Sub}; use crate::Config; #[derive(Copy, Clone, Debug)] -pub struct Indent { +pub(crate) struct Indent { // Width of the block indent, in characters. Must be a multiple of // Config::tab_spaces. - pub block_indent: usize, + pub(crate) block_indent: usize, // Alignment in characters. - pub alignment: usize, + pub(crate) alignment: usize, } // INDENT_BUFFER.len() = 81 @@ -19,14 +19,14 @@ const INDENT_BUFFER: &str = "\n "; impl Indent { - pub fn new(block_indent: usize, alignment: usize) -> Indent { + pub(crate) fn new(block_indent: usize, alignment: usize) -> Indent { Indent { block_indent, alignment, } } - pub fn from_width(config: &Config, width: usize) -> Indent { + pub(crate) fn from_width(config: &Config, width: usize) -> Indent { if config.hard_tabs() { let tab_num = width / config.tab_spaces(); let alignment = width % config.tab_spaces(); @@ -36,23 +36,23 @@ impl Indent { } } - pub fn empty() -> Indent { + pub(crate) fn empty() -> Indent { Indent::new(0, 0) } - pub fn block_only(&self) -> Indent { + pub(crate) fn block_only(&self) -> Indent { Indent { block_indent: self.block_indent, alignment: 0, } } - pub fn block_indent(mut self, config: &Config) -> Indent { + pub(crate) fn block_indent(mut self, config: &Config) -> Indent { self.block_indent += config.tab_spaces(); self } - pub fn block_unindent(mut self, config: &Config) -> Indent { + pub(crate) fn block_unindent(mut self, config: &Config) -> Indent { if self.block_indent < config.tab_spaces() { Indent::new(self.block_indent, 0) } else { @@ -61,15 +61,15 @@ impl Indent { } } - pub fn width(&self) -> usize { + pub(crate) fn width(&self) -> usize { self.block_indent + self.alignment } - pub fn to_string(&self, config: &Config) -> Cow<'static, str> { + pub(crate) fn to_string(&self, config: &Config) -> Cow<'static, str> { self.to_string_inner(config, 1) } - pub fn to_string_with_newline(&self, config: &Config) -> Cow<'static, str> { + pub(crate) fn to_string_with_newline(&self, config: &Config) -> Cow<'static, str> { self.to_string_inner(config, 0) } @@ -137,13 +137,13 @@ impl Sub for Indent { } #[derive(Copy, Clone, Debug)] -pub struct Shape { - pub width: usize, +pub(crate) struct Shape { + pub(crate) width: usize, // The current indentation of code. - pub indent: Indent, + pub(crate) indent: Indent, // Indentation + any already emitted text on the first line of the current // statement. - pub offset: usize, + pub(crate) offset: usize, } impl Shape { @@ -162,7 +162,7 @@ impl Shape { // |<------------>| max width // |<---->| indent // |<--->| width - pub fn legacy(width: usize, indent: Indent) -> Shape { + pub(crate) fn legacy(width: usize, indent: Indent) -> Shape { Shape { width, indent, @@ -170,7 +170,7 @@ impl Shape { } } - pub fn indented(indent: Indent, config: &Config) -> Shape { + pub(crate) fn indented(indent: Indent, config: &Config) -> Shape { Shape { width: config.max_width().saturating_sub(indent.width()), indent, @@ -178,14 +178,14 @@ impl Shape { } } - pub fn with_max_width(&self, config: &Config) -> Shape { + pub(crate) fn with_max_width(&self, config: &Config) -> Shape { Shape { width: config.max_width().saturating_sub(self.indent.width()), ..*self } } - pub fn visual_indent(&self, extra_width: usize) -> Shape { + pub(crate) fn visual_indent(&self, extra_width: usize) -> Shape { let alignment = self.offset + extra_width; Shape { width: self.width, @@ -194,7 +194,7 @@ impl Shape { } } - pub fn block_indent(&self, extra_width: usize) -> Shape { + pub(crate) fn block_indent(&self, extra_width: usize) -> Shape { if self.indent.alignment == 0 { Shape { width: self.width, @@ -210,36 +210,36 @@ impl Shape { } } - pub fn block_left(&self, width: usize) -> Option { + pub(crate) fn block_left(&self, width: usize) -> Option { self.block_indent(width).sub_width(width) } - pub fn add_offset(&self, extra_width: usize) -> Shape { + pub(crate) fn add_offset(&self, extra_width: usize) -> Shape { Shape { offset: self.offset + extra_width, ..*self } } - pub fn block(&self) -> Shape { + pub(crate) fn block(&self) -> Shape { Shape { indent: self.indent.block_only(), ..*self } } - pub fn saturating_sub_width(&self, width: usize) -> Shape { + pub(crate) fn saturating_sub_width(&self, width: usize) -> Shape { self.sub_width(width).unwrap_or(Shape { width: 0, ..*self }) } - pub fn sub_width(&self, width: usize) -> Option { + pub(crate) fn sub_width(&self, width: usize) -> Option { Some(Shape { width: self.width.checked_sub(width)?, ..*self }) } - pub fn shrink_left(&self, width: usize) -> Option { + pub(crate) fn shrink_left(&self, width: usize) -> Option { Some(Shape { width: self.width.checked_sub(width)?, indent: self.indent + width, @@ -247,21 +247,21 @@ impl Shape { }) } - pub fn offset_left(&self, width: usize) -> Option { + pub(crate) fn offset_left(&self, width: usize) -> Option { self.add_offset(width).sub_width(width) } - pub fn used_width(&self) -> usize { + pub(crate) fn used_width(&self) -> usize { self.indent.block_indent + self.offset } - pub fn rhs_overhead(&self, config: &Config) -> usize { + pub(crate) fn rhs_overhead(&self, config: &Config) -> usize { config .max_width() .saturating_sub(self.used_width() + self.width) } - pub fn comment(&self, config: &Config) -> Shape { + pub(crate) fn comment(&self, config: &Config) -> Shape { let width = min( self.width, config.comment_width().saturating_sub(self.indent.width()), @@ -269,7 +269,7 @@ impl Shape { Shape { width, ..*self } } - pub fn to_string_with_newline(&self, config: &Config) -> Cow<'static, str> { + pub(crate) fn to_string_with_newline(&self, config: &Config) -> Cow<'static, str> { let mut offset_indent = self.indent; offset_indent.alignment = self.offset; offset_indent.to_string_inner(config, 0) diff --git a/src/source_file.rs b/src/source_file.rs index 36483146f054..a7e0074cd2f0 100644 --- a/src/source_file.rs +++ b/src/source_file.rs @@ -12,7 +12,7 @@ use crate::rustfmt_diff::{make_diff, print_diff, ModifiedLines}; use crate::formatting::FileRecord; // Append a newline to the end of each file. -pub fn append_newline(s: &mut String) { +pub(crate) fn append_newline(s: &mut String) { s.push_str("\n"); } @@ -38,7 +38,7 @@ where Ok(()) } -pub fn write_file( +pub(crate) fn write_file( source_map: Option<&SourceMap>, filename: &FileName, formatted_text: &str, diff --git a/src/source_map.rs b/src/source_map.rs index db4796eb08e4..757d5f57db3d 100644 --- a/src/source_map.rs +++ b/src/source_map.rs @@ -7,7 +7,7 @@ use crate::comment::FindUncommented; use crate::config::file_lines::LineRange; use crate::visitor::SnippetProvider; -pub trait SpanUtils { +pub(crate) trait SpanUtils { fn span_after(&self, original: Span, needle: &str) -> BytePos; fn span_after_last(&self, original: Span, needle: &str) -> BytePos; fn span_before(&self, original: Span, needle: &str) -> BytePos; @@ -16,7 +16,7 @@ pub trait SpanUtils { fn opt_span_before(&self, original: Span, needle: &str) -> Option; } -pub trait LineRangeUtils { +pub(crate) trait LineRangeUtils { /// Returns the `LineRange` that corresponds to `span` in `self`. /// /// # Panics diff --git a/src/spanned.rs b/src/spanned.rs index 118b84526e7e..6e687a262c6a 100644 --- a/src/spanned.rs +++ b/src/spanned.rs @@ -9,7 +9,7 @@ use crate::macros::MacroArg; use crate::utils::{mk_sp, outer_attributes}; /// Spanned returns a span including attributes, if available. -pub trait Spanned { +pub(crate) trait Spanned { fn span(&self) -> Span; } diff --git a/src/string.rs b/src/string.rs index 14220ba5d797..4898c9e425cc 100644 --- a/src/string.rs +++ b/src/string.rs @@ -11,24 +11,24 @@ use crate::utils::{unicode_str_width, wrap_str}; const MIN_STRING: usize = 10; /// Describes the layout of a piece of text. -pub struct StringFormat<'a> { +pub(crate) struct StringFormat<'a> { /// The opening sequence of characters for the piece of text - pub opener: &'a str, + pub(crate) opener: &'a str, /// The closing sequence of characters for the piece of text - pub closer: &'a str, + pub(crate) closer: &'a str, /// The opening sequence of characters for a line - pub line_start: &'a str, + pub(crate) line_start: &'a str, /// The closing sequence of characters for a line - pub line_end: &'a str, + pub(crate) line_end: &'a str, /// The allocated box to fit the text into - pub shape: Shape, + pub(crate) shape: Shape, /// Trim trailing whitespaces - pub trim_end: bool, - pub config: &'a Config, + pub(crate) trim_end: bool, + pub(crate) config: &'a Config, } impl<'a> StringFormat<'a> { - pub fn new(shape: Shape, config: &'a Config) -> StringFormat<'a> { + pub(crate) fn new(shape: Shape, config: &'a Config) -> StringFormat<'a> { StringFormat { opener: "\"", closer: "\"", @@ -61,7 +61,7 @@ impl<'a> StringFormat<'a> { } } -pub fn rewrite_string<'a>( +pub(crate) fn rewrite_string<'a>( orig: &str, fmt: &StringFormat<'a>, newline_max_chars: usize, diff --git a/src/types.rs b/src/types.rs index 55367805ca31..eb90a67d0dc1 100644 --- a/src/types.rs +++ b/src/types.rs @@ -24,14 +24,14 @@ use crate::utils::{ }; #[derive(Copy, Clone, Debug, Eq, PartialEq)] -pub enum PathContext { +pub(crate) enum PathContext { Expr, Type, Import, } // Does not wrap on simple segments. -pub fn rewrite_path( +pub(crate) fn rewrite_path( context: &RewriteContext<'_>, path_context: PathContext, qself: Option<&ast::QSelf>, @@ -133,7 +133,7 @@ where } #[derive(Debug)] -pub enum SegmentParam<'a> { +pub(crate) enum SegmentParam<'a> { Const(&'a ast::AnonConst), LifeTime(&'a ast::Lifetime), Type(&'a ast::Ty), @@ -827,7 +827,11 @@ fn join_bounds( Some(result) } -pub fn can_be_overflowed_type(context: &RewriteContext<'_>, ty: &ast::Ty, len: usize) -> bool { +pub(crate) fn can_be_overflowed_type( + context: &RewriteContext<'_>, + ty: &ast::Ty, + len: usize, +) -> bool { match ty.node { ast::TyKind::Tup(..) => context.use_block_indent() && len == 1, ast::TyKind::Rptr(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => { diff --git a/src/utils.rs b/src/utils.rs index a1ab5fd5aadd..9a0a29dc5c34 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -17,15 +17,15 @@ use crate::config::{Config, Version}; use crate::rewrite::RewriteContext; use crate::shape::{Indent, Shape}; -pub const DEPR_SKIP_ANNOTATION: &str = "rustfmt_skip"; -pub const SKIP_ANNOTATION: &str = "rustfmt::skip"; +pub(crate) const DEPR_SKIP_ANNOTATION: &str = "rustfmt_skip"; +pub(crate) const SKIP_ANNOTATION: &str = "rustfmt::skip"; -pub fn rewrite_ident<'a>(context: &'a RewriteContext<'_>, ident: ast::Ident) -> &'a str { +pub(crate) fn rewrite_ident<'a>(context: &'a RewriteContext<'_>, ident: ast::Ident) -> &'a str { context.snippet(ident.span) } // Computes the length of a string's last line, minus offset. -pub fn extra_offset(text: &str, shape: Shape) -> usize { +pub(crate) fn extra_offset(text: &str, shape: Shape) -> usize { match text.rfind('\n') { // 1 for newline character Some(idx) => text.len().saturating_sub(idx + 1 + shape.used_width()), @@ -33,7 +33,7 @@ pub fn extra_offset(text: &str, shape: Shape) -> usize { } } -pub fn is_same_visibility(a: &Visibility, b: &Visibility) -> bool { +pub(crate) fn is_same_visibility(a: &Visibility, b: &Visibility) -> bool { match (&a.node, &b.node) { ( VisibilityKind::Restricted { path: p, .. }, @@ -54,7 +54,10 @@ pub fn is_same_visibility(a: &Visibility, b: &Visibility) -> bool { } // Uses Cow to avoid allocating in the common cases. -pub fn format_visibility(context: &RewriteContext<'_>, vis: &Visibility) -> Cow<'static, str> { +pub(crate) fn format_visibility( + context: &RewriteContext<'_>, + vis: &Visibility, +) -> Cow<'static, str> { match vis.node { VisibilityKind::Public => Cow::from("pub "), VisibilityKind::Inherited => Cow::from(""), @@ -78,7 +81,7 @@ pub fn format_visibility(context: &RewriteContext<'_>, vis: &Visibility) -> Cow< } #[inline] -pub fn format_async(is_async: ast::IsAsync) -> &'static str { +pub(crate) fn format_async(is_async: ast::IsAsync) -> &'static str { match is_async { ast::IsAsync::Async { .. } => "async ", ast::IsAsync::NotAsync => "", @@ -86,7 +89,7 @@ pub fn format_async(is_async: ast::IsAsync) -> &'static str { } #[inline] -pub fn format_constness(constness: ast::Constness) -> &'static str { +pub(crate) fn format_constness(constness: ast::Constness) -> &'static str { match constness { ast::Constness::Const => "const ", ast::Constness::NotConst => "", @@ -94,7 +97,7 @@ pub fn format_constness(constness: ast::Constness) -> &'static str { } #[inline] -pub fn format_defaultness(defaultness: ast::Defaultness) -> &'static str { +pub(crate) fn format_defaultness(defaultness: ast::Defaultness) -> &'static str { match defaultness { ast::Defaultness::Default => "default ", ast::Defaultness::Final => "", @@ -102,7 +105,7 @@ pub fn format_defaultness(defaultness: ast::Defaultness) -> &'static str { } #[inline] -pub fn format_unsafety(unsafety: ast::Unsafety) -> &'static str { +pub(crate) fn format_unsafety(unsafety: ast::Unsafety) -> &'static str { match unsafety { ast::Unsafety::Unsafe => "unsafe ", ast::Unsafety::Normal => "", @@ -110,7 +113,7 @@ pub fn format_unsafety(unsafety: ast::Unsafety) -> &'static str { } #[inline] -pub fn format_auto(is_auto: ast::IsAuto) -> &'static str { +pub(crate) fn format_auto(is_auto: ast::IsAuto) -> &'static str { match is_auto { ast::IsAuto::Yes => "auto ", ast::IsAuto::No => "", @@ -118,7 +121,7 @@ pub fn format_auto(is_auto: ast::IsAuto) -> &'static str { } #[inline] -pub fn format_mutability(mutability: ast::Mutability) -> &'static str { +pub(crate) fn format_mutability(mutability: ast::Mutability) -> &'static str { match mutability { ast::Mutability::Mutable => "mut ", ast::Mutability::Immutable => "", @@ -126,7 +129,7 @@ pub fn format_mutability(mutability: ast::Mutability) -> &'static str { } #[inline] -pub fn format_abi(abi: abi::Abi, explicit_abi: bool, is_mod: bool) -> Cow<'static, str> { +pub(crate) fn format_abi(abi: abi::Abi, explicit_abi: bool, is_mod: bool) -> Cow<'static, str> { if abi == abi::Abi::Rust && !is_mod { Cow::from("") } else if abi == abi::Abi::C && !explicit_abi { @@ -138,12 +141,15 @@ pub fn format_abi(abi: abi::Abi, explicit_abi: bool, is_mod: bool) -> Cow<'stati #[inline] // Transform `Vec>` into `Vec<&T>` -pub fn ptr_vec_to_ref_vec(vec: &[ptr::P]) -> Vec<&T> { +pub(crate) fn ptr_vec_to_ref_vec(vec: &[ptr::P]) -> Vec<&T> { vec.iter().map(|x| &**x).collect::>() } #[inline] -pub fn filter_attributes(attrs: &[ast::Attribute], style: ast::AttrStyle) -> Vec { +pub(crate) fn filter_attributes( + attrs: &[ast::Attribute], + style: ast::AttrStyle, +) -> Vec { attrs .iter() .filter(|a| a.style == style) @@ -152,50 +158,50 @@ pub fn filter_attributes(attrs: &[ast::Attribute], style: ast::AttrStyle) -> Vec } #[inline] -pub fn inner_attributes(attrs: &[ast::Attribute]) -> Vec { +pub(crate) fn inner_attributes(attrs: &[ast::Attribute]) -> Vec { filter_attributes(attrs, ast::AttrStyle::Inner) } #[inline] -pub fn outer_attributes(attrs: &[ast::Attribute]) -> Vec { +pub(crate) fn outer_attributes(attrs: &[ast::Attribute]) -> Vec { filter_attributes(attrs, ast::AttrStyle::Outer) } #[inline] -pub fn is_single_line(s: &str) -> bool { +pub(crate) fn is_single_line(s: &str) -> bool { s.chars().find(|&c| c == '\n').is_none() } #[inline] -pub fn first_line_contains_single_line_comment(s: &str) -> bool { +pub(crate) fn first_line_contains_single_line_comment(s: &str) -> bool { s.lines().next().map_or(false, |l| l.contains("//")) } #[inline] -pub fn last_line_contains_single_line_comment(s: &str) -> bool { +pub(crate) fn last_line_contains_single_line_comment(s: &str) -> bool { s.lines().last().map_or(false, |l| l.contains("//")) } #[inline] -pub fn is_attributes_extendable(attrs_str: &str) -> bool { +pub(crate) fn is_attributes_extendable(attrs_str: &str) -> bool { !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str) } // The width of the first line in s. #[inline] -pub fn first_line_width(s: &str) -> usize { +pub(crate) fn first_line_width(s: &str) -> usize { unicode_str_width(s.splitn(2, '\n').next().unwrap_or("")) } // The width of the last line in s. #[inline] -pub fn last_line_width(s: &str) -> usize { +pub(crate) fn last_line_width(s: &str) -> usize { unicode_str_width(s.rsplitn(2, '\n').next().unwrap_or("")) } // The total used width of the last line. #[inline] -pub fn last_line_used_width(s: &str, offset: usize) -> usize { +pub(crate) fn last_line_used_width(s: &str, offset: usize) -> usize { if s.contains('\n') { last_line_width(s) } else { @@ -204,7 +210,7 @@ pub fn last_line_used_width(s: &str, offset: usize) -> usize { } #[inline] -pub fn trimmed_last_line_width(s: &str) -> usize { +pub(crate) fn trimmed_last_line_width(s: &str) -> usize { unicode_str_width(match s.rfind('\n') { Some(n) => s[(n + 1)..].trim(), None => s.trim(), @@ -212,7 +218,7 @@ pub fn trimmed_last_line_width(s: &str) -> usize { } #[inline] -pub fn last_line_extendable(s: &str) -> bool { +pub(crate) fn last_line_extendable(s: &str) -> bool { if s.ends_with("\"#") { return true; } @@ -250,14 +256,14 @@ fn is_skip_nested(meta_item: &NestedMetaItem) -> bool { } #[inline] -pub fn contains_skip(attrs: &[Attribute]) -> bool { +pub(crate) fn contains_skip(attrs: &[Attribute]) -> bool { attrs .iter() .any(|a| a.meta().map_or(false, |a| is_skip(&a))) } #[inline] -pub fn semicolon_for_expr(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool { +pub(crate) fn semicolon_for_expr(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool { match expr.node { ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => { context.config.trailing_semicolon() @@ -267,7 +273,7 @@ pub fn semicolon_for_expr(context: &RewriteContext<'_>, expr: &ast::Expr) -> boo } #[inline] -pub fn semicolon_for_stmt(context: &RewriteContext<'_>, stmt: &ast::Stmt) -> bool { +pub(crate) fn semicolon_for_stmt(context: &RewriteContext<'_>, stmt: &ast::Stmt) -> bool { match stmt.node { ast::StmtKind::Semi(ref expr) => match expr.node { ast::ExprKind::While(..) @@ -285,7 +291,7 @@ pub fn semicolon_for_stmt(context: &RewriteContext<'_>, stmt: &ast::Stmt) -> boo } #[inline] -pub fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> { +pub(crate) fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> { match stmt.node { ast::StmtKind::Expr(ref expr) => Some(expr), _ => None, @@ -293,7 +299,7 @@ pub fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> { } #[inline] -pub fn count_newlines(input: &str) -> usize { +pub(crate) fn count_newlines(input: &str) -> usize { // Using bytes to omit UTF-8 decoding bytecount::count(input.as_bytes(), b'\n') } @@ -306,7 +312,7 @@ macro_rules! source { }; } -pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span { +pub(crate) fn mk_sp(lo: BytePos, hi: BytePos) -> Span { Span::new(lo, hi, NO_EXPANSION) } @@ -340,7 +346,7 @@ macro_rules! skip_out_of_file_lines_range_visitor { // Wraps String in an Option. Returns Some when the string adheres to the // Rewrite constraints defined for the Rewrite trait and None otherwise. -pub fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option { +pub(crate) fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option { if is_valid_str(&filter_normal_code(&s), max_width, shape) { Some(s) } else { @@ -376,7 +382,7 @@ fn is_valid_str(snippet: &str, max_width: usize, shape: Shape) -> bool { } #[inline] -pub fn colon_spaces(config: &Config) -> &'static str { +pub(crate) fn colon_spaces(config: &Config) -> &'static str { let before = config.space_before_colon(); let after = config.space_after_colon(); match (before, after) { @@ -388,7 +394,7 @@ pub fn colon_spaces(config: &Config) -> &'static str { } #[inline] -pub fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr { +pub(crate) fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr { match e.node { ast::ExprKind::Call(ref e, _) | ast::ExprKind::Binary(_, ref e, _) @@ -405,18 +411,18 @@ pub fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr { } #[inline] -pub fn starts_with_newline(s: &str) -> bool { +pub(crate) fn starts_with_newline(s: &str) -> bool { s.starts_with('\n') || s.starts_with("\r\n") } #[inline] -pub fn first_line_ends_with(s: &str, c: char) -> bool { +pub(crate) fn first_line_ends_with(s: &str, c: char) -> bool { s.lines().next().map_or(false, |l| l.ends_with(c)) } // States whether an expression's last line exclusively consists of closing // parens, braces, and brackets in its idiomatic formatting. -pub fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr: &str) -> bool { +pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr: &str) -> bool { match expr.node { ast::ExprKind::Mac(..) | ast::ExprKind::Call(..) @@ -448,7 +454,7 @@ pub fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr: &str) /// Removes trailing spaces from the specified snippet. We do not remove spaces /// inside strings or comments. -pub fn remove_trailing_white_spaces(text: &str) -> String { +pub(crate) fn remove_trailing_white_spaces(text: &str) -> String { let mut buffer = String::with_capacity(text.len()); let mut space_buffer = String::with_capacity(128); for (char_kind, c) in CharClasses::new(text.chars()) { @@ -503,7 +509,11 @@ pub fn remove_trailing_white_spaces(text: &str) -> String { /// ), /// } /// ``` -pub fn trim_left_preserve_layout(orig: &str, indent: Indent, config: &Config) -> Option { +pub(crate) fn trim_left_preserve_layout( + orig: &str, + indent: Indent, + config: &Config, +) -> Option { let mut lines = LineClasses::new(orig); let first_line = lines.next().map(|(_, s)| s.trim_end().to_owned())?; let mut trimmed_lines = Vec::with_capacity(16); @@ -570,12 +580,12 @@ pub fn trim_left_preserve_layout(orig: &str, indent: Indent, config: &Config) -> /// Based on the given line, determine if the next line can be indented or not. /// This allows to preserve the indentation of multi-line literals. -pub fn indent_next_line(kind: FullCodeCharKind, line: &str, config: &Config) -> bool { +pub(crate) fn indent_next_line(kind: FullCodeCharKind, line: &str, config: &Config) -> bool { !(kind.is_string() || (config.version() == Version::Two && kind.is_commented_string())) || line.ends_with('\\') } -pub fn is_empty_line(s: &str) -> bool { +pub(crate) fn is_empty_line(s: &str) -> bool { s.is_empty() || s.chars().all(char::is_whitespace) } @@ -605,7 +615,7 @@ pub(crate) fn unicode_str_width(s: &str) -> usize { s.width() } -pub fn get_skip_macro_names(attrs: &[ast::Attribute]) -> Vec { +pub(crate) fn get_skip_macro_names(attrs: &[ast::Attribute]) -> Vec { let mut skip_macro_names = vec![]; for attr in attrs { // syntax::ast::Path is implemented partialEq diff --git a/src/vertical.rs b/src/vertical.rs index 0b69c3603d47..62cc7d8b33dd 100644 --- a/src/vertical.rs +++ b/src/vertical.rs @@ -19,7 +19,7 @@ use crate::source_map::SpanUtils; use crate::spanned::Spanned; use crate::utils::{contains_skip, is_attributes_extendable, mk_sp, rewrite_ident}; -pub trait AlignedItem { +pub(crate) trait AlignedItem { fn skip(&self) -> bool; fn get_span(&self) -> Span; fn rewrite_prefix(&self, context: &RewriteContext<'_>, shape: Shape) -> Option; @@ -107,7 +107,7 @@ impl AlignedItem for ast::Field { } } -pub fn rewrite_with_alignment( +pub(crate) fn rewrite_with_alignment( fields: &[T], context: &RewriteContext<'_>, shape: Shape, diff --git a/src/visitor.rs b/src/visitor.rs index b1d3b12ea142..f317e0154239 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -27,7 +27,7 @@ use crate::utils::{ use crate::{ErrorKind, FormatReport, FormattingError}; /// Creates a string slice corresponding to the specified span. -pub struct SnippetProvider<'a> { +pub(crate) struct SnippetProvider<'a> { /// A pointer to the content of the file we are formatting. big_snippet: &'a str, /// A position of the start of `big_snippet`, used as an offset. @@ -35,13 +35,13 @@ pub struct SnippetProvider<'a> { } impl<'a> SnippetProvider<'a> { - pub fn span_to_snippet(&self, span: Span) -> Option<&str> { + pub(crate) fn span_to_snippet(&self, span: Span) -> Option<&str> { let start_index = span.lo().to_usize().checked_sub(self.start_pos)?; let end_index = span.hi().to_usize().checked_sub(self.start_pos)?; Some(&self.big_snippet[start_index..end_index]) } - pub fn new(start_pos: BytePos, big_snippet: &'a str) -> Self { + pub(crate) fn new(start_pos: BytePos, big_snippet: &'a str) -> Self { let start_pos = start_pos.to_usize(); SnippetProvider { big_snippet, @@ -50,24 +50,24 @@ impl<'a> SnippetProvider<'a> { } } -pub struct FmtVisitor<'a> { +pub(crate) struct FmtVisitor<'a> { parent_context: Option<&'a RewriteContext<'a>>, - pub parse_session: &'a ParseSess, - pub source_map: &'a SourceMap, - pub buffer: String, - pub last_pos: BytePos, + pub(crate) parse_session: &'a ParseSess, + pub(crate) source_map: &'a SourceMap, + pub(crate) buffer: String, + pub(crate) last_pos: BytePos, // FIXME: use an RAII util or closure for indenting - pub block_indent: Indent, - pub config: &'a Config, - pub is_if_else_block: bool, - pub snippet_provider: &'a SnippetProvider<'a>, - pub line_number: usize, + pub(crate) block_indent: Indent, + pub(crate) config: &'a Config, + pub(crate) is_if_else_block: bool, + pub(crate) snippet_provider: &'a SnippetProvider<'a>, + pub(crate) line_number: usize, /// List of 1-based line ranges which were annotated with skip /// Both bounds are inclusifs. - pub skipped_range: Vec<(usize, usize)>, - pub macro_rewrite_failure: bool, + pub(crate) skipped_range: Vec<(usize, usize)>, + pub(crate) macro_rewrite_failure: bool, pub(crate) report: FormatReport, - pub skip_macro_names: RefCell>, + pub(crate) skip_macro_names: RefCell>, } impl<'a> Drop for FmtVisitor<'a> { @@ -85,7 +85,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { self.parent_context = Some(context); } - pub fn shape(&self) -> Shape { + pub(crate) fn shape(&self) -> Shape { Shape::indented(self.block_indent, self.config) } @@ -124,7 +124,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { } } - pub fn visit_block( + pub(crate) fn visit_block( &mut self, b: &ast::Block, inner_attrs: Option<&[ast::Attribute]>, @@ -300,7 +300,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { self.visit_block(block, inner_attrs, true) } - pub fn visit_item(&mut self, item: &ast::Item) { + pub(crate) fn visit_item(&mut self, item: &ast::Item) { skip_out_of_file_lines_range_visitor!(self, item.span); // This is where we bail out if there is a skip attribute. This is only @@ -466,7 +466,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { self.skip_macro_names = temp_skip_macro_names; } - pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) { + pub(crate) fn visit_trait_item(&mut self, ti: &ast::TraitItem) { skip_out_of_file_lines_range_visitor!(self, ti.span); if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) { @@ -510,7 +510,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { } } - pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) { + pub(crate) fn visit_impl_item(&mut self, ii: &ast::ImplItem) { skip_out_of_file_lines_range_visitor!(self, ii.span); if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) { @@ -567,7 +567,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { self.push_rewrite(mac.span, rewrite); } - pub fn push_str(&mut self, s: &str) { + pub(crate) fn push_str(&mut self, s: &str) { self.line_number += count_newlines(s); self.buffer.push_str(s); } @@ -583,12 +583,12 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { self.last_pos = source!(self, span).hi(); } - pub fn push_rewrite(&mut self, span: Span, rewrite: Option) { + pub(crate) fn push_rewrite(&mut self, span: Span, rewrite: Option) { self.format_missing_with_indent(source!(self, span).lo()); self.push_rewrite_inner(span, rewrite); } - pub fn push_skipped_with_span( + pub(crate) fn push_skipped_with_span( &mut self, attrs: &[ast::Attribute], item_span: Span, @@ -611,7 +611,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { self.skipped_range.push((lo, hi)); } - pub fn from_context(ctx: &'a RewriteContext<'_>) -> FmtVisitor<'a> { + pub(crate) fn from_context(ctx: &'a RewriteContext<'_>) -> FmtVisitor<'a> { let mut visitor = FmtVisitor::from_source_map( ctx.parse_session, ctx.config, @@ -650,16 +650,16 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { } } - pub fn opt_snippet(&'b self, span: Span) -> Option<&'a str> { + pub(crate) fn opt_snippet(&'b self, span: Span) -> Option<&'a str> { self.snippet_provider.span_to_snippet(span) } - pub fn snippet(&'b self, span: Span) -> &'a str { + pub(crate) fn snippet(&'b self, span: Span) -> &'a str { self.opt_snippet(span).unwrap() } // Returns true if we should skip the following item. - pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool { + pub(crate) fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool { for attr in attrs { if attr.name() == DEPR_SKIP_ANNOTATION { let file_name = self.source_map.span_to_filename(attr.span).into(); @@ -810,13 +810,17 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { } } - pub fn format_separate_mod(&mut self, m: &ast::Mod, source_file: &source_map::SourceFile) { + pub(crate) fn format_separate_mod( + &mut self, + m: &ast::Mod, + source_file: &source_map::SourceFile, + ) { self.block_indent = Indent::empty(); self.walk_mod_items(m); self.format_missing_with_indent(source_file.end_pos); } - pub fn skip_empty_lines(&mut self, end_pos: BytePos) { + pub(crate) fn skip_empty_lines(&mut self, end_pos: BytePos) { while let Some(pos) = self .snippet_provider .opt_span_after(mk_sp(self.last_pos, end_pos), "\n") @@ -831,7 +835,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { } } - pub fn with_context(&mut self, f: F) -> Option + pub(crate) fn with_context(&mut self, f: F) -> Option where F: Fn(&RewriteContext<'_>) -> Option, { @@ -847,7 +851,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { result } - pub fn get_context(&self) -> RewriteContext<'_> { + pub(crate) fn get_context(&self) -> RewriteContext<'_> { RewriteContext { parse_session: self.parse_session, source_map: self.source_map,