diff --git a/.cargo/config.toml b/.cargo/config.toml index 3a7caaff78..f88d75d01d 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -33,4 +33,5 @@ rustflags = [ "-Wclippy::rc_buffer", "-Wclippy::rc_mutex", "-Wclippy::rest_pat_in_fully_bound_structs", + "-Wunreachable_pub" ] diff --git a/crates/ruff/src/autofix/actions.rs b/crates/ruff/src/autofix/actions.rs index 2fe97cc40f..b68610588e 100644 --- a/crates/ruff/src/autofix/actions.rs +++ b/crates/ruff/src/autofix/actions.rs @@ -168,7 +168,7 @@ fn is_end_of_file(stmt: &Stmt, locator: &Locator) -> bool { /// remove the entire start and end lines. /// - If the `Stmt` is the last statement in its parent body, replace it with a /// `pass` instead. -pub fn delete_stmt( +pub(crate) fn delete_stmt( stmt: &Stmt, parent: Option<&Stmt>, deleted: &[&Stmt], @@ -205,7 +205,7 @@ pub fn delete_stmt( } /// Generate a `Fix` to remove any unused imports from an `import` statement. -pub fn remove_unused_imports<'a>( +pub(crate) fn remove_unused_imports<'a>( unused_imports: impl Iterator, stmt: &Stmt, parent: Option<&Stmt>, @@ -330,7 +330,7 @@ pub fn remove_unused_imports<'a>( /// /// Supports the removal of parentheses when this is the only (kw)arg left. /// For this behavior, set `remove_parentheses` to `true`. -pub fn remove_argument( +pub(crate) fn remove_argument( locator: &Locator, call_at: TextSize, expr_range: TextRange, @@ -434,7 +434,7 @@ pub fn remove_argument( /// name on which the `lru_cache` symbol would be made available (`"functools.lru_cache"`). /// /// Attempts to reuse existing imports when possible. -pub fn get_or_import_symbol( +pub(crate) fn get_or_import_symbol( module: &str, member: &str, at: TextSize, diff --git a/crates/ruff/src/autofix/mod.rs b/crates/ruff/src/autofix/mod.rs index ac813ec0c7..a82ba1659d 100644 --- a/crates/ruff/src/autofix/mod.rs +++ b/crates/ruff/src/autofix/mod.rs @@ -10,10 +10,13 @@ use ruff_python_ast::source_code::Locator; use crate::linter::FixTable; use crate::registry::{AsRule, Rule}; -pub mod actions; +pub(crate) mod actions; /// Auto-fix errors in a file, and write the fixed source code to disk. -pub fn fix_file(diagnostics: &[Diagnostic], locator: &Locator) -> Option<(String, FixTable)> { +pub(crate) fn fix_file( + diagnostics: &[Diagnostic], + locator: &Locator, +) -> Option<(String, FixTable)> { let mut with_fixes = diagnostics .iter() .filter(|diag| diag.fix.is_some()) diff --git a/crates/ruff/src/checkers/ast/deferred.rs b/crates/ruff/src/checkers/ast/deferred.rs index cefc201419..19bf22736b 100644 --- a/crates/ruff/src/checkers/ast/deferred.rs +++ b/crates/ruff/src/checkers/ast/deferred.rs @@ -7,11 +7,11 @@ use ruff_python_semantic::context::Snapshot; /// Used to, e.g., store functions, whose bodies shouldn't be analyzed until all /// module-level definitions have been analyzed. #[derive(Default)] -pub struct Deferred<'a> { - pub string_type_definitions: Vec<(TextRange, &'a str, Snapshot)>, - pub type_definitions: Vec<(&'a Expr, Snapshot)>, - pub functions: Vec, - pub lambdas: Vec<(&'a Expr, Snapshot)>, - pub for_loops: Vec, - pub assignments: Vec, +pub(crate) struct Deferred<'a> { + pub(crate) string_type_definitions: Vec<(TextRange, &'a str, Snapshot)>, + pub(crate) type_definitions: Vec<(&'a Expr, Snapshot)>, + pub(crate) functions: Vec, + pub(crate) lambdas: Vec<(&'a Expr, Snapshot)>, + pub(crate) for_loops: Vec, + pub(crate) assignments: Vec, } diff --git a/crates/ruff/src/checkers/ast/mod.rs b/crates/ruff/src/checkers/ast/mod.rs index b4f0c7692c..d77b768564 100644 --- a/crates/ruff/src/checkers/ast/mod.rs +++ b/crates/ruff/src/checkers/ast/mod.rs @@ -5628,7 +5628,7 @@ impl<'a> Checker<'a> { } #[allow(clippy::too_many_arguments)] -pub fn check_ast( +pub(crate) fn check_ast( python_ast: &Suite, locator: &Locator, stylist: &Stylist, diff --git a/crates/ruff/src/checkers/filesystem.rs b/crates/ruff/src/checkers/filesystem.rs index 0238b6b894..83df0ba87b 100644 --- a/crates/ruff/src/checkers/filesystem.rs +++ b/crates/ruff/src/checkers/filesystem.rs @@ -7,7 +7,7 @@ use crate::rules::flake8_no_pep420::rules::implicit_namespace_package; use crate::rules::pep8_naming::rules::invalid_module_name; use crate::settings::Settings; -pub fn check_file_path( +pub(crate) fn check_file_path( path: &Path, package: Option<&Path>, settings: &Settings, diff --git a/crates/ruff/src/checkers/imports.rs b/crates/ruff/src/checkers/imports.rs index d8338dd040..31a5ff5f1f 100644 --- a/crates/ruff/src/checkers/imports.rs +++ b/crates/ruff/src/checkers/imports.rs @@ -73,7 +73,7 @@ fn extract_import_map(path: &Path, package: Option<&Path>, blocks: &[&Block]) -> } #[allow(clippy::too_many_arguments)] -pub fn check_imports( +pub(crate) fn check_imports( python_ast: &Suite, locator: &Locator, indexer: &Indexer, diff --git a/crates/ruff/src/checkers/logical_lines.rs b/crates/ruff/src/checkers/logical_lines.rs index 28572f7d91..d9ff322a73 100644 --- a/crates/ruff/src/checkers/logical_lines.rs +++ b/crates/ruff/src/checkers/logical_lines.rs @@ -30,7 +30,7 @@ fn expand_indent(line: &str) -> usize { indent } -pub fn check_logical_lines( +pub(crate) fn check_logical_lines( tokens: &[LexResult], locator: &Locator, stylist: &Stylist, @@ -136,7 +136,7 @@ impl<'a> LogicalLinesContext<'a> { } } - pub fn push>(&mut self, kind: K, range: TextRange) { + pub(crate) fn push>(&mut self, kind: K, range: TextRange) { let kind = kind.into(); if self.settings.rules.enabled(kind.rule()) { self.diagnostics.push(Diagnostic { @@ -148,7 +148,7 @@ impl<'a> LogicalLinesContext<'a> { } } - pub fn push_diagnostic(&mut self, diagnostic: Diagnostic) { + pub(crate) fn push_diagnostic(&mut self, diagnostic: Diagnostic) { if self.settings.rules.enabled(diagnostic.kind.rule()) { self.diagnostics.push(diagnostic); } diff --git a/crates/ruff/src/checkers/mod.rs b/crates/ruff/src/checkers/mod.rs index 13c937dd60..7f3d268c13 100644 --- a/crates/ruff/src/checkers/mod.rs +++ b/crates/ruff/src/checkers/mod.rs @@ -1,8 +1,8 @@ -pub mod ast; -pub mod filesystem; -pub mod imports; +pub(crate) mod ast; +pub(crate) mod filesystem; +pub(crate) mod imports; #[cfg(feature = "logical_lines")] pub(crate) mod logical_lines; -pub mod noqa; -pub mod physical_lines; -pub mod tokens; +pub(crate) mod noqa; +pub(crate) mod physical_lines; +pub(crate) mod tokens; diff --git a/crates/ruff/src/checkers/noqa.rs b/crates/ruff/src/checkers/noqa.rs index 63570167d7..f54b937d32 100644 --- a/crates/ruff/src/checkers/noqa.rs +++ b/crates/ruff/src/checkers/noqa.rs @@ -13,7 +13,7 @@ use crate::rule_redirects::get_redirect_target; use crate::rules::ruff::rules::{UnusedCodes, UnusedNOQA}; use crate::settings::Settings; -pub fn check_noqa( +pub(crate) fn check_noqa( diagnostics: &mut Vec, locator: &Locator, comment_ranges: &[TextRange], diff --git a/crates/ruff/src/checkers/physical_lines.rs b/crates/ruff/src/checkers/physical_lines.rs index a7e87043a8..5712778624 100644 --- a/crates/ruff/src/checkers/physical_lines.rs +++ b/crates/ruff/src/checkers/physical_lines.rs @@ -21,7 +21,7 @@ use crate::rules::pylint; use crate::rules::pyupgrade::rules::unnecessary_coding_comment; use crate::settings::Settings; -pub fn check_physical_lines( +pub(crate) fn check_physical_lines( path: &Path, locator: &Locator, stylist: &Stylist, diff --git a/crates/ruff/src/checkers/tokens.rs b/crates/ruff/src/checkers/tokens.rs index ec9acb37e6..bf52d716ff 100644 --- a/crates/ruff/src/checkers/tokens.rs +++ b/crates/ruff/src/checkers/tokens.rs @@ -14,7 +14,7 @@ use crate::settings::Settings; use ruff_diagnostics::Diagnostic; use ruff_python_ast::source_code::Locator; -pub fn check_tokens( +pub(crate) fn check_tokens( locator: &Locator, tokens: &[LexResult], settings: &Settings, diff --git a/crates/ruff/src/cst/helpers.rs b/crates/ruff/src/cst/helpers.rs index 2235afeb7f..faa0e34535 100644 --- a/crates/ruff/src/cst/helpers.rs +++ b/crates/ruff/src/cst/helpers.rs @@ -16,7 +16,7 @@ fn compose_call_path_inner<'a>(expr: &'a Expression, parts: &mut Vec<&'a str>) { } } -pub fn compose_call_path(expr: &Expression) -> Option { +pub(crate) fn compose_call_path(expr: &Expression) -> Option { let mut segments = vec![]; compose_call_path_inner(expr, &mut segments); if segments.is_empty() { @@ -26,7 +26,7 @@ pub fn compose_call_path(expr: &Expression) -> Option { } } -pub fn compose_module_path(module: &NameOrAttribute) -> String { +pub(crate) fn compose_module_path(module: &NameOrAttribute) -> String { match module { NameOrAttribute::N(name) => name.value.to_string(), NameOrAttribute::A(attr) => { diff --git a/crates/ruff/src/cst/matchers.rs b/crates/ruff/src/cst/matchers.rs index fbebdca0a8..dbabac4c9b 100644 --- a/crates/ruff/src/cst/matchers.rs +++ b/crates/ruff/src/cst/matchers.rs @@ -4,21 +4,21 @@ use libcst_native::{ ImportNames, Module, SimpleString, SmallStatement, Statement, }; -pub fn match_module(module_text: &str) -> Result { +pub(crate) fn match_module(module_text: &str) -> Result { match libcst_native::parse_module(module_text, None) { Ok(module) => Ok(module), Err(_) => bail!("Failed to extract CST from source"), } } -pub fn match_expression(expression_text: &str) -> Result { +pub(crate) fn match_expression(expression_text: &str) -> Result { match libcst_native::parse_expression(expression_text) { Ok(expression) => Ok(expression), Err(_) => bail!("Failed to extract CST from source"), } } -pub fn match_expr<'a, 'b>(module: &'a mut Module<'b>) -> Result<&'a mut Expr<'b>> { +pub(crate) fn match_expr<'a, 'b>(module: &'a mut Module<'b>) -> Result<&'a mut Expr<'b>> { if let Some(Statement::Simple(expr)) = module.body.first_mut() { if let Some(SmallStatement::Expr(expr)) = expr.body.first_mut() { Ok(expr) @@ -30,7 +30,7 @@ pub fn match_expr<'a, 'b>(module: &'a mut Module<'b>) -> Result<&'a mut Expr<'b> } } -pub fn match_import<'a, 'b>(module: &'a mut Module<'b>) -> Result<&'a mut Import<'b>> { +pub(crate) fn match_import<'a, 'b>(module: &'a mut Module<'b>) -> Result<&'a mut Import<'b>> { if let Some(Statement::Simple(expr)) = module.body.first_mut() { if let Some(SmallStatement::Import(expr)) = expr.body.first_mut() { Ok(expr) @@ -42,7 +42,9 @@ pub fn match_import<'a, 'b>(module: &'a mut Module<'b>) -> Result<&'a mut Import } } -pub fn match_import_from<'a, 'b>(module: &'a mut Module<'b>) -> Result<&'a mut ImportFrom<'b>> { +pub(crate) fn match_import_from<'a, 'b>( + module: &'a mut Module<'b>, +) -> Result<&'a mut ImportFrom<'b>> { if let Some(Statement::Simple(expr)) = module.body.first_mut() { if let Some(SmallStatement::ImportFrom(expr)) = expr.body.first_mut() { Ok(expr) @@ -54,7 +56,7 @@ pub fn match_import_from<'a, 'b>(module: &'a mut Module<'b>) -> Result<&'a mut I } } -pub fn match_aliases<'a, 'b>( +pub(crate) fn match_aliases<'a, 'b>( import_from: &'a mut ImportFrom<'b>, ) -> Result<&'a mut Vec>> { if let ImportNames::Aliases(aliases) = &mut import_from.names { @@ -64,7 +66,7 @@ pub fn match_aliases<'a, 'b>( } } -pub fn match_call<'a, 'b>(expression: &'a mut Expression<'b>) -> Result<&'a mut Call<'b>> { +pub(crate) fn match_call<'a, 'b>(expression: &'a mut Expression<'b>) -> Result<&'a mut Call<'b>> { if let Expression::Call(call) = expression { Ok(call) } else { @@ -72,7 +74,7 @@ pub fn match_call<'a, 'b>(expression: &'a mut Expression<'b>) -> Result<&'a mut } } -pub fn match_comparison<'a, 'b>( +pub(crate) fn match_comparison<'a, 'b>( expression: &'a mut Expression<'b>, ) -> Result<&'a mut Comparison<'b>> { if let Expression::Comparison(comparison) = expression { @@ -82,7 +84,7 @@ pub fn match_comparison<'a, 'b>( } } -pub fn match_dict<'a, 'b>(expression: &'a mut Expression<'b>) -> Result<&'a mut Dict<'b>> { +pub(crate) fn match_dict<'a, 'b>(expression: &'a mut Expression<'b>) -> Result<&'a mut Dict<'b>> { if let Expression::Dict(dict) = expression { Ok(dict) } else { @@ -90,7 +92,7 @@ pub fn match_dict<'a, 'b>(expression: &'a mut Expression<'b>) -> Result<&'a mut } } -pub fn match_attribute<'a, 'b>( +pub(crate) fn match_attribute<'a, 'b>( expression: &'a mut Expression<'b>, ) -> Result<&'a mut Attribute<'b>> { if let Expression::Attribute(attribute) = expression { @@ -100,7 +102,7 @@ pub fn match_attribute<'a, 'b>( } } -pub fn match_simple_string<'a, 'b>( +pub(crate) fn match_simple_string<'a, 'b>( expression: &'a mut Expression<'b>, ) -> Result<&'a mut SimpleString<'b>> { if let Expression::SimpleString(simple_string) = expression { diff --git a/crates/ruff/src/cst/mod.rs b/crates/ruff/src/cst/mod.rs index d4cf6cc5d7..9060c74698 100644 --- a/crates/ruff/src/cst/mod.rs +++ b/crates/ruff/src/cst/mod.rs @@ -1,2 +1,2 @@ -pub mod helpers; -pub mod matchers; +pub(crate) mod helpers; +pub(crate) mod matchers; diff --git a/crates/ruff/src/doc_lines.rs b/crates/ruff/src/doc_lines.rs index e564f11df8..e506c05e55 100644 --- a/crates/ruff/src/doc_lines.rs +++ b/crates/ruff/src/doc_lines.rs @@ -13,11 +13,14 @@ use ruff_python_ast::source_code::Locator; use ruff_python_ast::statement_visitor::{walk_stmt, StatementVisitor}; /// Extract doc lines (standalone comments) from a token sequence. -pub fn doc_lines_from_tokens<'a>(lxr: &'a [LexResult], locator: &'a Locator<'a>) -> DocLines<'a> { +pub(crate) fn doc_lines_from_tokens<'a>( + lxr: &'a [LexResult], + locator: &'a Locator<'a>, +) -> DocLines<'a> { DocLines::new(lxr, locator) } -pub struct DocLines<'a> { +pub(crate) struct DocLines<'a> { inner: std::iter::Flatten>, locator: &'a Locator<'a>, prev: TextSize, @@ -104,7 +107,7 @@ impl<'a> StringLinesVisitor<'a> { } /// Extract doc lines (standalone strings) start positions from an AST. -pub fn doc_lines_from_ast(python_ast: &Suite, locator: &Locator) -> Vec { +pub(crate) fn doc_lines_from_ast(python_ast: &Suite, locator: &Locator) -> Vec { let mut visitor = StringLinesVisitor::new(locator); visitor.visit_body(python_ast); visitor.string_lines diff --git a/crates/ruff/src/docstrings/mod.rs b/crates/ruff/src/docstrings/mod.rs index aedde3ec2f..e5f8715827 100644 --- a/crates/ruff/src/docstrings/mod.rs +++ b/crates/ruff/src/docstrings/mod.rs @@ -6,67 +6,67 @@ use rustpython_parser::ast::Expr; use ruff_python_semantic::definition::Definition; -pub mod extraction; -pub mod google; -pub mod numpy; -pub mod sections; -pub mod styles; +pub(crate) mod extraction; +pub(crate) mod google; +pub(crate) mod numpy; +pub(crate) mod sections; +pub(crate) mod styles; #[derive(Debug)] -pub struct Docstring<'a> { - pub definition: &'a Definition<'a>, - pub expr: &'a Expr, +pub(crate) struct Docstring<'a> { + pub(crate) definition: &'a Definition<'a>, + pub(crate) expr: &'a Expr, /// The content of the docstring, including the leading and trailing quotes. - pub contents: &'a str, + pub(crate) contents: &'a str, /// The range of the docstring body (without the quotes). The range is relative to [`Self::contents`]. - pub body_range: TextRange, - pub indentation: &'a str, + pub(crate) body_range: TextRange, + pub(crate) indentation: &'a str, } impl<'a> Docstring<'a> { - pub fn body(&self) -> DocstringBody { + pub(crate) fn body(&self) -> DocstringBody { DocstringBody { docstring: self } } - pub const fn start(&self) -> TextSize { + pub(crate) const fn start(&self) -> TextSize { self.expr.start() } - pub const fn end(&self) -> TextSize { + pub(crate) const fn end(&self) -> TextSize { self.expr.end() } - pub const fn range(&self) -> TextRange { + pub(crate) const fn range(&self) -> TextRange { self.expr.range() } - pub fn leading_quote(&self) -> &'a str { + pub(crate) fn leading_quote(&self) -> &'a str { &self.contents[TextRange::up_to(self.body_range.start())] } } #[derive(Copy, Clone)] -pub struct DocstringBody<'a> { +pub(crate) struct DocstringBody<'a> { docstring: &'a Docstring<'a>, } impl<'a> DocstringBody<'a> { #[inline] - pub fn start(self) -> TextSize { + pub(crate) fn start(self) -> TextSize { self.range().start() } #[inline] - pub fn end(self) -> TextSize { + pub(crate) fn end(self) -> TextSize { self.range().end() } - pub fn range(self) -> TextRange { + pub(crate) fn range(self) -> TextRange { self.docstring.body_range + self.docstring.start() } - pub fn as_str(self) -> &'a str { + pub(crate) fn as_str(self) -> &'a str { &self.docstring.contents[self.docstring.body_range] } } diff --git a/crates/ruff/src/docstrings/sections.rs b/crates/ruff/src/docstrings/sections.rs index 7676b58c06..46ad1962a6 100644 --- a/crates/ruff/src/docstrings/sections.rs +++ b/crates/ruff/src/docstrings/sections.rs @@ -137,7 +137,7 @@ pub(crate) struct SectionContexts<'a> { impl<'a> SectionContexts<'a> { /// Extract all `SectionContext` values from a docstring. - pub fn from_docstring(docstring: &'a Docstring<'a>, style: SectionStyle) -> Self { + pub(crate) fn from_docstring(docstring: &'a Docstring<'a>, style: SectionStyle) -> Self { let contents = docstring.body(); let mut contexts = Vec::new(); @@ -190,11 +190,11 @@ impl<'a> SectionContexts<'a> { } } - pub fn len(&self) -> usize { + pub(crate) fn len(&self) -> usize { self.contexts.len() } - pub fn iter(&self) -> SectionContextsIter { + pub(crate) fn iter(&self) -> SectionContextsIter { SectionContextsIter { docstring_body: self.docstring.body(), inner: self.contexts.iter(), diff --git a/crates/ruff/src/flake8_to_ruff/parser.rs b/crates/ruff/src/flake8_to_ruff/parser.rs index 3e44adab5a..8e71b8e2ab 100644 --- a/crates/ruff/src/flake8_to_ruff/parser.rs +++ b/crates/ruff/src/flake8_to_ruff/parser.rs @@ -13,7 +13,7 @@ static COMMA_SEPARATED_LIST_RE: Lazy = Lazy::new(|| Regex::new(r"[,\s]"). /// Parse a comma-separated list of `RuleSelector` values (e.g., /// "F401,E501"). -pub fn parse_prefix_codes(value: &str) -> Vec { +pub(crate) fn parse_prefix_codes(value: &str) -> Vec { let mut codes: Vec = vec![]; for code in COMMA_SEPARATED_LIST_RE.split(value) { let code = code.trim(); @@ -30,7 +30,7 @@ pub fn parse_prefix_codes(value: &str) -> Vec { } /// Parse a comma-separated list of strings (e.g., "__init__.py,__main__.py"). -pub fn parse_strings(value: &str) -> Vec { +pub(crate) fn parse_strings(value: &str) -> Vec { COMMA_SEPARATED_LIST_RE .split(value) .map(str::trim) @@ -40,7 +40,7 @@ pub fn parse_strings(value: &str) -> Vec { } /// Parse a boolean. -pub fn parse_bool(value: &str) -> Result { +pub(crate) fn parse_bool(value: &str) -> Result { match value.trim() { "true" => Ok(true), "false" => Ok(false), @@ -138,7 +138,7 @@ fn tokenize_files_to_codes_mapping(value: &str) -> Vec { /// Parse a 'files-to-codes' mapping, mimicking Flake8's internal logic. /// See: -pub fn parse_files_to_codes_mapping(value: &str) -> Result> { +pub(crate) fn parse_files_to_codes_mapping(value: &str) -> Result> { if value.trim().is_empty() { return Ok(vec![]); } @@ -178,7 +178,7 @@ pub fn parse_files_to_codes_mapping(value: &str) -> Result, ) -> FxHashMap> { let mut per_file_ignores: FxHashMap> = FxHashMap::default(); diff --git a/crates/ruff/src/flake8_to_ruff/plugin.rs b/crates/ruff/src/flake8_to_ruff/plugin.rs index 93e39d6b03..77f6645d29 100644 --- a/crates/ruff/src/flake8_to_ruff/plugin.rs +++ b/crates/ruff/src/flake8_to_ruff/plugin.rs @@ -175,7 +175,7 @@ impl From<&Plugin> for Linter { /// /// For example, if the user specified a `mypy-init-return` setting, we should /// infer that `flake8-annotations` is active. -pub fn infer_plugins_from_options(flake8: &HashMap>) -> Vec { +pub(crate) fn infer_plugins_from_options(flake8: &HashMap>) -> Vec { let mut plugins = BTreeSet::new(); for key in flake8.keys() { match key.as_str() { @@ -292,7 +292,7 @@ pub fn infer_plugins_from_options(flake8: &HashMap>) -> V /// /// For example, if the user ignores `ANN101`, we should infer that /// `flake8-annotations` is active. -pub fn infer_plugins_from_codes(selectors: &HashSet) -> Vec { +pub(crate) fn infer_plugins_from_codes(selectors: &HashSet) -> Vec { // Ignore cases in which we've knowingly changed rule prefixes. [ Plugin::Flake82020, diff --git a/crates/ruff/src/lex/docstring_detection.rs b/crates/ruff/src/lex/docstring_detection.rs index 09956511b4..89a7d0825e 100644 --- a/crates/ruff/src/lex/docstring_detection.rs +++ b/crates/ruff/src/lex/docstring_detection.rs @@ -25,13 +25,13 @@ enum State { } #[derive(Default)] -pub struct StateMachine { +pub(crate) struct StateMachine { state: State, bracket_count: usize, } impl StateMachine { - pub fn consume(&mut self, tok: &Tok) -> bool { + pub(crate) fn consume(&mut self, tok: &Tok) -> bool { match tok { Tok::NonLogicalNewline | Tok::Newline diff --git a/crates/ruff/src/lex/mod.rs b/crates/ruff/src/lex/mod.rs index e2b4c3e5a0..c6673c215d 100644 --- a/crates/ruff/src/lex/mod.rs +++ b/crates/ruff/src/lex/mod.rs @@ -1 +1 @@ -pub mod docstring_detection; +pub(crate) mod docstring_detection; diff --git a/crates/ruff/src/message/diff.rs b/crates/ruff/src/message/diff.rs index bdc0eb9a18..d3c56d7d24 100644 --- a/crates/ruff/src/message/diff.rs +++ b/crates/ruff/src/message/diff.rs @@ -21,7 +21,7 @@ pub(super) struct Diff<'a> { } impl<'a> Diff<'a> { - pub fn from_message(message: &'a Message) -> Option { + pub(crate) fn from_message(message: &'a Message) -> Option { message.fix.as_ref().map(|fix| Diff { source_code: &message.file, fix, diff --git a/crates/ruff/src/message/text.rs b/crates/ruff/src/message/text.rs index d9c73abfaf..252e049bc1 100644 --- a/crates/ruff/src/message/text.rs +++ b/crates/ruff/src/message/text.rs @@ -113,8 +113,8 @@ impl Emitter for TextEmitter { } pub(super) struct RuleCodeAndBody<'a> { - pub message: &'a Message, - pub show_fix_status: bool, + pub(crate) message: &'a Message, + pub(crate) show_fix_status: bool, } impl Display for RuleCodeAndBody<'_> { @@ -141,7 +141,7 @@ impl Display for RuleCodeAndBody<'_> { } pub(super) struct MessageCodeFrame<'a> { - pub message: &'a Message, + pub(crate) message: &'a Message, } impl Display for MessageCodeFrame<'_> { diff --git a/crates/ruff/src/noqa.rs b/crates/ruff/src/noqa.rs index 4434837f01..808ea4ee19 100644 --- a/crates/ruff/src/noqa.rs +++ b/crates/ruff/src/noqa.rs @@ -27,7 +27,7 @@ static NOQA_LINE_REGEX: Lazy = Lazy::new(|| { static SPLIT_COMMA_REGEX: Lazy = Lazy::new(|| Regex::new(r"[,\s]").unwrap()); #[derive(Debug)] -pub enum Directive<'a> { +pub(crate) enum Directive<'a> { None, // (leading spaces, noqa_range, trailing_spaces) All(TextSize, TextRange, TextSize), @@ -36,7 +36,7 @@ pub enum Directive<'a> { } /// Extract the noqa `Directive` from a line of Python source code. -pub fn extract_noqa_directive<'a>(range: TextRange, locator: &'a Locator) -> Directive<'a> { +pub(crate) fn extract_noqa_directive<'a>(range: TextRange, locator: &'a Locator) -> Directive<'a> { let text = &locator.contents()[range]; match NOQA_LINE_REGEX.captures(text) { Some(caps) => match ( @@ -123,7 +123,7 @@ fn parse_file_exemption(line: &str) -> ParsedExemption { /// Returns `true` if the string list of `codes` includes `code` (or an alias /// thereof). -pub fn includes(needle: Rule, haystack: &[&str]) -> bool { +pub(crate) fn includes(needle: Rule, haystack: &[&str]) -> bool { let needle = needle.noqa_code(); haystack .iter() @@ -131,7 +131,7 @@ pub fn includes(needle: Rule, haystack: &[&str]) -> bool { } /// Returns `true` if the given [`Rule`] is ignored at the specified `lineno`. -pub fn rule_is_ignored( +pub(crate) fn rule_is_ignored( code: Rule, offset: TextSize, noqa_line_for: &NoqaMapping, @@ -146,7 +146,7 @@ pub fn rule_is_ignored( } } -pub enum FileExemption { +pub(crate) enum FileExemption { None, All, Codes(Vec), @@ -154,7 +154,7 @@ pub enum FileExemption { /// Extract the [`FileExemption`] for a given Python source file, enumerating any rules that are /// globally ignored within the file. -pub fn file_exemption(contents: &str, comment_ranges: &[TextRange]) -> FileExemption { +pub(crate) fn file_exemption(contents: &str, comment_ranges: &[TextRange]) -> FileExemption { let mut exempt_codes: Vec = vec![]; for range in comment_ranges { @@ -184,7 +184,7 @@ pub fn file_exemption(contents: &str, comment_ranges: &[TextRange]) -> FileExemp } /// Adds noqa comments to suppress all diagnostics of a file. -pub fn add_noqa( +pub(crate) fn add_noqa( path: &Path, diagnostics: &[Diagnostic], locator: &Locator, @@ -368,9 +368,9 @@ fn push_codes(str: &mut String, codes: impl Iterator) { #[derive(Debug)] pub(crate) struct NoqaDirectiveLine<'a> { // The range of the text line for which the noqa directive applies. - pub range: TextRange, - pub directive: Directive<'a>, - pub matches: Vec, + pub(crate) range: TextRange, + pub(crate) directive: Directive<'a>, + pub(crate) matches: Vec, } #[derive(Debug, Default)] @@ -379,7 +379,10 @@ pub(crate) struct NoqaDirectives<'a> { } impl<'a> NoqaDirectives<'a> { - pub fn from_commented_ranges(comment_ranges: &[TextRange], locator: &'a Locator<'a>) -> Self { + pub(crate) fn from_commented_ranges( + comment_ranges: &[TextRange], + locator: &'a Locator<'a>, + ) -> Self { let mut directives = Vec::new(); for comment_range in comment_ranges { @@ -409,11 +412,11 @@ impl<'a> NoqaDirectives<'a> { Self { inner: directives } } - pub fn find_line_with_directive(&self, offset: TextSize) -> Option<&NoqaDirectiveLine> { + pub(crate) fn find_line_with_directive(&self, offset: TextSize) -> Option<&NoqaDirectiveLine> { self.find_line_index(offset).map(|index| &self.inner[index]) } - pub fn find_line_with_directive_mut( + pub(crate) fn find_line_with_directive_mut( &mut self, offset: TextSize, ) -> Option<&mut NoqaDirectiveLine<'a>> { @@ -438,7 +441,7 @@ impl<'a> NoqaDirectives<'a> { .ok() } - pub fn lines(&self) -> &[NoqaDirectiveLine] { + pub(crate) fn lines(&self) -> &[NoqaDirectiveLine] { &self.inner } } diff --git a/crates/ruff/src/rules/eradicate/detection.rs b/crates/ruff/src/rules/eradicate/detection.rs index 2cff42cd64..71fa7a77b6 100644 --- a/crates/ruff/src/rules/eradicate/detection.rs +++ b/crates/ruff/src/rules/eradicate/detection.rs @@ -31,7 +31,7 @@ static PARTIAL_DICTIONARY_REGEX: Lazy = static PRINT_RETURN_REGEX: Lazy = Lazy::new(|| Regex::new(r"^(print|return)\b\s*").unwrap()); /// Returns `true` if a comment contains Python code. -pub fn comment_contains_code(line: &str, task_tags: &[String]) -> bool { +pub(crate) fn comment_contains_code(line: &str, task_tags: &[String]) -> bool { let line = if let Some(line) = line.trim().strip_prefix('#') { line.trim_start_matches([' ', '#']) } else { diff --git a/crates/ruff/src/rules/eradicate/rules.rs b/crates/ruff/src/rules/eradicate/rules.rs index 62d10c6abd..02b42b1d88 100644 --- a/crates/ruff/src/rules/eradicate/rules.rs +++ b/crates/ruff/src/rules/eradicate/rules.rs @@ -46,7 +46,7 @@ fn is_standalone_comment(line: &str) -> bool { } /// ERA001 -pub fn commented_out_code( +pub(crate) fn commented_out_code( locator: &Locator, range: TextRange, settings: &Settings, diff --git a/crates/ruff/src/rules/flake8_2020/rules.rs b/crates/ruff/src/rules/flake8_2020/rules.rs index 6c7cca5b9a..40fccf8ead 100644 --- a/crates/ruff/src/rules/flake8_2020/rules.rs +++ b/crates/ruff/src/rules/flake8_2020/rules.rs @@ -121,7 +121,7 @@ fn is_sys(checker: &Checker, expr: &Expr, target: &str) -> bool { } /// YTT101, YTT102, YTT301, YTT303 -pub fn subscript(checker: &mut Checker, value: &Expr, slice: &Expr) { +pub(crate) fn subscript(checker: &mut Checker, value: &Expr, slice: &Expr) { if is_sys(checker, value, "version") { match &slice.node { ExprKind::Slice(ast::ExprSlice { @@ -172,7 +172,7 @@ pub fn subscript(checker: &mut Checker, value: &Expr, slice: &Expr) { } /// YTT103, YTT201, YTT203, YTT204, YTT302 -pub fn compare(checker: &mut Checker, left: &Expr, ops: &[Cmpop], comparators: &[Expr]) { +pub(crate) fn compare(checker: &mut Checker, left: &Expr, ops: &[Cmpop], comparators: &[Expr]) { match &left.node { ExprKind::Subscript(ast::ExprSubscript { value, slice, .. }) if is_sys(checker, value, "version_info") => @@ -285,7 +285,7 @@ pub fn compare(checker: &mut Checker, left: &Expr, ops: &[Cmpop], comparators: & } /// YTT202 -pub fn name_or_attribute(checker: &mut Checker, expr: &Expr) { +pub(crate) fn name_or_attribute(checker: &mut Checker, expr: &Expr) { if checker .ctx .resolve_call_path(expr) diff --git a/crates/ruff/src/rules/flake8_annotations/fixes.rs b/crates/ruff/src/rules/flake8_annotations/fixes.rs index 305368ca1f..e0630fb127 100644 --- a/crates/ruff/src/rules/flake8_annotations/fixes.rs +++ b/crates/ruff/src/rules/flake8_annotations/fixes.rs @@ -6,7 +6,11 @@ use ruff_diagnostics::Edit; use ruff_python_ast::source_code::Locator; /// ANN204 -pub fn add_return_annotation(locator: &Locator, stmt: &Stmt, annotation: &str) -> Result { +pub(crate) fn add_return_annotation( + locator: &Locator, + stmt: &Stmt, + annotation: &str, +) -> Result { let contents = &locator.contents()[stmt.range()]; // Find the colon (following the `def` keyword). diff --git a/crates/ruff/src/rules/flake8_annotations/helpers.rs b/crates/ruff/src/rules/flake8_annotations/helpers.rs index 166493cca7..4145c13e72 100644 --- a/crates/ruff/src/rules/flake8_annotations/helpers.rs +++ b/crates/ruff/src/rules/flake8_annotations/helpers.rs @@ -27,7 +27,7 @@ pub(super) fn match_function_def(stmt: &Stmt) -> (&str, &Arguments, Option<&Expr } /// Return the name of the function, if it's overloaded. -pub fn overloaded_name(checker: &Checker, definition: &Definition) -> Option { +pub(crate) fn overloaded_name(checker: &Checker, definition: &Definition) -> Option { if let Definition::Member(Member { kind: MemberKind::Function | MemberKind::NestedFunction | MemberKind::Method, stmt, @@ -47,7 +47,11 @@ pub fn overloaded_name(checker: &Checker, definition: &Definition) -> Option bool { +pub(crate) fn is_overload_impl( + checker: &Checker, + definition: &Definition, + overloaded_name: &str, +) -> bool { if let Definition::Member(Member { kind: MemberKind::Function | MemberKind::NestedFunction | MemberKind::Method, stmt, diff --git a/crates/ruff/src/rules/flake8_annotations/rules.rs b/crates/ruff/src/rules/flake8_annotations/rules.rs index 8f7dd9ce52..5a9f13ff81 100644 --- a/crates/ruff/src/rules/flake8_annotations/rules.rs +++ b/crates/ruff/src/rules/flake8_annotations/rules.rs @@ -446,7 +446,7 @@ fn check_dynamically_typed( } /// Generate flake8-annotation checks for a given `Definition`. -pub fn definition( +pub(crate) fn definition( checker: &Checker, definition: &Definition, visibility: Visibility, diff --git a/crates/ruff/src/rules/flake8_bandit/helpers.rs b/crates/ruff/src/rules/flake8_bandit/helpers.rs index d27842d7cd..be617427f0 100644 --- a/crates/ruff/src/rules/flake8_bandit/helpers.rs +++ b/crates/ruff/src/rules/flake8_bandit/helpers.rs @@ -8,7 +8,7 @@ static PASSWORD_CANDIDATE_REGEX: Lazy = Lazy::new(|| { Regex::new(r"(^|_)(?i)(pas+wo?r?d|pass(phrase)?|pwd|token|secrete?)($|_)").unwrap() }); -pub fn string_literal(expr: &Expr) -> Option<&str> { +pub(crate) fn string_literal(expr: &Expr) -> Option<&str> { match &expr.node { ExprKind::Constant(ast::ExprConstant { value: Constant::Str(string), @@ -18,11 +18,11 @@ pub fn string_literal(expr: &Expr) -> Option<&str> { } } -pub fn matches_password_name(string: &str) -> bool { +pub(crate) fn matches_password_name(string: &str) -> bool { PASSWORD_CANDIDATE_REGEX.is_match(string) } -pub fn is_untyped_exception(type_: Option<&Expr>, checker: &Checker) -> bool { +pub(crate) fn is_untyped_exception(type_: Option<&Expr>, checker: &Checker) -> bool { type_.map_or(true, |type_| { if let ExprKind::Tuple(ast::ExprTuple { elts, .. }) = &type_.node { elts.iter().any(|type_| { diff --git a/crates/ruff/src/rules/flake8_bandit/rules/assert_used.rs b/crates/ruff/src/rules/flake8_bandit/rules/assert_used.rs index 5678602b24..bb6de4211a 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/assert_used.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/assert_used.rs @@ -36,6 +36,6 @@ impl Violation for Assert { } /// S101 -pub fn assert_used(stmt: &Stmt) -> Diagnostic { +pub(crate) fn assert_used(stmt: &Stmt) -> Diagnostic { Diagnostic::new(Assert, TextRange::at(stmt.start(), "assert".text_len())) } diff --git a/crates/ruff/src/rules/flake8_bandit/rules/bad_file_permissions.rs b/crates/ruff/src/rules/flake8_bandit/rules/bad_file_permissions.rs index a1087cac81..ac353f986a 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/bad_file_permissions.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/bad_file_permissions.rs @@ -96,7 +96,7 @@ fn get_int_value(expr: &Expr) -> Option { } /// S103 -pub fn bad_file_permissions( +pub(crate) fn bad_file_permissions( checker: &mut Checker, func: &Expr, args: &[Expr], diff --git a/crates/ruff/src/rules/flake8_bandit/rules/exec_used.rs b/crates/ruff/src/rules/flake8_bandit/rules/exec_used.rs index d6fa50753e..dad79d7eda 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/exec_used.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/exec_used.rs @@ -14,7 +14,7 @@ impl Violation for ExecBuiltin { } /// S102 -pub fn exec_used(expr: &Expr, func: &Expr) -> Option { +pub(crate) fn exec_used(expr: &Expr, func: &Expr) -> Option { let ExprKind::Name(ast::ExprName { id, .. }) = &func.node else { return None; }; diff --git a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_bind_all_interfaces.rs b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_bind_all_interfaces.rs index a74288a841..47057ee468 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_bind_all_interfaces.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_bind_all_interfaces.rs @@ -13,7 +13,7 @@ impl Violation for HardcodedBindAllInterfaces { } /// S104 -pub fn hardcoded_bind_all_interfaces(value: &str, range: TextRange) -> Option { +pub(crate) fn hardcoded_bind_all_interfaces(value: &str, range: TextRange) -> Option { if value == "0.0.0.0" { Some(Diagnostic::new(HardcodedBindAllInterfaces, range)) } else { diff --git a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_default.rs b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_default.rs index 5cf86b8c63..e687306831 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_default.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_default.rs @@ -36,7 +36,7 @@ fn check_password_kwarg(arg: &Arg, default: &Expr) -> Option { } /// S107 -pub fn hardcoded_password_default(arguments: &Arguments) -> Vec { +pub(crate) fn hardcoded_password_default(arguments: &Arguments) -> Vec { let mut diagnostics: Vec = Vec::new(); let defaults_start = diff --git a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_func_arg.rs b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_func_arg.rs index a28cb86b59..4f4b51b3ff 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_func_arg.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_func_arg.rs @@ -22,7 +22,7 @@ impl Violation for HardcodedPasswordFuncArg { } /// S106 -pub fn hardcoded_password_func_arg(keywords: &[Keyword]) -> Vec { +pub(crate) fn hardcoded_password_func_arg(keywords: &[Keyword]) -> Vec { keywords .iter() .filter_map(|keyword| { diff --git a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_string.rs b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_string.rs index 9008123bdd..4d0bbf319f 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_string.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_string.rs @@ -46,7 +46,10 @@ fn password_target(target: &Expr) -> Option<&str> { } /// S105 -pub fn compare_to_hardcoded_password_string(left: &Expr, comparators: &[Expr]) -> Vec { +pub(crate) fn compare_to_hardcoded_password_string( + left: &Expr, + comparators: &[Expr], +) -> Vec { comparators .iter() .filter_map(|comp| { @@ -65,7 +68,10 @@ pub fn compare_to_hardcoded_password_string(left: &Expr, comparators: &[Expr]) - } /// S105 -pub fn assign_hardcoded_password_string(value: &Expr, targets: &[Expr]) -> Option { +pub(crate) fn assign_hardcoded_password_string( + value: &Expr, + targets: &[Expr], +) -> Option { if string_literal(value) .filter(|string| !string.is_empty()) .is_some() diff --git a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_sql_expression.rs b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_sql_expression.rs index 6143453a45..112860e3fa 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_sql_expression.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_sql_expression.rs @@ -92,7 +92,7 @@ fn unparse_string_format_expression(checker: &mut Checker, expr: &Expr) -> Optio } /// S608 -pub fn hardcoded_sql_expression(checker: &mut Checker, expr: &Expr) { +pub(crate) fn hardcoded_sql_expression(checker: &mut Checker, expr: &Expr) { match unparse_string_format_expression(checker, expr) { Some(string) if matches_sql_statement(&string) => { checker diff --git a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_tmp_directory.rs b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_tmp_directory.rs index f99c85f4cc..ad7dfd12b2 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_tmp_directory.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_tmp_directory.rs @@ -20,7 +20,7 @@ impl Violation for HardcodedTempFile { } /// S108 -pub fn hardcoded_tmp_directory( +pub(crate) fn hardcoded_tmp_directory( expr: &Expr, value: &str, prefixes: &[String], diff --git a/crates/ruff/src/rules/flake8_bandit/rules/hashlib_insecure_hash_functions.rs b/crates/ruff/src/rules/flake8_bandit/rules/hashlib_insecure_hash_functions.rs index ee060886e0..7af865a770 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/hashlib_insecure_hash_functions.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/hashlib_insecure_hash_functions.rs @@ -42,7 +42,7 @@ enum HashlibCall { } /// S324 -pub fn hashlib_insecure_hash_functions( +pub(crate) fn hashlib_insecure_hash_functions( checker: &mut Checker, func: &Expr, args: &[Expr], diff --git a/crates/ruff/src/rules/flake8_bandit/rules/jinja2_autoescape_false.rs b/crates/ruff/src/rules/flake8_bandit/rules/jinja2_autoescape_false.rs index 9c1b2ca661..e0ab2d75b4 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/jinja2_autoescape_false.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/jinja2_autoescape_false.rs @@ -30,7 +30,7 @@ impl Violation for Jinja2AutoescapeFalse { } /// S701 -pub fn jinja2_autoescape_false( +pub(crate) fn jinja2_autoescape_false( checker: &mut Checker, func: &Expr, args: &[Expr], diff --git a/crates/ruff/src/rules/flake8_bandit/rules/logging_config_insecure_listen.rs b/crates/ruff/src/rules/flake8_bandit/rules/logging_config_insecure_listen.rs index d838fe9dd1..697d7ebca6 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/logging_config_insecure_listen.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/logging_config_insecure_listen.rs @@ -17,7 +17,7 @@ impl Violation for LoggingConfigInsecureListen { } /// S612 -pub fn logging_config_insecure_listen( +pub(crate) fn logging_config_insecure_listen( checker: &mut Checker, func: &Expr, args: &[Expr], diff --git a/crates/ruff/src/rules/flake8_bandit/rules/mod.rs b/crates/ruff/src/rules/flake8_bandit/rules/mod.rs index aa836f6eba..a7a3f4f92e 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/mod.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/mod.rs @@ -1,35 +1,37 @@ -pub use assert_used::{assert_used, Assert}; -pub use bad_file_permissions::{bad_file_permissions, BadFilePermissions}; -pub use exec_used::{exec_used, ExecBuiltin}; -pub use hardcoded_bind_all_interfaces::{ +pub(crate) use assert_used::{assert_used, Assert}; +pub(crate) use bad_file_permissions::{bad_file_permissions, BadFilePermissions}; +pub(crate) use exec_used::{exec_used, ExecBuiltin}; +pub(crate) use hardcoded_bind_all_interfaces::{ hardcoded_bind_all_interfaces, HardcodedBindAllInterfaces, }; -pub use hardcoded_password_default::{hardcoded_password_default, HardcodedPasswordDefault}; -pub use hardcoded_password_func_arg::{hardcoded_password_func_arg, HardcodedPasswordFuncArg}; -pub use hardcoded_password_string::{ +pub(crate) use hardcoded_password_default::{hardcoded_password_default, HardcodedPasswordDefault}; +pub(crate) use hardcoded_password_func_arg::{ + hardcoded_password_func_arg, HardcodedPasswordFuncArg, +}; +pub(crate) use hardcoded_password_string::{ assign_hardcoded_password_string, compare_to_hardcoded_password_string, HardcodedPasswordString, }; -pub use hardcoded_sql_expression::{hardcoded_sql_expression, HardcodedSQLExpression}; -pub use hardcoded_tmp_directory::{hardcoded_tmp_directory, HardcodedTempFile}; -pub use hashlib_insecure_hash_functions::{ +pub(crate) use hardcoded_sql_expression::{hardcoded_sql_expression, HardcodedSQLExpression}; +pub(crate) use hardcoded_tmp_directory::{hardcoded_tmp_directory, HardcodedTempFile}; +pub(crate) use hashlib_insecure_hash_functions::{ hashlib_insecure_hash_functions, HashlibInsecureHashFunction, }; -pub use jinja2_autoescape_false::{jinja2_autoescape_false, Jinja2AutoescapeFalse}; -pub use logging_config_insecure_listen::{ +pub(crate) use jinja2_autoescape_false::{jinja2_autoescape_false, Jinja2AutoescapeFalse}; +pub(crate) use logging_config_insecure_listen::{ logging_config_insecure_listen, LoggingConfigInsecureListen, }; -pub use request_with_no_cert_validation::{ +pub(crate) use request_with_no_cert_validation::{ request_with_no_cert_validation, RequestWithNoCertValidation, }; -pub use request_without_timeout::{request_without_timeout, RequestWithoutTimeout}; -pub use shell_injection::{ +pub(crate) use request_without_timeout::{request_without_timeout, RequestWithoutTimeout}; +pub(crate) use shell_injection::{ shell_injection, CallWithShellEqualsTrue, StartProcessWithAShell, StartProcessWithNoShell, StartProcessWithPartialPath, SubprocessPopenWithShellEqualsTrue, SubprocessWithoutShellEqualsTrue, }; -pub use snmp_insecure_version::{snmp_insecure_version, SnmpInsecureVersion}; -pub use snmp_weak_cryptography::{snmp_weak_cryptography, SnmpWeakCryptography}; -pub use suspicious_function_call::{ +pub(crate) use snmp_insecure_version::{snmp_insecure_version, SnmpInsecureVersion}; +pub(crate) use snmp_weak_cryptography::{snmp_weak_cryptography, SnmpWeakCryptography}; +pub(crate) use suspicious_function_call::{ suspicious_function_call, SuspiciousEvalUsage, SuspiciousFTPLibUsage, SuspiciousInsecureCipherModeUsage, SuspiciousInsecureCipherUsage, SuspiciousInsecureHashUsage, SuspiciousMarkSafeUsage, SuspiciousMarshalUsage, SuspiciousMktempUsage, @@ -39,9 +41,9 @@ pub use suspicious_function_call::{ SuspiciousXMLExpatReaderUsage, SuspiciousXMLMiniDOMUsage, SuspiciousXMLPullDOMUsage, SuspiciousXMLSaxUsage, }; -pub use try_except_continue::{try_except_continue, TryExceptContinue}; -pub use try_except_pass::{try_except_pass, TryExceptPass}; -pub use unsafe_yaml_load::{unsafe_yaml_load, UnsafeYAMLLoad}; +pub(crate) use try_except_continue::{try_except_continue, TryExceptContinue}; +pub(crate) use try_except_pass::{try_except_pass, TryExceptPass}; +pub(crate) use unsafe_yaml_load::{unsafe_yaml_load, UnsafeYAMLLoad}; mod assert_used; mod bad_file_permissions; diff --git a/crates/ruff/src/rules/flake8_bandit/rules/request_with_no_cert_validation.rs b/crates/ruff/src/rules/flake8_bandit/rules/request_with_no_cert_validation.rs index 6ed0cf8bdd..2dc6b51148 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/request_with_no_cert_validation.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/request_with_no_cert_validation.rs @@ -37,7 +37,7 @@ const HTTPX_METHODS: [&str; 11] = [ ]; /// S501 -pub fn request_with_no_cert_validation( +pub(crate) fn request_with_no_cert_validation( checker: &mut Checker, func: &Expr, args: &[Expr], diff --git a/crates/ruff/src/rules/flake8_bandit/rules/request_without_timeout.rs b/crates/ruff/src/rules/flake8_bandit/rules/request_without_timeout.rs index 9071d17d10..a0fe4f8398 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/request_without_timeout.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/request_without_timeout.rs @@ -27,7 +27,7 @@ impl Violation for RequestWithoutTimeout { const HTTP_VERBS: [&str; 7] = ["get", "options", "head", "post", "put", "patch", "delete"]; /// S113 -pub fn request_without_timeout( +pub(crate) fn request_without_timeout( checker: &mut Checker, func: &Expr, args: &[Expr], diff --git a/crates/ruff/src/rules/flake8_bandit/rules/shell_injection.rs b/crates/ruff/src/rules/flake8_bandit/rules/shell_injection.rs index b035597ceb..324f938e99 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/shell_injection.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/shell_injection.rs @@ -181,7 +181,12 @@ fn try_string_literal(expr: &Expr) -> Option<&str> { } /// S602, S603, S604, S605, S606, S607 -pub fn shell_injection(checker: &mut Checker, func: &Expr, args: &[Expr], keywords: &[Keyword]) { +pub(crate) fn shell_injection( + checker: &mut Checker, + func: &Expr, + args: &[Expr], + keywords: &[Keyword], +) { let call_kind = get_call_kind(func, &checker.ctx); if matches!(call_kind, Some(CallKind::Subprocess)) { diff --git a/crates/ruff/src/rules/flake8_bandit/rules/snmp_insecure_version.rs b/crates/ruff/src/rules/flake8_bandit/rules/snmp_insecure_version.rs index 237ccb9de6..0e11699f7b 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/snmp_insecure_version.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/snmp_insecure_version.rs @@ -18,7 +18,7 @@ impl Violation for SnmpInsecureVersion { } /// S508 -pub fn snmp_insecure_version( +pub(crate) fn snmp_insecure_version( checker: &mut Checker, func: &Expr, args: &[Expr], diff --git a/crates/ruff/src/rules/flake8_bandit/rules/snmp_weak_cryptography.rs b/crates/ruff/src/rules/flake8_bandit/rules/snmp_weak_cryptography.rs index 72a586a8fb..02ddfeffd0 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/snmp_weak_cryptography.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/snmp_weak_cryptography.rs @@ -20,7 +20,7 @@ impl Violation for SnmpWeakCryptography { } /// S509 -pub fn snmp_weak_cryptography( +pub(crate) fn snmp_weak_cryptography( checker: &mut Checker, func: &Expr, args: &[Expr], diff --git a/crates/ruff/src/rules/flake8_bandit/rules/suspicious_function_call.rs b/crates/ruff/src/rules/flake8_bandit/rules/suspicious_function_call.rs index 15d5c753d2..644b7e1957 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/suspicious_function_call.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/suspicious_function_call.rs @@ -220,7 +220,7 @@ impl Violation for SuspiciousFTPLibUsage { } #[derive(Debug, PartialEq, Eq, Clone, Copy)] -pub enum Reason { +pub(crate) enum Reason { Pickle, Marshal, InsecureHash, @@ -250,7 +250,7 @@ struct SuspiciousMembers<'a> { } impl<'a> SuspiciousMembers<'a> { - pub const fn new(members: &'a [&'a [&'a str]], reason: Reason) -> Self { + pub(crate) const fn new(members: &'a [&'a [&'a str]], reason: Reason) -> Self { Self { members, reason } } } @@ -261,7 +261,7 @@ struct SuspiciousModule<'a> { } impl<'a> SuspiciousModule<'a> { - pub const fn new(name: &'a str, reason: Reason) -> Self { + pub(crate) const fn new(name: &'a str, reason: Reason) -> Self { Self { name, reason } } } @@ -465,7 +465,7 @@ const SUSPICIOUS_MODULES: &[SuspiciousModule] = &[ ]; /// S001 -pub fn suspicious_function_call(checker: &mut Checker, expr: &Expr) { +pub(crate) fn suspicious_function_call(checker: &mut Checker, expr: &Expr) { let ExprKind::Call(ast::ExprCall { func, .. }) = &expr.node else { return; }; diff --git a/crates/ruff/src/rules/flake8_bandit/rules/try_except_continue.rs b/crates/ruff/src/rules/flake8_bandit/rules/try_except_continue.rs index 9a48016b75..274e7509ac 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/try_except_continue.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/try_except_continue.rs @@ -17,7 +17,7 @@ impl Violation for TryExceptContinue { } /// S112 -pub fn try_except_continue( +pub(crate) fn try_except_continue( checker: &mut Checker, excepthandler: &Excepthandler, type_: Option<&Expr>, diff --git a/crates/ruff/src/rules/flake8_bandit/rules/try_except_pass.rs b/crates/ruff/src/rules/flake8_bandit/rules/try_except_pass.rs index 3700fe79d7..e56cdf07e5 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/try_except_pass.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/try_except_pass.rs @@ -17,7 +17,7 @@ impl Violation for TryExceptPass { } /// S110 -pub fn try_except_pass( +pub(crate) fn try_except_pass( checker: &mut Checker, excepthandler: &Excepthandler, type_: Option<&Expr>, diff --git a/crates/ruff/src/rules/flake8_bandit/rules/unsafe_yaml_load.rs b/crates/ruff/src/rules/flake8_bandit/rules/unsafe_yaml_load.rs index 45e378a40b..d6f2214d5d 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/unsafe_yaml_load.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/unsafe_yaml_load.rs @@ -31,7 +31,12 @@ impl Violation for UnsafeYAMLLoad { } /// S506 -pub fn unsafe_yaml_load(checker: &mut Checker, func: &Expr, args: &[Expr], keywords: &[Keyword]) { +pub(crate) fn unsafe_yaml_load( + checker: &mut Checker, + func: &Expr, + args: &[Expr], + keywords: &[Keyword], +) { if checker .ctx .resolve_call_path(func) diff --git a/crates/ruff/src/rules/flake8_blind_except/rules.rs b/crates/ruff/src/rules/flake8_blind_except/rules.rs index d975186794..49a3671a84 100644 --- a/crates/ruff/src/rules/flake8_blind_except/rules.rs +++ b/crates/ruff/src/rules/flake8_blind_except/rules.rs @@ -21,7 +21,7 @@ impl Violation for BlindExcept { } /// BLE001 -pub fn blind_except( +pub(crate) fn blind_except( checker: &mut Checker, type_: Option<&Expr>, name: Option<&str>, diff --git a/crates/ruff/src/rules/flake8_boolean_trap/rules.rs b/crates/ruff/src/rules/flake8_boolean_trap/rules.rs index b23df70645..050c37800b 100644 --- a/crates/ruff/src/rules/flake8_boolean_trap/rules.rs +++ b/crates/ruff/src/rules/flake8_boolean_trap/rules.rs @@ -98,7 +98,7 @@ fn add_if_boolean(checker: &mut Checker, arg: &Expr, kind: DiagnosticKind) { } } -pub fn check_positional_boolean_in_def( +pub(crate) fn check_positional_boolean_in_def( checker: &mut Checker, name: &str, decorator_list: &[Expr], @@ -141,7 +141,7 @@ pub fn check_positional_boolean_in_def( } } -pub fn check_boolean_default_value_in_function_definition( +pub(crate) fn check_boolean_default_value_in_function_definition( checker: &mut Checker, name: &str, decorator_list: &[Expr], @@ -162,7 +162,7 @@ pub fn check_boolean_default_value_in_function_definition( } } -pub fn check_boolean_positional_value_in_function_call( +pub(crate) fn check_boolean_positional_value_in_function_call( checker: &mut Checker, args: &[Expr], func: &Expr, diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/abstract_base_class.rs b/crates/ruff/src/rules/flake8_bugbear/rules/abstract_base_class.rs index c87feaeeca..d54ae2265f 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/abstract_base_class.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/abstract_base_class.rs @@ -69,7 +69,7 @@ fn is_empty_body(body: &[Stmt]) -> bool { /// B024 /// B027 -pub fn abstract_base_class( +pub(crate) fn abstract_base_class( checker: &mut Checker, stmt: &Stmt, name: &str, diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/assert_false.rs b/crates/ruff/src/rules/flake8_bugbear/rules/assert_false.rs index 2cfc086886..2352418ad1 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/assert_false.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/assert_false.rs @@ -50,7 +50,7 @@ fn assertion_error(msg: Option<&Expr>) -> Stmt { } /// B011 -pub fn assert_false(checker: &mut Checker, stmt: &Stmt, test: &Expr, msg: Option<&Expr>) { +pub(crate) fn assert_false(checker: &mut Checker, stmt: &Stmt, test: &Expr, msg: Option<&Expr>) { let ExprKind::Constant(ast::ExprConstant { value: Constant::Bool(false), .. diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/assert_raises_exception.rs b/crates/ruff/src/rules/flake8_bugbear/rules/assert_raises_exception.rs index 0ed86ae144..0bba5f8ae6 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/assert_raises_exception.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/assert_raises_exception.rs @@ -6,7 +6,7 @@ use ruff_macros::{derive_message_formats, violation}; use crate::checkers::ast::Checker; #[derive(Debug, PartialEq, Eq)] -pub enum AssertionKind { +pub(crate) enum AssertionKind { AssertRaises, PytestRaises, } @@ -50,7 +50,7 @@ impl Violation for AssertRaisesException { } /// B017 -pub fn assert_raises_exception(checker: &mut Checker, stmt: &Stmt, items: &[Withitem]) { +pub(crate) fn assert_raises_exception(checker: &mut Checker, stmt: &Stmt, items: &[Withitem]) { let Some(item) = items.first() else { return; }; diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/assignment_to_os_environ.rs b/crates/ruff/src/rules/flake8_bugbear/rules/assignment_to_os_environ.rs index 480da29df7..827f0dfd08 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/assignment_to_os_environ.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/assignment_to_os_environ.rs @@ -15,7 +15,7 @@ impl Violation for AssignmentToOsEnviron { } } /// B003 -pub fn assignment_to_os_environ(checker: &mut Checker, targets: &[Expr]) { +pub(crate) fn assignment_to_os_environ(checker: &mut Checker, targets: &[Expr]) { if targets.len() != 1 { return; } diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/cached_instance_method.rs b/crates/ruff/src/rules/flake8_bugbear/rules/cached_instance_method.rs index 0b56a9806f..bfc94a6027 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/cached_instance_method.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/cached_instance_method.rs @@ -29,7 +29,7 @@ fn is_cache_func(checker: &Checker, expr: &Expr) -> bool { } /// B019 -pub fn cached_instance_method(checker: &mut Checker, decorator_list: &[Expr]) { +pub(crate) fn cached_instance_method(checker: &mut Checker, decorator_list: &[Expr]) { if !matches!(checker.ctx.scope().kind, ScopeKind::Class(_)) { return; } diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/cannot_raise_literal.rs b/crates/ruff/src/rules/flake8_bugbear/rules/cannot_raise_literal.rs index 913cb2131b..391408f525 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/cannot_raise_literal.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/cannot_raise_literal.rs @@ -16,7 +16,7 @@ impl Violation for CannotRaiseLiteral { } /// B016 -pub fn cannot_raise_literal(checker: &mut Checker, expr: &Expr) { +pub(crate) fn cannot_raise_literal(checker: &mut Checker, expr: &Expr) { let ExprKind::Constant ( _) = &expr.node else { return; }; diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/duplicate_exceptions.rs b/crates/ruff/src/rules/flake8_bugbear/rules/duplicate_exceptions.rs index 30e17a86e8..26ee7a3458 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/duplicate_exceptions.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/duplicate_exceptions.rs @@ -112,7 +112,7 @@ fn duplicate_handler_exceptions<'a>( seen } -pub fn duplicate_exceptions(checker: &mut Checker, handlers: &[Excepthandler]) { +pub(crate) fn duplicate_exceptions(checker: &mut Checker, handlers: &[Excepthandler]) { let mut seen: FxHashSet = FxHashSet::default(); let mut duplicates: FxHashMap> = FxHashMap::default(); for handler in handlers { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/except_with_empty_tuple.rs b/crates/ruff/src/rules/flake8_bugbear/rules/except_with_empty_tuple.rs index 300fa5e8d0..09c0657bb0 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/except_with_empty_tuple.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/except_with_empty_tuple.rs @@ -17,7 +17,7 @@ impl Violation for ExceptWithEmptyTuple { } /// B029 -pub fn except_with_empty_tuple(checker: &mut Checker, excepthandler: &Excepthandler) { +pub(crate) fn except_with_empty_tuple(checker: &mut Checker, excepthandler: &Excepthandler) { let ExcepthandlerKind::ExceptHandler(ast::ExcepthandlerExceptHandler { type_, .. }) = &excepthandler.node; let Some(type_) = type_ else { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/except_with_non_exception_classes.rs b/crates/ruff/src/rules/flake8_bugbear/rules/except_with_non_exception_classes.rs index 8c4f5b700e..60ad1e073d 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/except_with_non_exception_classes.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/except_with_non_exception_classes.rs @@ -42,7 +42,10 @@ fn flatten_starred_iterables(expr: &Expr) -> Vec<&Expr> { } /// B030 -pub fn except_with_non_exception_classes(checker: &mut Checker, excepthandler: &Excepthandler) { +pub(crate) fn except_with_non_exception_classes( + checker: &mut Checker, + excepthandler: &Excepthandler, +) { let ExcepthandlerKind::ExceptHandler(ast::ExcepthandlerExceptHandler { type_, .. }) = &excepthandler.node; let Some(type_) = type_ else { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/f_string_docstring.rs b/crates/ruff/src/rules/flake8_bugbear/rules/f_string_docstring.rs index 4d6c762cc0..56f970dc13 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/f_string_docstring.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/f_string_docstring.rs @@ -19,7 +19,7 @@ impl Violation for FStringDocstring { } /// B021 -pub fn f_string_docstring(checker: &mut Checker, body: &[Stmt]) { +pub(crate) fn f_string_docstring(checker: &mut Checker, body: &[Stmt]) { let Some(stmt) = body.first() else { return; }; diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/function_call_argument_default.rs b/crates/ruff/src/rules/flake8_bugbear/rules/function_call_argument_default.rs index 0c74658d7a..b1bb94bad9 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/function_call_argument_default.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/function_call_argument_default.rs @@ -129,7 +129,7 @@ fn is_nan_or_infinity(expr: &Expr, args: &[Expr]) -> bool { } /// B008 -pub fn function_call_argument_default(checker: &mut Checker, arguments: &Arguments) { +pub(crate) fn function_call_argument_default(checker: &mut Checker, arguments: &Arguments) { // Map immutable calls to (module, member) format. let extend_immutable_calls: Vec = checker .settings diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/function_uses_loop_variable.rs b/crates/ruff/src/rules/flake8_bugbear/rules/function_uses_loop_variable.rs index ea84e9b3f3..9f9da4789a 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/function_uses_loop_variable.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/function_uses_loop_variable.rs @@ -235,7 +235,7 @@ impl<'a> Visitor<'a> for AssignedNamesVisitor<'a> { } /// B023 -pub fn function_uses_loop_variable<'a>(checker: &mut Checker<'a>, node: &Node<'a>) { +pub(crate) fn function_uses_loop_variable<'a>(checker: &mut Checker<'a>, node: &Node<'a>) { // Identify any "suspicious" variables. These are defined as variables that are // referenced in a function or lambda body, but aren't bound as arguments. let suspicious_variables = { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/getattr_with_constant.rs b/crates/ruff/src/rules/flake8_bugbear/rules/getattr_with_constant.rs index 70841c4d05..f67cbfddc1 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/getattr_with_constant.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/getattr_with_constant.rs @@ -37,7 +37,12 @@ fn attribute(value: &Expr, attr: &str) -> Expr { } /// B009 -pub fn getattr_with_constant(checker: &mut Checker, expr: &Expr, func: &Expr, args: &[Expr]) { +pub(crate) fn getattr_with_constant( + checker: &mut Checker, + expr: &Expr, + func: &Expr, + args: &[Expr], +) { let ExprKind::Name(ast::ExprName { id, .. } )= &func.node else { return; }; diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/jump_statement_in_finally.rs b/crates/ruff/src/rules/flake8_bugbear/rules/jump_statement_in_finally.rs index 6773361b2e..a621bb57d8 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/jump_statement_in_finally.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/jump_statement_in_finally.rs @@ -62,7 +62,7 @@ fn walk_stmt(checker: &mut Checker, body: &[Stmt], f: fn(&Stmt) -> bool) { } /// B012 -pub fn jump_statement_in_finally(checker: &mut Checker, finalbody: &[Stmt]) { +pub(crate) fn jump_statement_in_finally(checker: &mut Checker, finalbody: &[Stmt]) { walk_stmt(checker, finalbody, |stmt| { matches!( stmt.node, diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/loop_variable_overrides_iterator.rs b/crates/ruff/src/rules/flake8_bugbear/rules/loop_variable_overrides_iterator.rs index de3808343b..154b5b511d 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/loop_variable_overrides_iterator.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/loop_variable_overrides_iterator.rs @@ -55,7 +55,7 @@ where } /// B020 -pub fn loop_variable_overrides_iterator(checker: &mut Checker, target: &Expr, iter: &Expr) { +pub(crate) fn loop_variable_overrides_iterator(checker: &mut Checker, target: &Expr, iter: &Expr) { let target_names = { let mut target_finder = NameFinder::default(); target_finder.visit_expr(target); diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/mod.rs b/crates/ruff/src/rules/flake8_bugbear/rules/mod.rs index 86684d7e95..77714559fb 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/mod.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/mod.rs @@ -1,53 +1,63 @@ -pub use abstract_base_class::{ +pub(crate) use abstract_base_class::{ abstract_base_class, AbstractBaseClassWithoutAbstractMethod, EmptyMethodWithoutAbstractDecorator, }; -pub use assert_false::{assert_false, AssertFalse}; -pub use assert_raises_exception::{assert_raises_exception, AssertRaisesException}; -pub use assignment_to_os_environ::{assignment_to_os_environ, AssignmentToOsEnviron}; -pub use cached_instance_method::{cached_instance_method, CachedInstanceMethod}; -pub use cannot_raise_literal::{cannot_raise_literal, CannotRaiseLiteral}; -pub use duplicate_exceptions::{ +pub(crate) use assert_false::{assert_false, AssertFalse}; +pub(crate) use assert_raises_exception::{assert_raises_exception, AssertRaisesException}; +pub(crate) use assignment_to_os_environ::{assignment_to_os_environ, AssignmentToOsEnviron}; +pub(crate) use cached_instance_method::{cached_instance_method, CachedInstanceMethod}; +pub(crate) use cannot_raise_literal::{cannot_raise_literal, CannotRaiseLiteral}; +pub(crate) use duplicate_exceptions::{ duplicate_exceptions, DuplicateHandlerException, DuplicateTryBlockException, }; -pub use except_with_empty_tuple::{except_with_empty_tuple, ExceptWithEmptyTuple}; -pub use except_with_non_exception_classes::{ +pub(crate) use except_with_empty_tuple::{except_with_empty_tuple, ExceptWithEmptyTuple}; +pub(crate) use except_with_non_exception_classes::{ except_with_non_exception_classes, ExceptWithNonExceptionClasses, }; -pub use f_string_docstring::{f_string_docstring, FStringDocstring}; -pub use function_call_argument_default::{ +pub(crate) use f_string_docstring::{f_string_docstring, FStringDocstring}; +pub(crate) use function_call_argument_default::{ function_call_argument_default, FunctionCallInDefaultArgument, }; -pub use function_uses_loop_variable::{function_uses_loop_variable, FunctionUsesLoopVariable}; -pub use getattr_with_constant::{getattr_with_constant, GetAttrWithConstant}; -pub use jump_statement_in_finally::{jump_statement_in_finally, JumpStatementInFinally}; -pub use loop_variable_overrides_iterator::{ +pub(crate) use function_uses_loop_variable::{ + function_uses_loop_variable, FunctionUsesLoopVariable, +}; +pub(crate) use getattr_with_constant::{getattr_with_constant, GetAttrWithConstant}; +pub(crate) use jump_statement_in_finally::{jump_statement_in_finally, JumpStatementInFinally}; +pub(crate) use loop_variable_overrides_iterator::{ loop_variable_overrides_iterator, LoopVariableOverridesIterator, }; -pub use mutable_argument_default::{mutable_argument_default, MutableArgumentDefault}; -pub use no_explicit_stacklevel::{no_explicit_stacklevel, NoExplicitStacklevel}; -pub use raise_without_from_inside_except::{ +pub(crate) use mutable_argument_default::{mutable_argument_default, MutableArgumentDefault}; +pub(crate) use no_explicit_stacklevel::{no_explicit_stacklevel, NoExplicitStacklevel}; +pub(crate) use raise_without_from_inside_except::{ raise_without_from_inside_except, RaiseWithoutFromInsideExcept, }; -pub use redundant_tuple_in_exception_handler::{ +pub(crate) use redundant_tuple_in_exception_handler::{ redundant_tuple_in_exception_handler, RedundantTupleInExceptionHandler, }; -pub use reuse_of_groupby_generator::{reuse_of_groupby_generator, ReuseOfGroupbyGenerator}; -pub use setattr_with_constant::{setattr_with_constant, SetAttrWithConstant}; -pub use star_arg_unpacking_after_keyword_arg::{ +pub(crate) use reuse_of_groupby_generator::{reuse_of_groupby_generator, ReuseOfGroupbyGenerator}; +pub(crate) use setattr_with_constant::{setattr_with_constant, SetAttrWithConstant}; +pub(crate) use star_arg_unpacking_after_keyword_arg::{ star_arg_unpacking_after_keyword_arg, StarArgUnpackingAfterKeywordArg, }; -pub use strip_with_multi_characters::{strip_with_multi_characters, StripWithMultiCharacters}; -pub use unary_prefix_increment::{unary_prefix_increment, UnaryPrefixIncrement}; -pub use unintentional_type_annotation::{ +pub(crate) use strip_with_multi_characters::{ + strip_with_multi_characters, StripWithMultiCharacters, +}; +pub(crate) use unary_prefix_increment::{unary_prefix_increment, UnaryPrefixIncrement}; +pub(crate) use unintentional_type_annotation::{ unintentional_type_annotation, UnintentionalTypeAnnotation, }; -pub use unreliable_callable_check::{unreliable_callable_check, UnreliableCallableCheck}; -pub use unused_loop_control_variable::{unused_loop_control_variable, UnusedLoopControlVariable}; -pub use useless_comparison::{useless_comparison, UselessComparison}; -pub use useless_contextlib_suppress::{useless_contextlib_suppress, UselessContextlibSuppress}; -pub use useless_expression::{useless_expression, UselessExpression}; -pub use zip_without_explicit_strict::{zip_without_explicit_strict, ZipWithoutExplicitStrict}; +pub(crate) use unreliable_callable_check::{unreliable_callable_check, UnreliableCallableCheck}; +pub(crate) use unused_loop_control_variable::{ + unused_loop_control_variable, UnusedLoopControlVariable, +}; +pub(crate) use useless_comparison::{useless_comparison, UselessComparison}; +pub(crate) use useless_contextlib_suppress::{ + useless_contextlib_suppress, UselessContextlibSuppress, +}; +pub(crate) use useless_expression::{useless_expression, UselessExpression}; +pub(crate) use zip_without_explicit_strict::{ + zip_without_explicit_strict, ZipWithoutExplicitStrict, +}; mod abstract_base_class; mod assert_false; diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/mutable_argument_default.rs b/crates/ruff/src/rules/flake8_bugbear/rules/mutable_argument_default.rs index da604308f7..b2151e1b1d 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/mutable_argument_default.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/mutable_argument_default.rs @@ -25,7 +25,7 @@ const MUTABLE_FUNCS: &[&[&str]] = &[ &["collections", "deque"], ]; -pub fn is_mutable_func(checker: &Checker, func: &Expr) -> bool { +pub(crate) fn is_mutable_func(checker: &Checker, func: &Expr) -> bool { checker .ctx .resolve_call_path(func) @@ -50,7 +50,7 @@ fn is_mutable_expr(checker: &Checker, expr: &Expr) -> bool { } /// B006 -pub fn mutable_argument_default(checker: &mut Checker, arguments: &Arguments) { +pub(crate) fn mutable_argument_default(checker: &mut Checker, arguments: &Arguments) { // Scan in reverse order to right-align zip(). for (arg, default) in arguments .kwonlyargs diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/no_explicit_stacklevel.rs b/crates/ruff/src/rules/flake8_bugbear/rules/no_explicit_stacklevel.rs index 266bb7ef45..fa6c8f930f 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/no_explicit_stacklevel.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/no_explicit_stacklevel.rs @@ -38,7 +38,7 @@ impl Violation for NoExplicitStacklevel { } /// B028 -pub fn no_explicit_stacklevel( +pub(crate) fn no_explicit_stacklevel( checker: &mut Checker, func: &Expr, args: &[Expr], diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/raise_without_from_inside_except.rs b/crates/ruff/src/rules/flake8_bugbear/rules/raise_without_from_inside_except.rs index cbf6e7c53f..b2d187995e 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/raise_without_from_inside_except.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/raise_without_from_inside_except.rs @@ -22,7 +22,7 @@ impl Violation for RaiseWithoutFromInsideExcept { } /// B904 -pub fn raise_without_from_inside_except(checker: &mut Checker, body: &[Stmt]) { +pub(crate) fn raise_without_from_inside_except(checker: &mut Checker, body: &[Stmt]) { let raises = { let mut visitor = RaiseStatementVisitor::default(); visitor.visit_body(body); diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/redundant_tuple_in_exception_handler.rs b/crates/ruff/src/rules/flake8_bugbear/rules/redundant_tuple_in_exception_handler.rs index a4455d4f4e..3ae289df6b 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/redundant_tuple_in_exception_handler.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/redundant_tuple_in_exception_handler.rs @@ -29,7 +29,10 @@ impl AlwaysAutofixableViolation for RedundantTupleInExceptionHandler { } /// B013 -pub fn redundant_tuple_in_exception_handler(checker: &mut Checker, handlers: &[Excepthandler]) { +pub(crate) fn redundant_tuple_in_exception_handler( + checker: &mut Checker, + handlers: &[Excepthandler], +) { for handler in handlers { let ExcepthandlerKind::ExceptHandler(ast::ExcepthandlerExceptHandler { type_: Some(type_), .. }) = &handler.node else { continue; diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/reuse_of_groupby_generator.rs b/crates/ruff/src/rules/flake8_bugbear/rules/reuse_of_groupby_generator.rs index dc36fb1be1..3abc82a8dc 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/reuse_of_groupby_generator.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/reuse_of_groupby_generator.rs @@ -302,7 +302,7 @@ where } /// B031 -pub fn reuse_of_groupby_generator( +pub(crate) fn reuse_of_groupby_generator( checker: &mut Checker, target: &Expr, body: &[Stmt], diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/setattr_with_constant.rs b/crates/ruff/src/rules/flake8_bugbear/rules/setattr_with_constant.rs index 3427dda7ad..df51a0092c 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/setattr_with_constant.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/setattr_with_constant.rs @@ -47,7 +47,12 @@ fn assignment(obj: &Expr, name: &str, value: &Expr, stylist: &Stylist) -> String } /// B010 -pub fn setattr_with_constant(checker: &mut Checker, expr: &Expr, func: &Expr, args: &[Expr]) { +pub(crate) fn setattr_with_constant( + checker: &mut Checker, + expr: &Expr, + func: &Expr, + args: &[Expr], +) { let ExprKind::Name(ast::ExprName { id, .. }) = &func.node else { return; }; diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/star_arg_unpacking_after_keyword_arg.rs b/crates/ruff/src/rules/flake8_bugbear/rules/star_arg_unpacking_after_keyword_arg.rs index 1db8bc0c43..e80c55330a 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/star_arg_unpacking_after_keyword_arg.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/star_arg_unpacking_after_keyword_arg.rs @@ -25,7 +25,7 @@ impl Violation for StarArgUnpackingAfterKeywordArg { } /// B026 -pub fn star_arg_unpacking_after_keyword_arg( +pub(crate) fn star_arg_unpacking_after_keyword_arg( checker: &mut Checker, args: &[Expr], keywords: &[Keyword], diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/strip_with_multi_characters.rs b/crates/ruff/src/rules/flake8_bugbear/rules/strip_with_multi_characters.rs index fa0874c3e7..62eabf230d 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/strip_with_multi_characters.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/strip_with_multi_characters.rs @@ -17,7 +17,12 @@ impl Violation for StripWithMultiCharacters { } /// B005 -pub fn strip_with_multi_characters(checker: &mut Checker, expr: &Expr, func: &Expr, args: &[Expr]) { +pub(crate) fn strip_with_multi_characters( + checker: &mut Checker, + expr: &Expr, + func: &Expr, + args: &[Expr], +) { let ExprKind::Attribute(ast::ExprAttribute { attr, .. }) = &func.node else { return; }; diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/unary_prefix_increment.rs b/crates/ruff/src/rules/flake8_bugbear/rules/unary_prefix_increment.rs index 121e4ba772..10da1ebee6 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/unary_prefix_increment.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/unary_prefix_increment.rs @@ -35,7 +35,12 @@ impl Violation for UnaryPrefixIncrement { } /// B002 -pub fn unary_prefix_increment(checker: &mut Checker, expr: &Expr, op: &Unaryop, operand: &Expr) { +pub(crate) fn unary_prefix_increment( + checker: &mut Checker, + expr: &Expr, + op: &Unaryop, + operand: &Expr, +) { if !matches!(op, Unaryop::UAdd) { return; } diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/unintentional_type_annotation.rs b/crates/ruff/src/rules/flake8_bugbear/rules/unintentional_type_annotation.rs index dfe246c6ae..cfbcfef1b1 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/unintentional_type_annotation.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/unintentional_type_annotation.rs @@ -34,7 +34,7 @@ impl Violation for UnintentionalTypeAnnotation { } /// B032 -pub fn unintentional_type_annotation( +pub(crate) fn unintentional_type_annotation( checker: &mut Checker, target: &Expr, value: Option<&Expr>, diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/unreliable_callable_check.rs b/crates/ruff/src/rules/flake8_bugbear/rules/unreliable_callable_check.rs index 2350e6d59e..942ca0c2cb 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/unreliable_callable_check.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/unreliable_callable_check.rs @@ -19,7 +19,12 @@ impl Violation for UnreliableCallableCheck { } /// B004 -pub fn unreliable_callable_check(checker: &mut Checker, expr: &Expr, func: &Expr, args: &[Expr]) { +pub(crate) fn unreliable_callable_check( + checker: &mut Checker, + expr: &Expr, + func: &Expr, + args: &[Expr], +) { let ExprKind::Name(ast::ExprName { id, .. }) = &func.node else { return; }; diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/unused_loop_control_variable.rs b/crates/ruff/src/rules/flake8_bugbear/rules/unused_loop_control_variable.rs index ac49e41a15..19a3410245 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/unused_loop_control_variable.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/unused_loop_control_variable.rs @@ -101,7 +101,7 @@ where } /// B007 -pub fn unused_loop_control_variable(checker: &mut Checker, target: &Expr, body: &[Stmt]) { +pub(crate) fn unused_loop_control_variable(checker: &mut Checker, target: &Expr, body: &[Stmt]) { let control_names = { let mut finder = NameFinder::new(); finder.visit_expr(target); diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/useless_comparison.rs b/crates/ruff/src/rules/flake8_bugbear/rules/useless_comparison.rs index ea6b564125..25bdb2e676 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/useless_comparison.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/useless_comparison.rs @@ -19,7 +19,7 @@ impl Violation for UselessComparison { } /// B015 -pub fn useless_comparison(checker: &mut Checker, expr: &Expr) { +pub(crate) fn useless_comparison(checker: &mut Checker, expr: &Expr) { if matches!(expr.node, ExprKind::Compare(_)) { checker .diagnostics diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/useless_contextlib_suppress.rs b/crates/ruff/src/rules/flake8_bugbear/rules/useless_contextlib_suppress.rs index 7b618caa9a..445aa72b5f 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/useless_contextlib_suppress.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/useless_contextlib_suppress.rs @@ -18,7 +18,12 @@ impl Violation for UselessContextlibSuppress { } /// B022 -pub fn useless_contextlib_suppress(checker: &mut Checker, expr: &Expr, func: &Expr, args: &[Expr]) { +pub(crate) fn useless_contextlib_suppress( + checker: &mut Checker, + expr: &Expr, + func: &Expr, + args: &[Expr], +) { if args.is_empty() && checker .ctx diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/useless_expression.rs b/crates/ruff/src/rules/flake8_bugbear/rules/useless_expression.rs index f982abb9fa..350eed90ef 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/useless_expression.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/useless_expression.rs @@ -7,7 +7,7 @@ use ruff_python_ast::helpers::contains_effect; use crate::checkers::ast::Checker; #[derive(Debug, PartialEq, Eq, Copy, Clone)] -pub enum Kind { +pub(crate) enum Kind { Expression, Attribute, } @@ -34,7 +34,7 @@ impl Violation for UselessExpression { } /// B018 -pub fn useless_expression(checker: &mut Checker, value: &Expr) { +pub(crate) fn useless_expression(checker: &mut Checker, value: &Expr) { // Ignore comparisons, as they're handled by `useless_comparison`. if matches!(value.node, ExprKind::Compare(_)) { return; diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/zip_without_explicit_strict.rs b/crates/ruff/src/rules/flake8_bugbear/rules/zip_without_explicit_strict.rs index 4f2cab283c..1a49e65116 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/zip_without_explicit_strict.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/zip_without_explicit_strict.rs @@ -15,7 +15,7 @@ impl Violation for ZipWithoutExplicitStrict { } /// B905 -pub fn zip_without_explicit_strict( +pub(crate) fn zip_without_explicit_strict( checker: &mut Checker, expr: &Expr, func: &Expr, diff --git a/crates/ruff/src/rules/flake8_builtins/rules.rs b/crates/ruff/src/rules/flake8_builtins/rules.rs index f2999d5271..17cd5f438b 100644 --- a/crates/ruff/src/rules/flake8_builtins/rules.rs +++ b/crates/ruff/src/rules/flake8_builtins/rules.rs @@ -172,7 +172,7 @@ fn shadows_builtin(name: &str, ignorelist: &[String]) -> bool { } /// A001 -pub fn builtin_variable_shadowing( +pub(crate) fn builtin_variable_shadowing( checker: &mut Checker, name: &str, attributed: &Attributed, @@ -188,7 +188,7 @@ pub fn builtin_variable_shadowing( } /// A002 -pub fn builtin_argument_shadowing( +pub(crate) fn builtin_argument_shadowing( checker: &mut Checker, name: &str, attributed: &Attributed, @@ -204,7 +204,7 @@ pub fn builtin_argument_shadowing( } /// A003 -pub fn builtin_attribute_shadowing( +pub(crate) fn builtin_attribute_shadowing( checker: &mut Checker, name: &str, attributed: &Attributed, diff --git a/crates/ruff/src/rules/flake8_commas/rules.rs b/crates/ruff/src/rules/flake8_commas/rules.rs index d6c358c2e4..079ad514df 100644 --- a/crates/ruff/src/rules/flake8_commas/rules.rs +++ b/crates/ruff/src/rules/flake8_commas/rules.rs @@ -219,7 +219,7 @@ impl AlwaysAutofixableViolation for ProhibitedTrailingComma { } /// COM812, COM818, COM819 -pub fn trailing_commas( +pub(crate) fn trailing_commas( tokens: &[LexResult], locator: &Locator, settings: &Settings, diff --git a/crates/ruff/src/rules/flake8_comprehensions/fixes.rs b/crates/ruff/src/rules/flake8_comprehensions/fixes.rs index 955c38edd4..28e030837b 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/fixes.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/fixes.rs @@ -30,7 +30,7 @@ fn match_arg<'a, 'b>(call: &'a Call<'b>) -> Result<&'a Arg<'b>> { } /// (C400) Convert `list(x for x in y)` to `[x for x in y]`. -pub fn fix_unnecessary_generator_list( +pub(crate) fn fix_unnecessary_generator_list( locator: &Locator, stylist: &Stylist, expr: &rustpython_parser::ast::Expr, @@ -72,7 +72,7 @@ pub fn fix_unnecessary_generator_list( } /// (C401) Convert `set(x for x in y)` to `{x for x in y}`. -pub fn fix_unnecessary_generator_set( +pub(crate) fn fix_unnecessary_generator_set( locator: &Locator, stylist: &Stylist, expr: &rustpython_parser::ast::Expr, @@ -126,7 +126,7 @@ pub fn fix_unnecessary_generator_set( /// (C402) Convert `dict((x, x) for x in range(3))` to `{x: x for x in /// range(3)}`. -pub fn fix_unnecessary_generator_dict( +pub(crate) fn fix_unnecessary_generator_dict( locator: &Locator, stylist: &Stylist, expr: &rustpython_parser::ast::Expr, @@ -195,7 +195,7 @@ pub fn fix_unnecessary_generator_dict( } /// (C403) Convert `set([x for x in y])` to `{x for x in y}`. -pub fn fix_unnecessary_list_comprehension_set( +pub(crate) fn fix_unnecessary_list_comprehension_set( locator: &Locator, stylist: &Stylist, expr: &rustpython_parser::ast::Expr, @@ -237,7 +237,7 @@ pub fn fix_unnecessary_list_comprehension_set( /// (C404) Convert `dict([(i, i) for i in range(3)])` to `{i: i for i in /// range(3)}`. -pub fn fix_unnecessary_list_comprehension_dict( +pub(crate) fn fix_unnecessary_list_comprehension_dict( locator: &Locator, stylist: &Stylist, expr: &rustpython_parser::ast::Expr, @@ -331,7 +331,7 @@ fn drop_trailing_comma<'a>( } /// (C405) Convert `set((1, 2))` to `{1, 2}`. -pub fn fix_unnecessary_literal_set( +pub(crate) fn fix_unnecessary_literal_set( locator: &Locator, stylist: &Stylist, expr: &rustpython_parser::ast::Expr, @@ -378,7 +378,7 @@ pub fn fix_unnecessary_literal_set( } /// (C406) Convert `dict([(1, 2)])` to `{1: 2}`. -pub fn fix_unnecessary_literal_dict( +pub(crate) fn fix_unnecessary_literal_dict( locator: &Locator, stylist: &Stylist, expr: &rustpython_parser::ast::Expr, @@ -447,7 +447,7 @@ pub fn fix_unnecessary_literal_dict( } /// (C408) -pub fn fix_unnecessary_collection_call( +pub(crate) fn fix_unnecessary_collection_call( locator: &Locator, stylist: &Stylist, expr: &rustpython_parser::ast::Expr, @@ -559,7 +559,7 @@ pub fn fix_unnecessary_collection_call( } /// (C409) Convert `tuple([1, 2])` to `tuple(1, 2)` -pub fn fix_unnecessary_literal_within_tuple_call( +pub(crate) fn fix_unnecessary_literal_within_tuple_call( locator: &Locator, stylist: &Stylist, expr: &rustpython_parser::ast::Expr, @@ -614,7 +614,7 @@ pub fn fix_unnecessary_literal_within_tuple_call( } /// (C410) Convert `list([1, 2])` to `[1, 2]` -pub fn fix_unnecessary_literal_within_list_call( +pub(crate) fn fix_unnecessary_literal_within_list_call( locator: &Locator, stylist: &Stylist, expr: &rustpython_parser::ast::Expr, @@ -671,7 +671,7 @@ pub fn fix_unnecessary_literal_within_list_call( } /// (C411) Convert `list([i * i for i in x])` to `[i * i for i in x]`. -pub fn fix_unnecessary_list_call( +pub(crate) fn fix_unnecessary_list_call( locator: &Locator, stylist: &Stylist, expr: &rustpython_parser::ast::Expr, @@ -698,7 +698,7 @@ pub fn fix_unnecessary_list_call( /// (C413) Convert `list(sorted([2, 3, 1]))` to `sorted([2, 3, 1])`. /// (C413) Convert `reversed(sorted([2, 3, 1]))` to `sorted([2, 3, 1], /// reverse=True)`. -pub fn fix_unnecessary_call_around_sorted( +pub(crate) fn fix_unnecessary_call_around_sorted( locator: &Locator, stylist: &Stylist, expr: &rustpython_parser::ast::Expr, @@ -821,7 +821,7 @@ pub fn fix_unnecessary_call_around_sorted( } /// (C414) Convert `sorted(list(foo))` to `sorted(foo)` -pub fn fix_unnecessary_double_cast_or_process( +pub(crate) fn fix_unnecessary_double_cast_or_process( locator: &Locator, stylist: &Stylist, expr: &rustpython_parser::ast::Expr, @@ -858,7 +858,7 @@ pub fn fix_unnecessary_double_cast_or_process( } /// (C416) Convert `[i for i in x]` to `list(x)`. -pub fn fix_unnecessary_comprehension( +pub(crate) fn fix_unnecessary_comprehension( locator: &Locator, stylist: &Stylist, expr: &rustpython_parser::ast::Expr, @@ -950,7 +950,7 @@ pub fn fix_unnecessary_comprehension( } /// (C417) Convert `map(lambda x: x * 2, bar)` to `(x * 2 for x in bar)`. -pub fn fix_unnecessary_map( +pub(crate) fn fix_unnecessary_map( locator: &Locator, stylist: &Stylist, expr: &rustpython_parser::ast::Expr, @@ -1114,7 +1114,7 @@ pub fn fix_unnecessary_map( } /// (C418) Convert `dict({"a": 1})` to `{"a": 1}` -pub fn fix_unnecessary_literal_within_dict_call( +pub(crate) fn fix_unnecessary_literal_within_dict_call( locator: &Locator, stylist: &Stylist, expr: &rustpython_parser::ast::Expr, @@ -1138,7 +1138,7 @@ pub fn fix_unnecessary_literal_within_dict_call( } /// (C419) Convert `[i for i in a]` into `i for i in a` -pub fn fix_unnecessary_comprehension_any_all( +pub(crate) fn fix_unnecessary_comprehension_any_all( locator: &Locator, stylist: &Stylist, expr: &rustpython_parser::ast::Expr, diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/helpers.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/helpers.rs index c5f55e7cf2..82a989d919 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/helpers.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/helpers.rs @@ -1,6 +1,6 @@ use rustpython_parser::ast::{self, Expr, ExprKind, Keyword}; -pub fn expr_name(func: &Expr) -> Option<&str> { +pub(crate) fn expr_name(func: &Expr) -> Option<&str> { if let ExprKind::Name(ast::ExprName { id, .. }) = &func.node { Some(id) } else { @@ -8,7 +8,7 @@ pub fn expr_name(func: &Expr) -> Option<&str> { } } -pub fn exactly_one_argument_with_matching_function<'a>( +pub(crate) fn exactly_one_argument_with_matching_function<'a>( name: &str, func: &Expr, args: &'a [Expr], @@ -26,7 +26,7 @@ pub fn exactly_one_argument_with_matching_function<'a>( Some(&args[0].node) } -pub fn first_argument_with_matching_function<'a>( +pub(crate) fn first_argument_with_matching_function<'a>( name: &str, func: &Expr, args: &'a [Expr], diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/mod.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/mod.rs index d7418e3a66..0cb1aaacfe 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/mod.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/mod.rs @@ -1,39 +1,41 @@ -pub use unnecessary_call_around_sorted::{ +pub(crate) use unnecessary_call_around_sorted::{ unnecessary_call_around_sorted, UnnecessaryCallAroundSorted, }; -pub use unnecessary_collection_call::{unnecessary_collection_call, UnnecessaryCollectionCall}; -pub use unnecessary_comprehension::{ +pub(crate) use unnecessary_collection_call::{ + unnecessary_collection_call, UnnecessaryCollectionCall, +}; +pub(crate) use unnecessary_comprehension::{ unnecessary_dict_comprehension, unnecessary_list_set_comprehension, UnnecessaryComprehension, }; -pub use unnecessary_comprehension_any_all::{ +pub(crate) use unnecessary_comprehension_any_all::{ unnecessary_comprehension_any_all, UnnecessaryComprehensionAnyAll, }; -pub use unnecessary_double_cast_or_process::{ +pub(crate) use unnecessary_double_cast_or_process::{ unnecessary_double_cast_or_process, UnnecessaryDoubleCastOrProcess, }; -pub use unnecessary_generator_dict::{unnecessary_generator_dict, UnnecessaryGeneratorDict}; -pub use unnecessary_generator_list::{unnecessary_generator_list, UnnecessaryGeneratorList}; -pub use unnecessary_generator_set::{unnecessary_generator_set, UnnecessaryGeneratorSet}; -pub use unnecessary_list_call::{unnecessary_list_call, UnnecessaryListCall}; -pub use unnecessary_list_comprehension_dict::{ +pub(crate) use unnecessary_generator_dict::{unnecessary_generator_dict, UnnecessaryGeneratorDict}; +pub(crate) use unnecessary_generator_list::{unnecessary_generator_list, UnnecessaryGeneratorList}; +pub(crate) use unnecessary_generator_set::{unnecessary_generator_set, UnnecessaryGeneratorSet}; +pub(crate) use unnecessary_list_call::{unnecessary_list_call, UnnecessaryListCall}; +pub(crate) use unnecessary_list_comprehension_dict::{ unnecessary_list_comprehension_dict, UnnecessaryListComprehensionDict, }; -pub use unnecessary_list_comprehension_set::{ +pub(crate) use unnecessary_list_comprehension_set::{ unnecessary_list_comprehension_set, UnnecessaryListComprehensionSet, }; -pub use unnecessary_literal_dict::{unnecessary_literal_dict, UnnecessaryLiteralDict}; -pub use unnecessary_literal_set::{unnecessary_literal_set, UnnecessaryLiteralSet}; -pub use unnecessary_literal_within_dict_call::{ +pub(crate) use unnecessary_literal_dict::{unnecessary_literal_dict, UnnecessaryLiteralDict}; +pub(crate) use unnecessary_literal_set::{unnecessary_literal_set, UnnecessaryLiteralSet}; +pub(crate) use unnecessary_literal_within_dict_call::{ unnecessary_literal_within_dict_call, UnnecessaryLiteralWithinDictCall, }; -pub use unnecessary_literal_within_list_call::{ +pub(crate) use unnecessary_literal_within_list_call::{ unnecessary_literal_within_list_call, UnnecessaryLiteralWithinListCall, }; -pub use unnecessary_literal_within_tuple_call::{ +pub(crate) use unnecessary_literal_within_tuple_call::{ unnecessary_literal_within_tuple_call, UnnecessaryLiteralWithinTupleCall, }; -pub use unnecessary_map::{unnecessary_map, UnnecessaryMap}; -pub use unnecessary_subscript_reversal::{ +pub(crate) use unnecessary_map::{unnecessary_map, UnnecessaryMap}; +pub(crate) use unnecessary_subscript_reversal::{ unnecessary_subscript_reversal, UnnecessarySubscriptReversal, }; diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_call_around_sorted.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_call_around_sorted.rs index 85b1afa245..a2402c059b 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_call_around_sorted.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_call_around_sorted.rs @@ -50,7 +50,7 @@ impl AlwaysAutofixableViolation for UnnecessaryCallAroundSorted { } /// C413 -pub fn unnecessary_call_around_sorted( +pub(crate) fn unnecessary_call_around_sorted( checker: &mut Checker, expr: &Expr, func: &Expr, diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_collection_call.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_collection_call.rs index e2f12c5e5c..09fd27a9cd 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_collection_call.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_collection_call.rs @@ -52,7 +52,7 @@ impl AlwaysAutofixableViolation for UnnecessaryCollectionCall { } /// C408 -pub fn unnecessary_collection_call( +pub(crate) fn unnecessary_collection_call( checker: &mut Checker, expr: &Expr, func: &Expr, diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_comprehension.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_comprehension.rs index 212292fe14..aa7636cb75 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_comprehension.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_comprehension.rs @@ -75,7 +75,7 @@ fn add_diagnostic(checker: &mut Checker, expr: &Expr) { } /// C416 -pub fn unnecessary_dict_comprehension( +pub(crate) fn unnecessary_dict_comprehension( checker: &mut Checker, expr: &Expr, key: &Expr, @@ -117,7 +117,7 @@ pub fn unnecessary_dict_comprehension( } /// C416 -pub fn unnecessary_list_set_comprehension( +pub(crate) fn unnecessary_list_set_comprehension( checker: &mut Checker, expr: &Expr, elt: &Expr, diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_comprehension_any_all.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_comprehension_any_all.rs index c6276285e7..baa751743d 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_comprehension_any_all.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_comprehension_any_all.rs @@ -56,7 +56,7 @@ impl Violation for UnnecessaryComprehensionAnyAll { } /// C419 -pub fn unnecessary_comprehension_any_all( +pub(crate) fn unnecessary_comprehension_any_all( checker: &mut Checker, expr: &Expr, func: &Expr, diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_double_cast_or_process.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_double_cast_or_process.rs index e9a4e510bd..2fe1254d3a 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_double_cast_or_process.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_double_cast_or_process.rs @@ -64,7 +64,7 @@ impl AlwaysAutofixableViolation for UnnecessaryDoubleCastOrProcess { } /// C414 -pub fn unnecessary_double_cast_or_process( +pub(crate) fn unnecessary_double_cast_or_process( checker: &mut Checker, expr: &Expr, func: &Expr, diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_dict.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_dict.rs index a2b686512c..49c3d5bc75 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_dict.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_dict.rs @@ -42,7 +42,7 @@ impl AlwaysAutofixableViolation for UnnecessaryGeneratorDict { } /// C402 (`dict((x, y) for x, y in iterable)`) -pub fn unnecessary_generator_dict( +pub(crate) fn unnecessary_generator_dict( checker: &mut Checker, expr: &Expr, parent: Option<&Expr>, diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_list.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_list.rs index e5031155bb..0ee58fbcb6 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_list.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_list.rs @@ -42,7 +42,7 @@ impl AlwaysAutofixableViolation for UnnecessaryGeneratorList { } /// C400 (`list(generator)`) -pub fn unnecessary_generator_list( +pub(crate) fn unnecessary_generator_list( checker: &mut Checker, expr: &Expr, func: &Expr, diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_set.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_set.rs index a6391bf068..df17c1d6e2 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_set.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_set.rs @@ -42,7 +42,7 @@ impl AlwaysAutofixableViolation for UnnecessaryGeneratorSet { } /// C401 (`set(generator)`) -pub fn unnecessary_generator_set( +pub(crate) fn unnecessary_generator_set( checker: &mut Checker, expr: &Expr, parent: Option<&Expr>, diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_call.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_call.rs index aa3af1363a..bdbdf82c78 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_call.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_call.rs @@ -38,7 +38,12 @@ impl AlwaysAutofixableViolation for UnnecessaryListCall { } /// C411 -pub fn unnecessary_list_call(checker: &mut Checker, expr: &Expr, func: &Expr, args: &[Expr]) { +pub(crate) fn unnecessary_list_call( + checker: &mut Checker, + expr: &Expr, + func: &Expr, + args: &[Expr], +) { let Some(argument) = helpers::first_argument_with_matching_function("list", func, args) else { return; }; diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_dict.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_dict.rs index f96c466086..22b9da504b 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_dict.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_dict.rs @@ -39,7 +39,7 @@ impl AlwaysAutofixableViolation for UnnecessaryListComprehensionDict { } /// C404 (`dict([...])`) -pub fn unnecessary_list_comprehension_dict( +pub(crate) fn unnecessary_list_comprehension_dict( checker: &mut Checker, expr: &Expr, func: &Expr, diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_set.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_set.rs index 1b639f3cd8..41fac334f0 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_set.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_set.rs @@ -40,7 +40,7 @@ impl AlwaysAutofixableViolation for UnnecessaryListComprehensionSet { } /// C403 (`set([...])`) -pub fn unnecessary_list_comprehension_set( +pub(crate) fn unnecessary_list_comprehension_set( checker: &mut Checker, expr: &Expr, func: &Expr, diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_dict.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_dict.rs index 3d382b90d0..5490304873 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_dict.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_dict.rs @@ -46,7 +46,7 @@ impl AlwaysAutofixableViolation for UnnecessaryLiteralDict { } /// C406 (`dict([(1, 2)])`) -pub fn unnecessary_literal_dict( +pub(crate) fn unnecessary_literal_dict( checker: &mut Checker, expr: &Expr, func: &Expr, diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_set.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_set.rs index 1cd490451a..ddcdb3b45d 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_set.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_set.rs @@ -47,7 +47,7 @@ impl AlwaysAutofixableViolation for UnnecessaryLiteralSet { } /// C405 (`set([1, 2])`) -pub fn unnecessary_literal_set( +pub(crate) fn unnecessary_literal_set( checker: &mut Checker, expr: &Expr, func: &Expr, diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_dict_call.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_dict_call.rs index b7b2f9bb91..5a4b32cca2 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_dict_call.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_dict_call.rs @@ -11,7 +11,7 @@ use crate::rules::flake8_comprehensions::fixes; use super::helpers; #[derive(Debug, PartialEq, Eq)] -pub enum DictKind { +pub(crate) enum DictKind { Literal, Comprehension, } @@ -62,7 +62,7 @@ impl AlwaysAutofixableViolation for UnnecessaryLiteralWithinDictCall { } /// C418 -pub fn unnecessary_literal_within_dict_call( +pub(crate) fn unnecessary_literal_within_dict_call( checker: &mut Checker, expr: &Expr, func: &Expr, diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_list_call.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_list_call.rs index 3ec88ff9c6..b790971fa0 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_list_call.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_list_call.rs @@ -65,7 +65,7 @@ impl AlwaysAutofixableViolation for UnnecessaryLiteralWithinListCall { } /// C410 -pub fn unnecessary_literal_within_list_call( +pub(crate) fn unnecessary_literal_within_list_call( checker: &mut Checker, expr: &Expr, func: &Expr, diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_tuple_call.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_tuple_call.rs index a7b4aa7dc6..92c02354b9 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_tuple_call.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_tuple_call.rs @@ -66,7 +66,7 @@ impl AlwaysAutofixableViolation for UnnecessaryLiteralWithinTupleCall { } /// C409 -pub fn unnecessary_literal_within_tuple_call( +pub(crate) fn unnecessary_literal_within_tuple_call( checker: &mut Checker, expr: &Expr, func: &Expr, diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_map.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_map.rs index f1536047d4..ebec47d1f1 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_map.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_map.rs @@ -67,7 +67,7 @@ impl Violation for UnnecessaryMap { } /// C417 -pub fn unnecessary_map( +pub(crate) fn unnecessary_map( checker: &mut Checker, expr: &Expr, parent: Option<&Expr>, diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_subscript_reversal.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_subscript_reversal.rs index 62ea19c828..3a9467ed21 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_subscript_reversal.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_subscript_reversal.rs @@ -42,7 +42,7 @@ impl Violation for UnnecessarySubscriptReversal { } /// C415 -pub fn unnecessary_subscript_reversal( +pub(crate) fn unnecessary_subscript_reversal( checker: &mut Checker, expr: &Expr, func: &Expr, diff --git a/crates/ruff/src/rules/flake8_datetimez/rules.rs b/crates/ruff/src/rules/flake8_datetimez/rules.rs index 83c3cd36a4..8821d1e876 100644 --- a/crates/ruff/src/rules/flake8_datetimez/rules.rs +++ b/crates/ruff/src/rules/flake8_datetimez/rules.rs @@ -117,7 +117,7 @@ impl Violation for CallDateFromtimestamp { } } -pub fn call_datetime_without_tzinfo( +pub(crate) fn call_datetime_without_tzinfo( checker: &mut Checker, func: &Expr, args: &[Expr], @@ -156,7 +156,7 @@ pub fn call_datetime_without_tzinfo( /// /// It uses the system local timezone. /// Use `datetime.datetime.now(tz=)` instead. -pub fn call_datetime_today(checker: &mut Checker, func: &Expr, location: TextRange) { +pub(crate) fn call_datetime_today(checker: &mut Checker, func: &Expr, location: TextRange) { if checker .ctx .resolve_call_path(func) @@ -178,7 +178,7 @@ pub fn call_datetime_today(checker: &mut Checker, func: &Expr, location: TextRan /// local times, it is preferred to use aware datetimes to represent times in /// UTC. As such, the recommended way to create an object representing the /// current time in UTC is by calling `datetime.now(timezone.utc)`. -pub fn call_datetime_utcnow(checker: &mut Checker, func: &Expr, location: TextRange) { +pub(crate) fn call_datetime_utcnow(checker: &mut Checker, func: &Expr, location: TextRange) { if checker .ctx .resolve_call_path(func) @@ -201,7 +201,11 @@ pub fn call_datetime_utcnow(checker: &mut Checker, func: &Expr, location: TextRa /// UTC. As such, the recommended way to create an object representing a /// specific timestamp in UTC is by calling `datetime.fromtimestamp(timestamp, /// tz=timezone.utc)`. -pub fn call_datetime_utcfromtimestamp(checker: &mut Checker, func: &Expr, location: TextRange) { +pub(crate) fn call_datetime_utcfromtimestamp( + checker: &mut Checker, + func: &Expr, + location: TextRange, +) { if checker .ctx .resolve_call_path(func) @@ -216,7 +220,7 @@ pub fn call_datetime_utcfromtimestamp(checker: &mut Checker, func: &Expr, locati } /// DTZ005 -pub fn call_datetime_now_without_tzinfo( +pub(crate) fn call_datetime_now_without_tzinfo( checker: &mut Checker, func: &Expr, args: &[Expr], @@ -258,7 +262,7 @@ pub fn call_datetime_now_without_tzinfo( } /// DTZ006 -pub fn call_datetime_fromtimestamp( +pub(crate) fn call_datetime_fromtimestamp( checker: &mut Checker, func: &Expr, args: &[Expr], @@ -300,7 +304,7 @@ pub fn call_datetime_fromtimestamp( } /// DTZ007 -pub fn call_datetime_strptime_without_zone( +pub(crate) fn call_datetime_strptime_without_zone( checker: &mut Checker, func: &Expr, args: &[Expr], @@ -363,7 +367,7 @@ pub fn call_datetime_strptime_without_zone( /// /// It uses the system local timezone. /// Use `datetime.datetime.now(tz=).date()` instead. -pub fn call_date_today(checker: &mut Checker, func: &Expr, location: TextRange) { +pub(crate) fn call_date_today(checker: &mut Checker, func: &Expr, location: TextRange) { if checker .ctx .resolve_call_path(func) @@ -383,7 +387,7 @@ pub fn call_date_today(checker: &mut Checker, func: &Expr, location: TextRange) /// /// It uses the system local timezone. /// Use `datetime.datetime.fromtimestamp(, tz=).date()` instead. -pub fn call_date_fromtimestamp(checker: &mut Checker, func: &Expr, location: TextRange) { +pub(crate) fn call_date_fromtimestamp(checker: &mut Checker, func: &Expr, location: TextRange) { if checker .ctx .resolve_call_path(func) diff --git a/crates/ruff/src/rules/flake8_debugger/rules.rs b/crates/ruff/src/rules/flake8_debugger/rules.rs index 808402ce95..015e719bfa 100644 --- a/crates/ruff/src/rules/flake8_debugger/rules.rs +++ b/crates/ruff/src/rules/flake8_debugger/rules.rs @@ -41,7 +41,7 @@ const DEBUGGERS: &[&[&str]] = &[ ]; /// Checks for the presence of a debugger call. -pub fn debugger_call(checker: &mut Checker, expr: &Expr, func: &Expr) { +pub(crate) fn debugger_call(checker: &mut Checker, expr: &Expr, func: &Expr) { if let Some(target) = checker.ctx.resolve_call_path(func).and_then(|call_path| { DEBUGGERS .iter() @@ -57,7 +57,7 @@ pub fn debugger_call(checker: &mut Checker, expr: &Expr, func: &Expr) { } /// Checks for the presence of a debugger import. -pub fn debugger_import(stmt: &Stmt, module: Option<&str>, name: &str) -> Option { +pub(crate) fn debugger_import(stmt: &Stmt, module: Option<&str>, name: &str) -> Option { // Special-case: allow `import builtins`, which is far more general than (e.g.) // `import celery.contrib.rdb`). if module.is_none() && name == "builtins" { diff --git a/crates/ruff/src/rules/flake8_debugger/types.rs b/crates/ruff/src/rules/flake8_debugger/types.rs index ab3485a3a6..9652e66960 100644 --- a/crates/ruff/src/rules/flake8_debugger/types.rs +++ b/crates/ruff/src/rules/flake8_debugger/types.rs @@ -1,5 +1,5 @@ #[derive(Debug, PartialEq, Eq, Clone)] -pub enum DebuggerUsingType { +pub(crate) enum DebuggerUsingType { Call(String), Import(String), } diff --git a/crates/ruff/src/rules/flake8_django/rules/all_with_model_form.rs b/crates/ruff/src/rules/flake8_django/rules/all_with_model_form.rs index 7a861a268f..81bb5efa26 100644 --- a/crates/ruff/src/rules/flake8_django/rules/all_with_model_form.rs +++ b/crates/ruff/src/rules/flake8_django/rules/all_with_model_form.rs @@ -47,7 +47,11 @@ impl Violation for DjangoAllWithModelForm { } /// DJ007 -pub fn all_with_model_form(checker: &Checker, bases: &[Expr], body: &[Stmt]) -> Option { +pub(crate) fn all_with_model_form( + checker: &Checker, + bases: &[Expr], + body: &[Stmt], +) -> Option { if !bases.iter().any(|base| is_model_form(&checker.ctx, base)) { return None; } diff --git a/crates/ruff/src/rules/flake8_django/rules/exclude_with_model_form.rs b/crates/ruff/src/rules/flake8_django/rules/exclude_with_model_form.rs index f5d1e87b29..e23aeab4ff 100644 --- a/crates/ruff/src/rules/flake8_django/rules/exclude_with_model_form.rs +++ b/crates/ruff/src/rules/flake8_django/rules/exclude_with_model_form.rs @@ -45,7 +45,7 @@ impl Violation for DjangoExcludeWithModelForm { } /// DJ006 -pub fn exclude_with_model_form( +pub(crate) fn exclude_with_model_form( checker: &Checker, bases: &[Expr], body: &[Stmt], diff --git a/crates/ruff/src/rules/flake8_django/rules/helpers.rs b/crates/ruff/src/rules/flake8_django/rules/helpers.rs index 6d3bc724cc..ac73f2143f 100644 --- a/crates/ruff/src/rules/flake8_django/rules/helpers.rs +++ b/crates/ruff/src/rules/flake8_django/rules/helpers.rs @@ -3,14 +3,14 @@ use rustpython_parser::ast::Expr; use ruff_python_semantic::context::Context; /// Return `true` if a Python class appears to be a Django model, based on its base classes. -pub fn is_model(context: &Context, base: &Expr) -> bool { +pub(crate) fn is_model(context: &Context, base: &Expr) -> bool { context.resolve_call_path(base).map_or(false, |call_path| { call_path.as_slice() == ["django", "db", "models", "Model"] }) } /// Return `true` if a Python class appears to be a Django model form, based on its base classes. -pub fn is_model_form(context: &Context, base: &Expr) -> bool { +pub(crate) fn is_model_form(context: &Context, base: &Expr) -> bool { context.resolve_call_path(base).map_or(false, |call_path| { call_path.as_slice() == ["django", "forms", "ModelForm"] || call_path.as_slice() == ["django", "forms", "models", "ModelForm"] @@ -18,7 +18,7 @@ pub fn is_model_form(context: &Context, base: &Expr) -> bool { } /// Return `true` if the expression is constructor for a Django model field. -pub fn is_model_field(context: &Context, expr: &Expr) -> bool { +pub(crate) fn is_model_field(context: &Context, expr: &Expr) -> bool { context.resolve_call_path(expr).map_or(false, |call_path| { call_path .as_slice() @@ -27,7 +27,7 @@ pub fn is_model_field(context: &Context, expr: &Expr) -> bool { } /// Return the name of the field type, if the expression is constructor for a Django model field. -pub fn get_model_field_name<'a>(context: &'a Context, expr: &'a Expr) -> Option<&'a str> { +pub(crate) fn get_model_field_name<'a>(context: &'a Context, expr: &'a Expr) -> Option<&'a str> { context.resolve_call_path(expr).and_then(|call_path| { let call_path = call_path.as_slice(); if !call_path.starts_with(&["django", "db", "models"]) { diff --git a/crates/ruff/src/rules/flake8_django/rules/locals_in_render_function.rs b/crates/ruff/src/rules/flake8_django/rules/locals_in_render_function.rs index 9c488d60ff..03d3bdee1b 100644 --- a/crates/ruff/src/rules/flake8_django/rules/locals_in_render_function.rs +++ b/crates/ruff/src/rules/flake8_django/rules/locals_in_render_function.rs @@ -43,7 +43,7 @@ impl Violation for DjangoLocalsInRenderFunction { } /// DJ003 -pub fn locals_in_render_function( +pub(crate) fn locals_in_render_function( checker: &mut Checker, func: &Expr, args: &[Expr], diff --git a/crates/ruff/src/rules/flake8_django/rules/mod.rs b/crates/ruff/src/rules/flake8_django/rules/mod.rs index 504f9c14af..2b5188d71a 100644 --- a/crates/ruff/src/rules/flake8_django/rules/mod.rs +++ b/crates/ruff/src/rules/flake8_django/rules/mod.rs @@ -1,14 +1,16 @@ -pub use all_with_model_form::{all_with_model_form, DjangoAllWithModelForm}; -pub use exclude_with_model_form::{exclude_with_model_form, DjangoExcludeWithModelForm}; -pub use locals_in_render_function::{locals_in_render_function, DjangoLocalsInRenderFunction}; -pub use model_without_dunder_str::{model_without_dunder_str, DjangoModelWithoutDunderStr}; -pub use non_leading_receiver_decorator::{ +pub(crate) use all_with_model_form::{all_with_model_form, DjangoAllWithModelForm}; +pub(crate) use exclude_with_model_form::{exclude_with_model_form, DjangoExcludeWithModelForm}; +pub(crate) use locals_in_render_function::{ + locals_in_render_function, DjangoLocalsInRenderFunction, +}; +pub(crate) use model_without_dunder_str::{model_without_dunder_str, DjangoModelWithoutDunderStr}; +pub(crate) use non_leading_receiver_decorator::{ non_leading_receiver_decorator, DjangoNonLeadingReceiverDecorator, }; -pub use nullable_model_string_field::{ +pub(crate) use nullable_model_string_field::{ nullable_model_string_field, DjangoNullableModelStringField, }; -pub use unordered_body_content_in_model::{ +pub(crate) use unordered_body_content_in_model::{ unordered_body_content_in_model, DjangoUnorderedBodyContentInModel, }; diff --git a/crates/ruff/src/rules/flake8_django/rules/model_without_dunder_str.rs b/crates/ruff/src/rules/flake8_django/rules/model_without_dunder_str.rs index 3d5f66770a..91e1f47ea1 100644 --- a/crates/ruff/src/rules/flake8_django/rules/model_without_dunder_str.rs +++ b/crates/ruff/src/rules/flake8_django/rules/model_without_dunder_str.rs @@ -49,7 +49,7 @@ impl Violation for DjangoModelWithoutDunderStr { } /// DJ008 -pub fn model_without_dunder_str( +pub(crate) fn model_without_dunder_str( checker: &Checker, bases: &[Expr], body: &[Stmt], diff --git a/crates/ruff/src/rules/flake8_django/rules/non_leading_receiver_decorator.rs b/crates/ruff/src/rules/flake8_django/rules/non_leading_receiver_decorator.rs index 714e55357c..fb7bb6144b 100644 --- a/crates/ruff/src/rules/flake8_django/rules/non_leading_receiver_decorator.rs +++ b/crates/ruff/src/rules/flake8_django/rules/non_leading_receiver_decorator.rs @@ -48,7 +48,7 @@ impl Violation for DjangoNonLeadingReceiverDecorator { } /// DJ013 -pub fn non_leading_receiver_decorator<'a, F>( +pub(crate) fn non_leading_receiver_decorator<'a, F>( decorator_list: &'a [Expr], resolve_call_path: F, ) -> Vec diff --git a/crates/ruff/src/rules/flake8_django/rules/nullable_model_string_field.rs b/crates/ruff/src/rules/flake8_django/rules/nullable_model_string_field.rs index bddddd9776..c1d44e6e64 100644 --- a/crates/ruff/src/rules/flake8_django/rules/nullable_model_string_field.rs +++ b/crates/ruff/src/rules/flake8_django/rules/nullable_model_string_field.rs @@ -61,7 +61,7 @@ const NOT_NULL_TRUE_FIELDS: [&str; 6] = [ ]; /// DJ001 -pub fn nullable_model_string_field(checker: &Checker, body: &[Stmt]) -> Vec { +pub(crate) fn nullable_model_string_field(checker: &Checker, body: &[Stmt]) -> Vec { let mut errors = Vec::new(); for statement in body.iter() { let StmtKind::Assign(ast::StmtAssign {value, ..}) = &statement.node else { diff --git a/crates/ruff/src/rules/flake8_django/rules/unordered_body_content_in_model.rs b/crates/ruff/src/rules/flake8_django/rules/unordered_body_content_in_model.rs index 135879c0af..c555b67373 100644 --- a/crates/ruff/src/rules/flake8_django/rules/unordered_body_content_in_model.rs +++ b/crates/ruff/src/rules/flake8_django/rules/unordered_body_content_in_model.rs @@ -75,7 +75,7 @@ impl Violation for DjangoUnorderedBodyContentInModel { } #[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq)] -pub enum ContentType { +pub(crate) enum ContentType { FieldDeclaration, ManagerDeclaration, MetaClass, @@ -137,7 +137,11 @@ fn get_element_type(checker: &Checker, element: &StmtKind) -> Option = Lazy::new(|| Regex::new(r"^(?P\s*)#!(?P.*)").unwrap()); #[derive(Debug, PartialEq, Eq)] -pub enum ShebangDirective<'a> { +pub(crate) enum ShebangDirective<'a> { None, // whitespace length, start of the shebang, contents Match(TextSize, TextSize, &'a str), } -pub fn extract_shebang(line: &str) -> ShebangDirective { +pub(crate) fn extract_shebang(line: &str) -> ShebangDirective { // Minor optimization to avoid matches in the common case. if !line.contains('!') { return ShebangDirective::None; @@ -41,7 +41,7 @@ pub fn extract_shebang(line: &str) -> ShebangDirective { } #[cfg(target_family = "unix")] -pub fn is_executable(filepath: &Path) -> Result { +pub(crate) fn is_executable(filepath: &Path) -> Result { { let metadata = filepath.metadata()?; let permissions = metadata.permissions(); diff --git a/crates/ruff/src/rules/flake8_executable/rules/mod.rs b/crates/ruff/src/rules/flake8_executable/rules/mod.rs index 382952bbb8..4e300fae44 100644 --- a/crates/ruff/src/rules/flake8_executable/rules/mod.rs +++ b/crates/ruff/src/rules/flake8_executable/rules/mod.rs @@ -1,8 +1,8 @@ -pub use shebang_missing::{shebang_missing, ShebangMissingExecutableFile}; -pub use shebang_newline::{shebang_newline, ShebangNotFirstLine}; -pub use shebang_not_executable::{shebang_not_executable, ShebangNotExecutable}; -pub use shebang_python::{shebang_python, ShebangMissingPython}; -pub use shebang_whitespace::{shebang_whitespace, ShebangLeadingWhitespace}; +pub(crate) use shebang_missing::{shebang_missing, ShebangMissingExecutableFile}; +pub(crate) use shebang_newline::{shebang_newline, ShebangNotFirstLine}; +pub(crate) use shebang_not_executable::{shebang_not_executable, ShebangNotExecutable}; +pub(crate) use shebang_python::{shebang_python, ShebangMissingPython}; +pub(crate) use shebang_whitespace::{shebang_whitespace, ShebangLeadingWhitespace}; mod shebang_missing; mod shebang_newline; diff --git a/crates/ruff/src/rules/flake8_executable/rules/shebang_missing.rs b/crates/ruff/src/rules/flake8_executable/rules/shebang_missing.rs index dc3c02d2e4..4466127f9c 100644 --- a/crates/ruff/src/rules/flake8_executable/rules/shebang_missing.rs +++ b/crates/ruff/src/rules/flake8_executable/rules/shebang_missing.rs @@ -22,7 +22,7 @@ impl Violation for ShebangMissingExecutableFile { /// EXE002 #[cfg(target_family = "unix")] -pub fn shebang_missing(filepath: &Path) -> Option { +pub(crate) fn shebang_missing(filepath: &Path) -> Option { if let Ok(true) = is_executable(filepath) { let diagnostic = Diagnostic::new(ShebangMissingExecutableFile, TextRange::default()); return Some(diagnostic); @@ -31,6 +31,6 @@ pub fn shebang_missing(filepath: &Path) -> Option { } #[cfg(not(target_family = "unix"))] -pub fn shebang_missing(_filepath: &Path) -> Option { +pub(crate) fn shebang_missing(_filepath: &Path) -> Option { None } diff --git a/crates/ruff/src/rules/flake8_executable/rules/shebang_newline.rs b/crates/ruff/src/rules/flake8_executable/rules/shebang_newline.rs index ad5e2cc1d3..9c605ba940 100644 --- a/crates/ruff/src/rules/flake8_executable/rules/shebang_newline.rs +++ b/crates/ruff/src/rules/flake8_executable/rules/shebang_newline.rs @@ -16,7 +16,7 @@ impl Violation for ShebangNotFirstLine { } /// EXE005 -pub fn shebang_newline( +pub(crate) fn shebang_newline( range: TextRange, shebang: &ShebangDirective, first_line: bool, diff --git a/crates/ruff/src/rules/flake8_executable/rules/shebang_not_executable.rs b/crates/ruff/src/rules/flake8_executable/rules/shebang_not_executable.rs index 72e284f895..f68ffa5aaf 100644 --- a/crates/ruff/src/rules/flake8_executable/rules/shebang_not_executable.rs +++ b/crates/ruff/src/rules/flake8_executable/rules/shebang_not_executable.rs @@ -23,7 +23,7 @@ impl Violation for ShebangNotExecutable { /// EXE001 #[cfg(target_family = "unix")] -pub fn shebang_not_executable( +pub(crate) fn shebang_not_executable( filepath: &Path, range: TextRange, shebang: &ShebangDirective, @@ -41,7 +41,7 @@ pub fn shebang_not_executable( } #[cfg(not(target_family = "unix"))] -pub fn shebang_not_executable( +pub(crate) fn shebang_not_executable( _filepath: &Path, _range: TextRange, _shebang: &ShebangDirective, diff --git a/crates/ruff/src/rules/flake8_executable/rules/shebang_python.rs b/crates/ruff/src/rules/flake8_executable/rules/shebang_python.rs index ded384a05b..73f3d1f333 100644 --- a/crates/ruff/src/rules/flake8_executable/rules/shebang_python.rs +++ b/crates/ruff/src/rules/flake8_executable/rules/shebang_python.rs @@ -16,7 +16,7 @@ impl Violation for ShebangMissingPython { } /// EXE003 -pub fn shebang_python(range: TextRange, shebang: &ShebangDirective) -> Option { +pub(crate) fn shebang_python(range: TextRange, shebang: &ShebangDirective) -> Option { if let ShebangDirective::Match(_, start, content) = shebang { if content.contains("python") || content.contains("pytest") { None diff --git a/crates/ruff/src/rules/flake8_executable/rules/shebang_whitespace.rs b/crates/ruff/src/rules/flake8_executable/rules/shebang_whitespace.rs index 76480221c3..0458d61432 100644 --- a/crates/ruff/src/rules/flake8_executable/rules/shebang_whitespace.rs +++ b/crates/ruff/src/rules/flake8_executable/rules/shebang_whitespace.rs @@ -20,7 +20,7 @@ impl AlwaysAutofixableViolation for ShebangLeadingWhitespace { } /// EXE004 -pub fn shebang_whitespace( +pub(crate) fn shebang_whitespace( range: TextRange, shebang: &ShebangDirective, autofix: bool, diff --git a/crates/ruff/src/rules/flake8_gettext/rules.rs b/crates/ruff/src/rules/flake8_gettext/rules.rs index d292bba3d2..9dabace058 100644 --- a/crates/ruff/src/rules/flake8_gettext/rules.rs +++ b/crates/ruff/src/rules/flake8_gettext/rules.rs @@ -33,7 +33,7 @@ impl Violation for PrintfInGetTextFuncCall { } /// Returns true if the [`Expr`] is an internationalization function call. -pub fn is_gettext_func_call(func: &Expr, functions_names: &[String]) -> bool { +pub(crate) fn is_gettext_func_call(func: &Expr, functions_names: &[String]) -> bool { if let ExprKind::Name(ast::ExprName { id, .. }) = &func.node { functions_names.contains(id.as_ref()) } else { @@ -42,7 +42,7 @@ pub fn is_gettext_func_call(func: &Expr, functions_names: &[String]) -> bool { } /// INT001 -pub fn f_string_in_gettext_func_call(args: &[Expr]) -> Option { +pub(crate) fn f_string_in_gettext_func_call(args: &[Expr]) -> Option { if let Some(first) = args.first() { if matches!(first.node, ExprKind::JoinedStr(_)) { return Some(Diagnostic::new(FStringInGetTextFuncCall {}, first.range())); @@ -52,7 +52,7 @@ pub fn f_string_in_gettext_func_call(args: &[Expr]) -> Option { } /// INT002 -pub fn format_in_gettext_func_call(args: &[Expr]) -> Option { +pub(crate) fn format_in_gettext_func_call(args: &[Expr]) -> Option { if let Some(first) = args.first() { if let ExprKind::Call(ast::ExprCall { func, .. }) = &first.node { if let ExprKind::Attribute(ast::ExprAttribute { attr, .. }) = &func.node { @@ -66,7 +66,7 @@ pub fn format_in_gettext_func_call(args: &[Expr]) -> Option { } /// INT003 -pub fn printf_in_gettext_func_call(args: &[Expr]) -> Option { +pub(crate) fn printf_in_gettext_func_call(args: &[Expr]) -> Option { if let Some(first) = args.first() { if let ExprKind::BinOp(ast::ExprBinOp { op: Operator::Mod { .. }, diff --git a/crates/ruff/src/rules/flake8_implicit_str_concat/rules.rs b/crates/ruff/src/rules/flake8_implicit_str_concat/rules.rs index feb8889c81..0a1df5b397 100644 --- a/crates/ruff/src/rules/flake8_implicit_str_concat/rules.rs +++ b/crates/ruff/src/rules/flake8_implicit_str_concat/rules.rs @@ -119,7 +119,11 @@ impl Violation for ExplicitStringConcatenation { } /// ISC001, ISC002 -pub fn implicit(tokens: &[LexResult], settings: &Settings, locator: &Locator) -> Vec { +pub(crate) fn implicit( + tokens: &[LexResult], + settings: &Settings, + locator: &Locator, +) -> Vec { let mut diagnostics = vec![]; for ((a_tok, a_range), (b_tok, b_range)) in tokens .iter() @@ -148,7 +152,7 @@ pub fn implicit(tokens: &[LexResult], settings: &Settings, locator: &Locator) -> } /// ISC003 -pub fn explicit(expr: &Expr) -> Option { +pub(crate) fn explicit(expr: &Expr) -> Option { if let ExprKind::BinOp(ast::ExprBinOp { left, op, right }) = &expr.node { if matches!(op, Operator::Add) { if matches!( diff --git a/crates/ruff/src/rules/flake8_import_conventions/rules/banned_import_alias.rs b/crates/ruff/src/rules/flake8_import_conventions/rules/banned_import_alias.rs index bb312bd2ac..66f038553a 100644 --- a/crates/ruff/src/rules/flake8_import_conventions/rules/banned_import_alias.rs +++ b/crates/ruff/src/rules/flake8_import_conventions/rules/banned_import_alias.rs @@ -41,7 +41,7 @@ impl Violation for BannedImportAlias { } /// ICN002 -pub fn banned_import_alias( +pub(crate) fn banned_import_alias( stmt: &Stmt, name: &str, asname: &str, diff --git a/crates/ruff/src/rules/flake8_import_conventions/rules/banned_import_from.rs b/crates/ruff/src/rules/flake8_import_conventions/rules/banned_import_from.rs index 498fa5751d..ebfdc815d4 100644 --- a/crates/ruff/src/rules/flake8_import_conventions/rules/banned_import_from.rs +++ b/crates/ruff/src/rules/flake8_import_conventions/rules/banned_import_from.rs @@ -41,7 +41,7 @@ impl Violation for BannedImportFrom { } /// ICN003 -pub fn banned_import_from( +pub(crate) fn banned_import_from( stmt: &Stmt, name: &str, banned_conventions: &FxHashSet, diff --git a/crates/ruff/src/rules/flake8_import_conventions/rules/conventional_import_alias.rs b/crates/ruff/src/rules/flake8_import_conventions/rules/conventional_import_alias.rs index 180aea7f53..7c18d40b50 100644 --- a/crates/ruff/src/rules/flake8_import_conventions/rules/conventional_import_alias.rs +++ b/crates/ruff/src/rules/flake8_import_conventions/rules/conventional_import_alias.rs @@ -40,7 +40,7 @@ impl Violation for UnconventionalImportAlias { } /// ICN001 -pub fn conventional_import_alias( +pub(crate) fn conventional_import_alias( stmt: &Stmt, name: &str, asname: Option<&str>, diff --git a/crates/ruff/src/rules/flake8_import_conventions/rules/mod.rs b/crates/ruff/src/rules/flake8_import_conventions/rules/mod.rs index d8dbbbfe1b..63f88d0f9a 100644 --- a/crates/ruff/src/rules/flake8_import_conventions/rules/mod.rs +++ b/crates/ruff/src/rules/flake8_import_conventions/rules/mod.rs @@ -1,6 +1,6 @@ -pub use banned_import_alias::{banned_import_alias, BannedImportAlias}; -pub use banned_import_from::{banned_import_from, BannedImportFrom}; -pub use conventional_import_alias::{conventional_import_alias, UnconventionalImportAlias}; +pub(crate) use banned_import_alias::{banned_import_alias, BannedImportAlias}; +pub(crate) use banned_import_from::{banned_import_from, BannedImportFrom}; +pub(crate) use conventional_import_alias::{conventional_import_alias, UnconventionalImportAlias}; mod banned_import_alias; mod banned_import_from; diff --git a/crates/ruff/src/rules/flake8_logging_format/rules.rs b/crates/ruff/src/rules/flake8_logging_format/rules.rs index 056c04494b..835ebf116b 100644 --- a/crates/ruff/src/rules/flake8_logging_format/rules.rs +++ b/crates/ruff/src/rules/flake8_logging_format/rules.rs @@ -145,7 +145,12 @@ impl LoggingCallType { } /// Check logging calls for violations. -pub fn logging_call(checker: &mut Checker, func: &Expr, args: &[Expr], keywords: &[Keyword]) { +pub(crate) fn logging_call( + checker: &mut Checker, + func: &Expr, + args: &[Expr], + keywords: &[Keyword], +) { if !logging::is_logger_candidate(&checker.ctx, func) { return; } diff --git a/crates/ruff/src/rules/flake8_no_pep420/rules.rs b/crates/ruff/src/rules/flake8_no_pep420/rules.rs index d38fd9f920..406446bdaf 100644 --- a/crates/ruff/src/rules/flake8_no_pep420/rules.rs +++ b/crates/ruff/src/rules/flake8_no_pep420/rules.rs @@ -38,7 +38,7 @@ impl Violation for ImplicitNamespacePackage { } /// INP001 -pub fn implicit_namespace_package( +pub(crate) fn implicit_namespace_package( path: &Path, package: Option<&Path>, project_root: &Path, diff --git a/crates/ruff/src/rules/flake8_pie/rules.rs b/crates/ruff/src/rules/flake8_pie/rules.rs index 8fdff8e9c5..b31fbcf72c 100644 --- a/crates/ruff/src/rules/flake8_pie/rules.rs +++ b/crates/ruff/src/rules/flake8_pie/rules.rs @@ -295,7 +295,7 @@ impl AlwaysAutofixableViolation for ReimplementedListBuiltin { } /// PIE790 -pub fn no_unnecessary_pass(checker: &mut Checker, body: &[Stmt]) { +pub(crate) fn no_unnecessary_pass(checker: &mut Checker, body: &[Stmt]) { if body.len() > 1 { // This only catches the case in which a docstring makes a `pass` statement // redundant. Consider removing all `pass` statements instead. @@ -340,7 +340,7 @@ pub fn no_unnecessary_pass(checker: &mut Checker, body: &[Stmt]) { } /// PIE794 -pub fn duplicate_class_field_definition<'a, 'b>( +pub(crate) fn duplicate_class_field_definition<'a, 'b>( checker: &mut Checker<'a>, parent: &'b Stmt, body: &'b [Stmt], @@ -403,8 +403,11 @@ pub fn duplicate_class_field_definition<'a, 'b>( } /// PIE796 -pub fn non_unique_enums<'a, 'b>(checker: &mut Checker<'a>, parent: &'b Stmt, body: &'b [Stmt]) -where +pub(crate) fn non_unique_enums<'a, 'b>( + checker: &mut Checker<'a>, + parent: &'b Stmt, + body: &'b [Stmt], +) where 'b: 'a, { let StmtKind::ClassDef(ast::StmtClassDef { bases, .. }) = &parent.node else { @@ -449,7 +452,7 @@ where } /// PIE800 -pub fn unnecessary_spread(checker: &mut Checker, keys: &[Option], values: &[Expr]) { +pub(crate) fn unnecessary_spread(checker: &mut Checker, keys: &[Option], values: &[Expr]) { for item in keys.iter().zip(values.iter()) { if let (None, value) = item { // We only care about when the key is None which indicates a spread `**` @@ -476,7 +479,7 @@ fn is_valid_kwarg_name(key: &Expr) -> bool { } /// PIE804 -pub fn unnecessary_dict_kwargs(checker: &mut Checker, expr: &Expr, kwargs: &[Keyword]) { +pub(crate) fn unnecessary_dict_kwargs(checker: &mut Checker, expr: &Expr, kwargs: &[Keyword]) { for kw in kwargs { // keyword is a spread operator (indicated by None) if kw.node.arg.is_none() { @@ -495,7 +498,7 @@ pub fn unnecessary_dict_kwargs(checker: &mut Checker, expr: &Expr, kwargs: &[Key } /// PIE810 -pub fn multiple_starts_ends_with(checker: &mut Checker, expr: &Expr) { +pub(crate) fn multiple_starts_ends_with(checker: &mut Checker, expr: &Expr) { let ExprKind::BoolOp(ast::ExprBoolOp { op: Boolop::Or, values }) = &expr.node else { return; }; @@ -607,7 +610,7 @@ pub fn multiple_starts_ends_with(checker: &mut Checker, expr: &Expr) { } /// PIE807 -pub fn reimplemented_list_builtin(checker: &mut Checker, expr: &Expr) { +pub(crate) fn reimplemented_list_builtin(checker: &mut Checker, expr: &Expr) { let ExprKind::Lambda(ast::ExprLambda { args, body }) = &expr.node else { panic!("Expected ExprKind::Lambda"); }; diff --git a/crates/ruff/src/rules/flake8_print/rules/mod.rs b/crates/ruff/src/rules/flake8_print/rules/mod.rs index 505d8967dc..e044fe39e9 100644 --- a/crates/ruff/src/rules/flake8_print/rules/mod.rs +++ b/crates/ruff/src/rules/flake8_print/rules/mod.rs @@ -1,3 +1,3 @@ -pub use print_call::{print_call, PPrint, Print}; +pub(crate) use print_call::{print_call, PPrint, Print}; mod print_call; diff --git a/crates/ruff/src/rules/flake8_print/rules/print_call.rs b/crates/ruff/src/rules/flake8_print/rules/print_call.rs index 80d5046318..828f9c1368 100644 --- a/crates/ruff/src/rules/flake8_print/rules/print_call.rs +++ b/crates/ruff/src/rules/flake8_print/rules/print_call.rs @@ -76,7 +76,7 @@ impl Violation for PPrint { } /// T201, T203 -pub fn print_call(checker: &mut Checker, func: &Expr, keywords: &[Keyword]) { +pub(crate) fn print_call(checker: &mut Checker, func: &Expr, keywords: &[Keyword]) { let diagnostic = { let call_path = checker.ctx.resolve_call_path(func); if call_path diff --git a/crates/ruff/src/rules/flake8_pyi/rules/bad_version_info_comparison.rs b/crates/ruff/src/rules/flake8_pyi/rules/bad_version_info_comparison.rs index 94bbc61f33..6c86a1b4a3 100644 --- a/crates/ruff/src/rules/flake8_pyi/rules/bad_version_info_comparison.rs +++ b/crates/ruff/src/rules/flake8_pyi/rules/bad_version_info_comparison.rs @@ -56,7 +56,7 @@ impl Violation for BadVersionInfoComparison { } /// PYI006 -pub fn bad_version_info_comparison( +pub(crate) fn bad_version_info_comparison( checker: &mut Checker, expr: &Expr, left: &Expr, diff --git a/crates/ruff/src/rules/flake8_pyi/rules/docstring_in_stubs.rs b/crates/ruff/src/rules/flake8_pyi/rules/docstring_in_stubs.rs index 10aa9bee40..013808e8e1 100644 --- a/crates/ruff/src/rules/flake8_pyi/rules/docstring_in_stubs.rs +++ b/crates/ruff/src/rules/flake8_pyi/rules/docstring_in_stubs.rs @@ -16,7 +16,7 @@ impl Violation for DocstringInStub { } /// PYI021 -pub fn docstring_in_stubs(checker: &mut Checker, docstring: Option<&Expr>) { +pub(crate) fn docstring_in_stubs(checker: &mut Checker, docstring: Option<&Expr>) { if let Some(docstr) = &docstring { checker .diagnostics diff --git a/crates/ruff/src/rules/flake8_pyi/rules/duplicate_union_member.rs b/crates/ruff/src/rules/flake8_pyi/rules/duplicate_union_member.rs index cae6193e0f..a4bb984262 100644 --- a/crates/ruff/src/rules/flake8_pyi/rules/duplicate_union_member.rs +++ b/crates/ruff/src/rules/flake8_pyi/rules/duplicate_union_member.rs @@ -26,7 +26,7 @@ impl AlwaysAutofixableViolation for DuplicateUnionMember { } /// PYI016 -pub fn duplicate_union_member(checker: &mut Checker, expr: &Expr) { +pub(crate) fn duplicate_union_member(checker: &mut Checker, expr: &Expr) { let mut seen_nodes = FxHashSet::default(); traverse_union(&mut seen_nodes, checker, expr, None); } diff --git a/crates/ruff/src/rules/flake8_pyi/rules/mod.rs b/crates/ruff/src/rules/flake8_pyi/rules/mod.rs index 56019ab999..833286ace5 100644 --- a/crates/ruff/src/rules/flake8_pyi/rules/mod.rs +++ b/crates/ruff/src/rules/flake8_pyi/rules/mod.rs @@ -1,21 +1,23 @@ -pub use bad_version_info_comparison::{bad_version_info_comparison, BadVersionInfoComparison}; -pub use docstring_in_stubs::{docstring_in_stubs, DocstringInStub}; -pub use duplicate_union_member::{duplicate_union_member, DuplicateUnionMember}; -pub use non_empty_stub_body::{non_empty_stub_body, NonEmptyStubBody}; -pub use pass_in_class_body::{pass_in_class_body, PassInClassBody}; -pub use pass_statement_stub_body::{pass_statement_stub_body, PassStatementStubBody}; -pub use prefix_type_params::{prefix_type_params, UnprefixedTypeParam}; -pub use quoted_annotation_in_stub::{quoted_annotation_in_stub, QuotedAnnotationInStub}; -pub use simple_defaults::{ +pub(crate) use bad_version_info_comparison::{ + bad_version_info_comparison, BadVersionInfoComparison, +}; +pub(crate) use docstring_in_stubs::{docstring_in_stubs, DocstringInStub}; +pub(crate) use duplicate_union_member::{duplicate_union_member, DuplicateUnionMember}; +pub(crate) use non_empty_stub_body::{non_empty_stub_body, NonEmptyStubBody}; +pub(crate) use pass_in_class_body::{pass_in_class_body, PassInClassBody}; +pub(crate) use pass_statement_stub_body::{pass_statement_stub_body, PassStatementStubBody}; +pub(crate) use prefix_type_params::{prefix_type_params, UnprefixedTypeParam}; +pub(crate) use quoted_annotation_in_stub::{quoted_annotation_in_stub, QuotedAnnotationInStub}; +pub(crate) use simple_defaults::{ annotated_assignment_default_in_stub, argument_simple_defaults, assignment_default_in_stub, typed_argument_simple_defaults, ArgumentDefaultInStub, AssignmentDefaultInStub, TypedArgumentDefaultInStub, }; -pub use type_alias_naming::{ +pub(crate) use type_alias_naming::{ snake_case_type_alias, t_suffixed_type_alias, SnakeCaseTypeAlias, TSuffixedTypeAlias, }; -pub use type_comment_in_stub::{type_comment_in_stub, TypeCommentInStub}; -pub use unrecognized_platform::{ +pub(crate) use type_comment_in_stub::{type_comment_in_stub, TypeCommentInStub}; +pub(crate) use unrecognized_platform::{ unrecognized_platform, UnrecognizedPlatformCheck, UnrecognizedPlatformName, }; diff --git a/crates/ruff/src/rules/flake8_pyi/rules/non_empty_stub_body.rs b/crates/ruff/src/rules/flake8_pyi/rules/non_empty_stub_body.rs index de669f4736..e20a26976f 100644 --- a/crates/ruff/src/rules/flake8_pyi/rules/non_empty_stub_body.rs +++ b/crates/ruff/src/rules/flake8_pyi/rules/non_empty_stub_body.rs @@ -16,7 +16,7 @@ impl Violation for NonEmptyStubBody { } /// PYI010 -pub fn non_empty_stub_body(checker: &mut Checker, body: &[Stmt]) { +pub(crate) fn non_empty_stub_body(checker: &mut Checker, body: &[Stmt]) { if body.len() != 1 { return; } diff --git a/crates/ruff/src/rules/flake8_pyi/rules/pass_in_class_body.rs b/crates/ruff/src/rules/flake8_pyi/rules/pass_in_class_body.rs index 529638110a..9abb89d9c7 100644 --- a/crates/ruff/src/rules/flake8_pyi/rules/pass_in_class_body.rs +++ b/crates/ruff/src/rules/flake8_pyi/rules/pass_in_class_body.rs @@ -24,7 +24,11 @@ impl AlwaysAutofixableViolation for PassInClassBody { } /// PYI012 -pub fn pass_in_class_body<'a>(checker: &mut Checker<'a>, parent: &'a Stmt, body: &'a [Stmt]) { +pub(crate) fn pass_in_class_body<'a>( + checker: &mut Checker<'a>, + parent: &'a Stmt, + body: &'a [Stmt], +) { // `pass` is required in these situations (or handled by `pass_statement_stub_body`). if body.len() < 2 { return; diff --git a/crates/ruff/src/rules/flake8_pyi/rules/pass_statement_stub_body.rs b/crates/ruff/src/rules/flake8_pyi/rules/pass_statement_stub_body.rs index 4223262548..bcb03d497d 100644 --- a/crates/ruff/src/rules/flake8_pyi/rules/pass_statement_stub_body.rs +++ b/crates/ruff/src/rules/flake8_pyi/rules/pass_statement_stub_body.rs @@ -16,7 +16,7 @@ impl Violation for PassStatementStubBody { } /// PYI009 -pub fn pass_statement_stub_body(checker: &mut Checker, body: &[Stmt]) { +pub(crate) fn pass_statement_stub_body(checker: &mut Checker, body: &[Stmt]) { if body.len() != 1 { return; } diff --git a/crates/ruff/src/rules/flake8_pyi/rules/prefix_type_params.rs b/crates/ruff/src/rules/flake8_pyi/rules/prefix_type_params.rs index 5d8b73e46a..4e2048aaaf 100644 --- a/crates/ruff/src/rules/flake8_pyi/rules/prefix_type_params.rs +++ b/crates/ruff/src/rules/flake8_pyi/rules/prefix_type_params.rs @@ -8,7 +8,7 @@ use ruff_macros::{derive_message_formats, violation}; use crate::checkers::ast::Checker; #[derive(Debug, PartialEq, Eq, Copy, Clone)] -pub enum VarKind { +pub(crate) enum VarKind { TypeVar, ParamSpec, TypeVarTuple, @@ -59,7 +59,7 @@ impl Violation for UnprefixedTypeParam { } /// PYI001 -pub fn prefix_type_params(checker: &mut Checker, value: &Expr, targets: &[Expr]) { +pub(crate) fn prefix_type_params(checker: &mut Checker, value: &Expr, targets: &[Expr]) { if targets.len() != 1 { return; } diff --git a/crates/ruff/src/rules/flake8_pyi/rules/quoted_annotation_in_stub.rs b/crates/ruff/src/rules/flake8_pyi/rules/quoted_annotation_in_stub.rs index 46f8aed2df..8ba8d3fbf3 100644 --- a/crates/ruff/src/rules/flake8_pyi/rules/quoted_annotation_in_stub.rs +++ b/crates/ruff/src/rules/flake8_pyi/rules/quoted_annotation_in_stub.rs @@ -20,7 +20,7 @@ impl AlwaysAutofixableViolation for QuotedAnnotationInStub { } /// PYI020 -pub fn quoted_annotation_in_stub(checker: &mut Checker, annotation: &str, range: TextRange) { +pub(crate) fn quoted_annotation_in_stub(checker: &mut Checker, annotation: &str, range: TextRange) { let mut diagnostic = Diagnostic::new(QuotedAnnotationInStub, range); if checker.patch(Rule::QuotedAnnotationInStub) { #[allow(deprecated)] diff --git a/crates/ruff/src/rules/flake8_pyi/rules/simple_defaults.rs b/crates/ruff/src/rules/flake8_pyi/rules/simple_defaults.rs index c9077add37..07e0c59615 100644 --- a/crates/ruff/src/rules/flake8_pyi/rules/simple_defaults.rs +++ b/crates/ruff/src/rules/flake8_pyi/rules/simple_defaults.rs @@ -286,7 +286,7 @@ fn is_special_assignment(context: &Context, target: &Expr) -> bool { } /// PYI011 -pub fn typed_argument_simple_defaults(checker: &mut Checker, args: &Arguments) { +pub(crate) fn typed_argument_simple_defaults(checker: &mut Checker, args: &Arguments) { if !args.defaults.is_empty() { let defaults_start = args.posonlyargs.len() + args.args.len() - args.defaults.len(); for (i, arg) in args.posonlyargs.iter().chain(&args.args).enumerate() { @@ -343,7 +343,7 @@ pub fn typed_argument_simple_defaults(checker: &mut Checker, args: &Arguments) { } /// PYI014 -pub fn argument_simple_defaults(checker: &mut Checker, args: &Arguments) { +pub(crate) fn argument_simple_defaults(checker: &mut Checker, args: &Arguments) { if !args.defaults.is_empty() { let defaults_start = args.posonlyargs.len() + args.args.len() - args.defaults.len(); for (i, arg) in args.posonlyargs.iter().chain(&args.args).enumerate() { @@ -400,7 +400,7 @@ pub fn argument_simple_defaults(checker: &mut Checker, args: &Arguments) { } /// PYI015 -pub fn assignment_default_in_stub(checker: &mut Checker, targets: &[Expr], value: &Expr) { +pub(crate) fn assignment_default_in_stub(checker: &mut Checker, targets: &[Expr], value: &Expr) { if targets.len() == 1 && is_special_assignment(&checker.ctx, &targets[0]) { return; } @@ -426,7 +426,7 @@ pub fn assignment_default_in_stub(checker: &mut Checker, targets: &[Expr], value } /// PYI015 -pub fn annotated_assignment_default_in_stub( +pub(crate) fn annotated_assignment_default_in_stub( checker: &mut Checker, target: &Expr, value: &Expr, diff --git a/crates/ruff/src/rules/flake8_pyi/rules/type_alias_naming.rs b/crates/ruff/src/rules/flake8_pyi/rules/type_alias_naming.rs index e5dece1db9..bccb79fe9f 100644 --- a/crates/ruff/src/rules/flake8_pyi/rules/type_alias_naming.rs +++ b/crates/ruff/src/rules/flake8_pyi/rules/type_alias_naming.rs @@ -59,7 +59,7 @@ fn is_t_suffixed_type_alias(name: &str) -> bool { } /// PYI042 -pub fn snake_case_type_alias(checker: &mut Checker, target: &Expr) { +pub(crate) fn snake_case_type_alias(checker: &mut Checker, target: &Expr) { if let ExprKind::Name(ast::ExprName { id, .. }) = target.node() { if !is_snake_case_type_alias(id) { return; @@ -75,7 +75,7 @@ pub fn snake_case_type_alias(checker: &mut Checker, target: &Expr) { } /// PYI043 -pub fn t_suffixed_type_alias(checker: &mut Checker, target: &Expr) { +pub(crate) fn t_suffixed_type_alias(checker: &mut Checker, target: &Expr) { if let ExprKind::Name(ast::ExprName { id, .. }) = target.node() { if !is_t_suffixed_type_alias(id) { return; diff --git a/crates/ruff/src/rules/flake8_pyi/rules/type_comment_in_stub.rs b/crates/ruff/src/rules/flake8_pyi/rules/type_comment_in_stub.rs index e92592d993..365018311f 100644 --- a/crates/ruff/src/rules/flake8_pyi/rules/type_comment_in_stub.rs +++ b/crates/ruff/src/rules/flake8_pyi/rules/type_comment_in_stub.rs @@ -35,7 +35,7 @@ impl Violation for TypeCommentInStub { } /// PYI033 -pub fn type_comment_in_stub(tokens: &[LexResult]) -> Vec { +pub(crate) fn type_comment_in_stub(tokens: &[LexResult]) -> Vec { let mut diagnostics = vec![]; for token in tokens.iter().flatten() { diff --git a/crates/ruff/src/rules/flake8_pyi/rules/unrecognized_platform.rs b/crates/ruff/src/rules/flake8_pyi/rules/unrecognized_platform.rs index 272b5aaa67..ed070e109a 100644 --- a/crates/ruff/src/rules/flake8_pyi/rules/unrecognized_platform.rs +++ b/crates/ruff/src/rules/flake8_pyi/rules/unrecognized_platform.rs @@ -89,7 +89,7 @@ impl Violation for UnrecognizedPlatformName { } /// PYI007, PYI008 -pub fn unrecognized_platform( +pub(crate) fn unrecognized_platform( checker: &mut Checker, expr: &Expr, left: &Expr, diff --git a/crates/ruff/src/rules/flake8_pytest_style/rules/assertion.rs b/crates/ruff/src/rules/flake8_pytest_style/rules/assertion.rs index 29425a1364..47113ff66f 100644 --- a/crates/ruff/src/rules/flake8_pytest_style/rules/assertion.rs +++ b/crates/ruff/src/rules/flake8_pytest_style/rules/assertion.rs @@ -174,7 +174,7 @@ fn check_assert_in_except(name: &str, body: &[Stmt]) -> Vec { } /// PT009 -pub fn unittest_assertion( +pub(crate) fn unittest_assertion( checker: &Checker, expr: &Expr, func: &Expr, @@ -215,7 +215,7 @@ pub fn unittest_assertion( } /// PT015 -pub fn assert_falsy(checker: &mut Checker, stmt: &Stmt, test: &Expr) { +pub(crate) fn assert_falsy(checker: &mut Checker, stmt: &Stmt, test: &Expr) { if Truthiness::from_expr(test, |id| checker.ctx.is_builtin(id)).is_falsey() { checker .diagnostics @@ -224,7 +224,7 @@ pub fn assert_falsy(checker: &mut Checker, stmt: &Stmt, test: &Expr) { } /// PT017 -pub fn assert_in_exception_handler(handlers: &[Excepthandler]) -> Vec { +pub(crate) fn assert_in_exception_handler(handlers: &[Excepthandler]) -> Vec { handlers .iter() .flat_map(|handler| match &handler.node { @@ -418,7 +418,12 @@ fn fix_composite_condition(stmt: &Stmt, locator: &Locator, stylist: &Stylist) -> } /// PT018 -pub fn composite_condition(checker: &mut Checker, stmt: &Stmt, test: &Expr, msg: Option<&Expr>) { +pub(crate) fn composite_condition( + checker: &mut Checker, + stmt: &Stmt, + test: &Expr, + msg: Option<&Expr>, +) { let composite = is_composite_condition(test); if matches!(composite, CompositionKind::Simple | CompositionKind::Mixed) { let fixable = matches!(composite, CompositionKind::Simple) diff --git a/crates/ruff/src/rules/flake8_pytest_style/rules/fail.rs b/crates/ruff/src/rules/flake8_pytest_style/rules/fail.rs index 7a323b1185..cb61c427c0 100644 --- a/crates/ruff/src/rules/flake8_pytest_style/rules/fail.rs +++ b/crates/ruff/src/rules/flake8_pytest_style/rules/fail.rs @@ -18,7 +18,7 @@ impl Violation for PytestFailWithoutMessage { } } -pub fn fail_call(checker: &mut Checker, func: &Expr, args: &[Expr], keywords: &[Keyword]) { +pub(crate) fn fail_call(checker: &mut Checker, func: &Expr, args: &[Expr], keywords: &[Keyword]) { if is_pytest_fail(&checker.ctx, func) { let call_args = SimpleCallArgs::new(args, keywords); let msg = call_args.argument("msg", 0); diff --git a/crates/ruff/src/rules/flake8_pytest_style/rules/fixture.rs b/crates/ruff/src/rules/flake8_pytest_style/rules/fixture.rs index d80a7b2223..6a74211473 100644 --- a/crates/ruff/src/rules/flake8_pytest_style/rules/fixture.rs +++ b/crates/ruff/src/rules/flake8_pytest_style/rules/fixture.rs @@ -23,7 +23,7 @@ use super::helpers::{ }; #[derive(Debug, PartialEq, Eq)] -pub enum Parentheses { +pub(crate) enum Parentheses { None, Empty, } @@ -265,7 +265,7 @@ fn pytest_fixture_parentheses( checker.diagnostics.push(diagnostic); } -pub fn fix_extraneous_scope_function( +pub(crate) fn fix_extraneous_scope_function( locator: &Locator, stmt_at: TextSize, expr_range: TextRange, @@ -523,7 +523,7 @@ fn check_fixture_marks(checker: &mut Checker, decorators: &[Expr]) { } } -pub fn fixture( +pub(crate) fn fixture( checker: &mut Checker, stmt: &Stmt, name: &str, diff --git a/crates/ruff/src/rules/flake8_pytest_style/rules/imports.rs b/crates/ruff/src/rules/flake8_pytest_style/rules/imports.rs index df2601e0fa..cb4efe4309 100644 --- a/crates/ruff/src/rules/flake8_pytest_style/rules/imports.rs +++ b/crates/ruff/src/rules/flake8_pytest_style/rules/imports.rs @@ -18,7 +18,7 @@ fn is_pytest_or_subpackage(imported_name: &str) -> bool { } /// PT013 -pub fn import(import_from: &Stmt, name: &str, asname: Option<&str>) -> Option { +pub(crate) fn import(import_from: &Stmt, name: &str, asname: Option<&str>) -> Option { if is_pytest_or_subpackage(name) { if let Some(alias) = asname { if alias != name { @@ -33,7 +33,7 @@ pub fn import(import_from: &Stmt, name: &str, asname: Option<&str>) -> Option, level: Option, diff --git a/crates/ruff/src/rules/flake8_pytest_style/rules/marks.rs b/crates/ruff/src/rules/flake8_pytest_style/rules/marks.rs index 0cf8987889..39de83ec58 100644 --- a/crates/ruff/src/rules/flake8_pytest_style/rules/marks.rs +++ b/crates/ruff/src/rules/flake8_pytest_style/rules/marks.rs @@ -123,7 +123,7 @@ fn check_useless_usefixtures(checker: &mut Checker, decorator: &Expr, call_path: } } -pub fn marks(checker: &mut Checker, decorators: &[Expr]) { +pub(crate) fn marks(checker: &mut Checker, decorators: &[Expr]) { let enforce_parentheses = checker .settings .rules diff --git a/crates/ruff/src/rules/flake8_pytest_style/rules/mod.rs b/crates/ruff/src/rules/flake8_pytest_style/rules/mod.rs index 6a8e227f35..dcf1277056 100644 --- a/crates/ruff/src/rules/flake8_pytest_style/rules/mod.rs +++ b/crates/ruff/src/rules/flake8_pytest_style/rules/mod.rs @@ -1,10 +1,10 @@ -pub use assertion::{ +pub(crate) use assertion::{ assert_falsy, assert_in_exception_handler, composite_condition, unittest_assertion, PytestAssertAlwaysFalse, PytestAssertInExcept, PytestCompositeAssertion, PytestUnittestAssertion, }; -pub use fail::{fail_call, PytestFailWithoutMessage}; -pub use fixture::{ +pub(crate) use fail::{fail_call, PytestFailWithoutMessage}; +pub(crate) use fixture::{ fixture, PytestDeprecatedYieldFixture, PytestErroneousUseFixturesOnFixture, PytestExtraneousScopeFunction, PytestFixtureFinalizerCallback, PytestFixtureIncorrectParenthesesStyle, PytestFixtureParamWithoutValue, @@ -12,13 +12,15 @@ pub use fixture::{ PytestMissingFixtureNameUnderscore, PytestUnnecessaryAsyncioMarkOnFixture, PytestUselessYieldFixture, }; -pub use imports::{import, import_from, PytestIncorrectPytestImport}; -pub use marks::{marks, PytestIncorrectMarkParenthesesStyle, PytestUseFixturesWithoutParameters}; -pub use parametrize::{ +pub(crate) use imports::{import, import_from, PytestIncorrectPytestImport}; +pub(crate) use marks::{ + marks, PytestIncorrectMarkParenthesesStyle, PytestUseFixturesWithoutParameters, +}; +pub(crate) use parametrize::{ parametrize, PytestParametrizeNamesWrongType, PytestParametrizeValuesWrongType, }; -pub use patch::{patch_with_lambda, PytestPatchWithLambda}; -pub use raises::{ +pub(crate) use patch::{patch_with_lambda, PytestPatchWithLambda}; +pub(crate) use raises::{ complex_raises, raises_call, PytestRaisesTooBroad, PytestRaisesWithMultipleStatements, PytestRaisesWithoutException, }; diff --git a/crates/ruff/src/rules/flake8_pytest_style/rules/parametrize.rs b/crates/ruff/src/rules/flake8_pytest_style/rules/parametrize.rs index dc6cb5b251..2d3ef24aab 100644 --- a/crates/ruff/src/rules/flake8_pytest_style/rules/parametrize.rs +++ b/crates/ruff/src/rules/flake8_pytest_style/rules/parametrize.rs @@ -425,7 +425,7 @@ fn handle_value_rows( } } -pub fn parametrize(checker: &mut Checker, decorators: &[Expr]) { +pub(crate) fn parametrize(checker: &mut Checker, decorators: &[Expr]) { for decorator in decorators { if is_pytest_parametrize(&checker.ctx, decorator) { if let ExprKind::Call(ast::ExprCall { args, .. }) = &decorator.node { diff --git a/crates/ruff/src/rules/flake8_pytest_style/rules/patch.rs b/crates/ruff/src/rules/flake8_pytest_style/rules/patch.rs index 2cdb60c7ec..1cef0b5af8 100644 --- a/crates/ruff/src/rules/flake8_pytest_style/rules/patch.rs +++ b/crates/ruff/src/rules/flake8_pytest_style/rules/patch.rs @@ -89,7 +89,11 @@ fn check_patch_call( None } -pub fn patch_with_lambda(call: &Expr, args: &[Expr], keywords: &[Keyword]) -> Option { +pub(crate) fn patch_with_lambda( + call: &Expr, + args: &[Expr], + keywords: &[Keyword], +) -> Option { if let Some(call_path) = compose_call_path(call) { if PATCH_NAMES.contains(&call_path.as_str()) { check_patch_call(call, args, keywords, 1) diff --git a/crates/ruff/src/rules/flake8_pytest_style/rules/raises.rs b/crates/ruff/src/rules/flake8_pytest_style/rules/raises.rs index 948c116a99..33d2f6404a 100644 --- a/crates/ruff/src/rules/flake8_pytest_style/rules/raises.rs +++ b/crates/ruff/src/rules/flake8_pytest_style/rules/raises.rs @@ -65,7 +65,7 @@ const fn is_non_trivial_with_body(body: &[Stmt]) -> bool { } } -pub fn raises_call(checker: &mut Checker, func: &Expr, args: &[Expr], keywords: &[Keyword]) { +pub(crate) fn raises_call(checker: &mut Checker, func: &Expr, args: &[Expr], keywords: &[Keyword]) { if is_pytest_raises(checker, func) { if checker .settings @@ -97,7 +97,12 @@ pub fn raises_call(checker: &mut Checker, func: &Expr, args: &[Expr], keywords: } } -pub fn complex_raises(checker: &mut Checker, stmt: &Stmt, items: &[Withitem], body: &[Stmt]) { +pub(crate) fn complex_raises( + checker: &mut Checker, + stmt: &Stmt, + items: &[Withitem], + body: &[Stmt], +) { let mut is_too_complex = false; let raises_called = items.iter().any(|item| match &item.context_expr.node { diff --git a/crates/ruff/src/rules/flake8_pytest_style/rules/unittest_assert.rs b/crates/ruff/src/rules/flake8_pytest_style/rules/unittest_assert.rs index 2eefd373ea..064586eff0 100644 --- a/crates/ruff/src/rules/flake8_pytest_style/rules/unittest_assert.rs +++ b/crates/ruff/src/rules/flake8_pytest_style/rules/unittest_assert.rs @@ -12,7 +12,7 @@ use ruff_python_ast::helpers::{create_expr, create_stmt}; /// `unittest` module. Note: any variants that can't be replaced with plain /// `assert` statements are commented out. #[derive(Copy, Clone)] -pub enum UnittestAssert { +pub(crate) enum UnittestAssert { AlmostEqual, AlmostEquals, CountEqual, @@ -201,7 +201,7 @@ impl UnittestAssert { } /// Create a map from argument name to value. - pub fn args_map<'a>( + pub(crate) fn args_map<'a>( &'a self, args: &'a [Expr], keywords: &'a [Keyword], @@ -259,7 +259,7 @@ impl UnittestAssert { Ok(args_map) } - pub fn generate_assert(self, args: &[Expr], keywords: &[Keyword]) -> Result { + pub(crate) fn generate_assert(self, args: &[Expr], keywords: &[Keyword]) -> Result { let args = self.args_map(args, keywords)?; match self { UnittestAssert::True | UnittestAssert::False => { diff --git a/crates/ruff/src/rules/flake8_quotes/rules.rs b/crates/ruff/src/rules/flake8_quotes/rules.rs index 1c3e3d613f..b9f5efc6b0 100644 --- a/crates/ruff/src/rules/flake8_quotes/rules.rs +++ b/crates/ruff/src/rules/flake8_quotes/rules.rs @@ -467,7 +467,11 @@ fn strings(locator: &Locator, sequence: &[TextRange], settings: &Settings) -> Ve } /// Generate `flake8-quote` diagnostics from a token stream. -pub fn from_tokens(lxr: &[LexResult], locator: &Locator, settings: &Settings) -> Vec { +pub(crate) fn from_tokens( + lxr: &[LexResult], + locator: &Locator, + settings: &Settings, +) -> Vec { let mut diagnostics = vec![]; // Keep track of sequences of strings, which represent implicit string diff --git a/crates/ruff/src/rules/flake8_raise/rules/mod.rs b/crates/ruff/src/rules/flake8_raise/rules/mod.rs index 7177469472..12efaed6ba 100644 --- a/crates/ruff/src/rules/flake8_raise/rules/mod.rs +++ b/crates/ruff/src/rules/flake8_raise/rules/mod.rs @@ -1,4 +1,4 @@ -pub use unnecessary_paren_on_raise_exception::{ +pub(crate) use unnecessary_paren_on_raise_exception::{ unnecessary_paren_on_raise_exception, UnnecessaryParenOnRaiseException, }; diff --git a/crates/ruff/src/rules/flake8_raise/rules/unnecessary_paren_on_raise_exception.rs b/crates/ruff/src/rules/flake8_raise/rules/unnecessary_paren_on_raise_exception.rs index e9bdc69b5b..1f8aaa8787 100644 --- a/crates/ruff/src/rules/flake8_raise/rules/unnecessary_paren_on_raise_exception.rs +++ b/crates/ruff/src/rules/flake8_raise/rules/unnecessary_paren_on_raise_exception.rs @@ -22,7 +22,7 @@ impl AlwaysAutofixableViolation for UnnecessaryParenOnRaiseException { } /// RSE102 -pub fn unnecessary_paren_on_raise_exception(checker: &mut Checker, expr: &Expr) { +pub(crate) fn unnecessary_paren_on_raise_exception(checker: &mut Checker, expr: &Expr) { if let ExprKind::Call(ast::ExprCall { func, args, diff --git a/crates/ruff/src/rules/flake8_return/branch.rs b/crates/ruff/src/rules/flake8_return/branch.rs index b1aa9e86bf..998d6da129 100644 --- a/crates/ruff/src/rules/flake8_return/branch.rs +++ b/crates/ruff/src/rules/flake8_return/branch.rs @@ -1,7 +1,7 @@ use std::fmt; #[derive(Debug, PartialEq, Eq, Copy, Clone)] -pub enum Branch { +pub(crate) enum Branch { Elif, Else, } diff --git a/crates/ruff/src/rules/flake8_return/helpers.rs b/crates/ruff/src/rules/flake8_return/helpers.rs index d1ca7388a8..4fd46778f0 100644 --- a/crates/ruff/src/rules/flake8_return/helpers.rs +++ b/crates/ruff/src/rules/flake8_return/helpers.rs @@ -6,7 +6,7 @@ use ruff_python_ast::source_code::Locator; /// Return `true` if a function's return statement include at least one /// non-`None` value. -pub fn result_exists(returns: &[(&Stmt, Option<&Expr>)]) -> bool { +pub(crate) fn result_exists(returns: &[(&Stmt, Option<&Expr>)]) -> bool { returns.iter().any(|(_, expr)| { expr.map(|expr| { !matches!( @@ -25,7 +25,7 @@ pub fn result_exists(returns: &[(&Stmt, Option<&Expr>)]) -> bool { /// /// This method assumes that the statement is the last statement in its body; specifically, that /// the statement isn't followed by a semicolon, followed by a multi-line statement. -pub fn end_of_last_statement(stmt: &Stmt, locator: &Locator) -> TextSize { +pub(crate) fn end_of_last_statement(stmt: &Stmt, locator: &Locator) -> TextSize { // End-of-file, so just return the end of the statement. if stmt.end() == locator.text_len() { stmt.end() diff --git a/crates/ruff/src/rules/flake8_return/rules.rs b/crates/ruff/src/rules/flake8_return/rules.rs index b6fa8fa26a..0948f5131e 100644 --- a/crates/ruff/src/rules/flake8_return/rules.rs +++ b/crates/ruff/src/rules/flake8_return/rules.rs @@ -687,7 +687,7 @@ fn superfluous_else(checker: &mut Checker, stack: &Stack) { } /// Run all checks from the `flake8-return` plugin. -pub fn function(checker: &mut Checker, body: &[Stmt], returns: Option<&Expr>) { +pub(crate) fn function(checker: &mut Checker, body: &[Stmt], returns: Option<&Expr>) { // Find the last statement in the function. let Some(last_stmt) = body.last() else { // Skip empty functions. diff --git a/crates/ruff/src/rules/flake8_return/visitor.rs b/crates/ruff/src/rules/flake8_return/visitor.rs index d14ae293cc..c56a22cf46 100644 --- a/crates/ruff/src/rules/flake8_return/visitor.rs +++ b/crates/ruff/src/rules/flake8_return/visitor.rs @@ -6,21 +6,21 @@ use ruff_python_ast::visitor; use ruff_python_ast::visitor::Visitor; #[derive(Default)] -pub struct Stack<'a> { - pub returns: Vec<(&'a Stmt, Option<&'a Expr>)>, - pub yields: Vec<&'a Expr>, - pub elses: Vec<&'a Stmt>, - pub elifs: Vec<&'a Stmt>, - pub references: FxHashMap<&'a str, Vec>, - pub non_locals: FxHashSet<&'a str>, - pub assignments: FxHashMap<&'a str, Vec>, - pub loops: Vec, - pub tries: Vec, +pub(crate) struct Stack<'a> { + pub(crate) returns: Vec<(&'a Stmt, Option<&'a Expr>)>, + pub(crate) yields: Vec<&'a Expr>, + pub(crate) elses: Vec<&'a Stmt>, + pub(crate) elifs: Vec<&'a Stmt>, + pub(crate) references: FxHashMap<&'a str, Vec>, + pub(crate) non_locals: FxHashSet<&'a str>, + pub(crate) assignments: FxHashMap<&'a str, Vec>, + pub(crate) loops: Vec, + pub(crate) tries: Vec, } #[derive(Default)] -pub struct ReturnVisitor<'a> { - pub stack: Stack<'a>, +pub(crate) struct ReturnVisitor<'a> { + pub(crate) stack: Stack<'a>, parents: Vec<&'a Stmt>, } diff --git a/crates/ruff/src/rules/flake8_self/rules/mod.rs b/crates/ruff/src/rules/flake8_self/rules/mod.rs index 6eca540bf2..edd1f1a2f7 100644 --- a/crates/ruff/src/rules/flake8_self/rules/mod.rs +++ b/crates/ruff/src/rules/flake8_self/rules/mod.rs @@ -1,3 +1,3 @@ -pub use private_member_access::{private_member_access, PrivateMemberAccess}; +pub(crate) use private_member_access::{private_member_access, PrivateMemberAccess}; mod private_member_access; diff --git a/crates/ruff/src/rules/flake8_self/rules/private_member_access.rs b/crates/ruff/src/rules/flake8_self/rules/private_member_access.rs index f97ac69711..d3feab126e 100644 --- a/crates/ruff/src/rules/flake8_self/rules/private_member_access.rs +++ b/crates/ruff/src/rules/flake8_self/rules/private_member_access.rs @@ -61,7 +61,7 @@ impl Violation for PrivateMemberAccess { } /// SLF001 -pub fn private_member_access(checker: &mut Checker, expr: &Expr) { +pub(crate) fn private_member_access(checker: &mut Checker, expr: &Expr) { if let ExprKind::Attribute(ast::ExprAttribute { value, attr, .. }) = &expr.node { if (attr.starts_with("__") && !attr.ends_with("__")) || (attr.starts_with('_') && !attr.starts_with("__")) diff --git a/crates/ruff/src/rules/flake8_simplify/rules/ast_bool_op.rs b/crates/ruff/src/rules/flake8_simplify/rules/ast_bool_op.rs index 5141ab41e2..712cc5aaa7 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/ast_bool_op.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/ast_bool_op.rs @@ -127,7 +127,7 @@ impl AlwaysAutofixableViolation for ExprOrNotExpr { } #[derive(Debug, PartialEq, Eq)] -pub enum ContentAround { +pub(crate) enum ContentAround { Before, After, Both, @@ -252,7 +252,7 @@ fn is_same_expr<'a>(a: &'a Expr, b: &'a Expr) -> Option<&'a str> { } /// SIM101 -pub fn duplicate_isinstance_call(checker: &mut Checker, expr: &Expr) { +pub(crate) fn duplicate_isinstance_call(checker: &mut Checker, expr: &Expr) { let ExprKind::BoolOp(ast::ExprBoolOp { op: Boolop::Or, values } )= &expr.node else { return; }; @@ -402,7 +402,7 @@ fn match_eq_target(expr: &Expr) -> Option<(&str, &Expr)> { } /// SIM109 -pub fn compare_with_tuple(checker: &mut Checker, expr: &Expr) { +pub(crate) fn compare_with_tuple(checker: &mut Checker, expr: &Expr) { let ExprKind::BoolOp(ast::ExprBoolOp { op: Boolop::Or, values }) = &expr.node else { return; }; @@ -484,7 +484,7 @@ pub fn compare_with_tuple(checker: &mut Checker, expr: &Expr) { } /// SIM220 -pub fn expr_and_not_expr(checker: &mut Checker, expr: &Expr) { +pub(crate) fn expr_and_not_expr(checker: &mut Checker, expr: &Expr) { let ExprKind::BoolOp(ast::ExprBoolOp { op: Boolop::And, values, }) = &expr.node else { return; }; @@ -538,7 +538,7 @@ pub fn expr_and_not_expr(checker: &mut Checker, expr: &Expr) { } /// SIM221 -pub fn expr_or_not_expr(checker: &mut Checker, expr: &Expr) { +pub(crate) fn expr_or_not_expr(checker: &mut Checker, expr: &Expr) { let ExprKind::BoolOp(ast::ExprBoolOp { op: Boolop::Or, values, }) = &expr.node else { return; }; @@ -591,7 +591,7 @@ pub fn expr_or_not_expr(checker: &mut Checker, expr: &Expr) { } } -pub fn get_short_circuit_edit( +pub(crate) fn get_short_circuit_edit( expr: &Expr, range: TextRange, truthiness: Truthiness, @@ -692,7 +692,7 @@ fn is_short_circuit( } /// SIM222 -pub fn expr_or_true(checker: &mut Checker, expr: &Expr) { +pub(crate) fn expr_or_true(checker: &mut Checker, expr: &Expr) { if let Some((edit, remove)) = is_short_circuit(expr, &Boolop::Or, &checker.ctx, checker.stylist) { let mut diagnostic = Diagnostic::new( @@ -711,7 +711,7 @@ pub fn expr_or_true(checker: &mut Checker, expr: &Expr) { } /// SIM223 -pub fn expr_and_false(checker: &mut Checker, expr: &Expr) { +pub(crate) fn expr_and_false(checker: &mut Checker, expr: &Expr) { if let Some((edit, remove)) = is_short_circuit(expr, &Boolop::And, &checker.ctx, checker.stylist) { diff --git a/crates/ruff/src/rules/flake8_simplify/rules/ast_expr.rs b/crates/ruff/src/rules/flake8_simplify/rules/ast_expr.rs index dabe1170e9..90740e77ef 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/ast_expr.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/ast_expr.rs @@ -69,7 +69,7 @@ impl AlwaysAutofixableViolation for DictGetWithNoneDefault { } /// SIM112 -pub fn use_capital_environment_variables(checker: &mut Checker, expr: &Expr) { +pub(crate) fn use_capital_environment_variables(checker: &mut Checker, expr: &Expr) { // Ex) `os.environ['foo']` if let ExprKind::Subscript(_) = &expr.node { check_os_environ_subscript(checker, expr); @@ -154,7 +154,7 @@ fn check_os_environ_subscript(checker: &mut Checker, expr: &Expr) { } /// SIM910 -pub fn dict_get_with_none_default(checker: &mut Checker, expr: &Expr) { +pub(crate) fn dict_get_with_none_default(checker: &mut Checker, expr: &Expr) { let ExprKind::Call(ast::ExprCall { func, args, keywords }) = &expr.node else { return; }; diff --git a/crates/ruff/src/rules/flake8_simplify/rules/ast_if.rs b/crates/ruff/src/rules/flake8_simplify/rules/ast_if.rs index b453e1e064..28f7786a62 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/ast_if.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/ast_if.rs @@ -221,7 +221,7 @@ fn find_last_nested_if(body: &[Stmt]) -> Option<(&Expr, &Stmt)> { } /// SIM102 -pub fn nested_if_statements( +pub(crate) fn nested_if_statements( checker: &mut Checker, stmt: &Stmt, test: &Expr, @@ -336,7 +336,7 @@ fn is_one_line_return_bool(stmts: &[Stmt]) -> Option { } /// SIM103 -pub fn needless_bool(checker: &mut Checker, stmt: &Stmt) { +pub(crate) fn needless_bool(checker: &mut Checker, stmt: &Stmt) { let StmtKind::If(ast::StmtIf { test, body, orelse }) = &stmt.node else { return; }; @@ -416,7 +416,7 @@ fn contains_call_path(ctx: &Context, expr: &Expr, target: &[&str]) -> bool { } /// SIM108 -pub fn use_ternary_operator(checker: &mut Checker, stmt: &Stmt, parent: Option<&Stmt>) { +pub(crate) fn use_ternary_operator(checker: &mut Checker, stmt: &Stmt, parent: Option<&Stmt>) { let StmtKind::If(ast::StmtIf { test, body, orelse } )= &stmt.node else { return; }; @@ -549,7 +549,7 @@ fn get_if_body_pairs<'a>( } /// SIM114 -pub fn if_with_same_arms(checker: &mut Checker, stmt: &Stmt, parent: Option<&Stmt>) { +pub(crate) fn if_with_same_arms(checker: &mut Checker, stmt: &Stmt, parent: Option<&Stmt>) { let StmtKind::If(ast::StmtIf { test, body, orelse }) = &stmt.node else { return; }; @@ -601,7 +601,7 @@ pub fn if_with_same_arms(checker: &mut Checker, stmt: &Stmt, parent: Option<&Stm } /// SIM116 -pub fn manual_dict_lookup( +pub(crate) fn manual_dict_lookup( checker: &mut Checker, stmt: &Stmt, test: &Expr, @@ -747,7 +747,7 @@ pub fn manual_dict_lookup( } /// SIM401 -pub fn use_dict_get_with_default( +pub(crate) fn use_dict_get_with_default( checker: &mut Checker, stmt: &Stmt, test: &Expr, diff --git a/crates/ruff/src/rules/flake8_simplify/rules/ast_ifexp.rs b/crates/ruff/src/rules/flake8_simplify/rules/ast_ifexp.rs index f076701f5b..115646b22b 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/ast_ifexp.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/ast_ifexp.rs @@ -74,7 +74,7 @@ impl AlwaysAutofixableViolation for IfExprWithTwistedArms { } /// SIM210 -pub fn explicit_true_false_in_ifexpr( +pub(crate) fn explicit_true_false_in_ifexpr( checker: &mut Checker, expr: &Expr, test: &Expr, @@ -129,7 +129,7 @@ pub fn explicit_true_false_in_ifexpr( } /// SIM211 -pub fn explicit_false_true_in_ifexpr( +pub(crate) fn explicit_false_true_in_ifexpr( checker: &mut Checker, expr: &Expr, test: &Expr, @@ -172,7 +172,7 @@ pub fn explicit_false_true_in_ifexpr( } /// SIM212 -pub fn twisted_arms_in_ifexpr( +pub(crate) fn twisted_arms_in_ifexpr( checker: &mut Checker, expr: &Expr, test: &Expr, diff --git a/crates/ruff/src/rules/flake8_simplify/rules/ast_unary_op.rs b/crates/ruff/src/rules/flake8_simplify/rules/ast_unary_op.rs index 8bbabcca09..43297852e8 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/ast_unary_op.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/ast_unary_op.rs @@ -78,7 +78,12 @@ fn is_exception_check(stmt: &Stmt) -> bool { } /// SIM201 -pub fn negation_with_equal_op(checker: &mut Checker, expr: &Expr, op: &Unaryop, operand: &Expr) { +pub(crate) fn negation_with_equal_op( + checker: &mut Checker, + expr: &Expr, + op: &Unaryop, + operand: &Expr, +) { if !matches!(op, Unaryop::Not) { return; } @@ -124,7 +129,7 @@ pub fn negation_with_equal_op(checker: &mut Checker, expr: &Expr, op: &Unaryop, } /// SIM202 -pub fn negation_with_not_equal_op( +pub(crate) fn negation_with_not_equal_op( checker: &mut Checker, expr: &Expr, op: &Unaryop, @@ -175,7 +180,7 @@ pub fn negation_with_not_equal_op( } /// SIM208 -pub fn double_negation(checker: &mut Checker, expr: &Expr, op: &Unaryop, operand: &Expr) { +pub(crate) fn double_negation(checker: &mut Checker, expr: &Expr, op: &Unaryop, operand: &Expr) { if !matches!(op, Unaryop::Not) { return; } diff --git a/crates/ruff/src/rules/flake8_simplify/rules/ast_with.rs b/crates/ruff/src/rules/flake8_simplify/rules/ast_with.rs index 9c787c10cf..2437b9a29c 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/ast_with.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/ast_with.rs @@ -66,7 +66,7 @@ fn find_last_with(body: &[Stmt]) -> Option<(&Vec, &Vec)> { } /// SIM117 -pub fn multiple_with_statements( +pub(crate) fn multiple_with_statements( checker: &mut Checker, with_stmt: &Stmt, with_body: &[Stmt], diff --git a/crates/ruff/src/rules/flake8_simplify/rules/key_in_dict.rs b/crates/ruff/src/rules/flake8_simplify/rules/key_in_dict.rs index 18abf6e9bf..0e803c1cdb 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/key_in_dict.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/key_in_dict.rs @@ -101,7 +101,7 @@ fn key_in_dict(checker: &mut Checker, left: &Expr, right: &Expr, range: TextRang } /// SIM118 in a for loop -pub fn key_in_dict_for(checker: &mut Checker, target: &Expr, iter: &Expr) { +pub(crate) fn key_in_dict_for(checker: &mut Checker, target: &Expr, iter: &Expr) { key_in_dict( checker, target, @@ -111,7 +111,7 @@ pub fn key_in_dict_for(checker: &mut Checker, target: &Expr, iter: &Expr) { } /// SIM118 in a comparison -pub fn key_in_dict_compare( +pub(crate) fn key_in_dict_compare( checker: &mut Checker, expr: &Expr, left: &Expr, diff --git a/crates/ruff/src/rules/flake8_simplify/rules/mod.rs b/crates/ruff/src/rules/flake8_simplify/rules/mod.rs index 5cd8424536..80a9ad752d 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/mod.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/mod.rs @@ -1,34 +1,36 @@ -pub use ast_bool_op::{ +pub(crate) use ast_bool_op::{ compare_with_tuple, duplicate_isinstance_call, expr_and_false, expr_and_not_expr, expr_or_not_expr, expr_or_true, CompareWithTuple, DuplicateIsinstanceCall, ExprAndFalse, ExprAndNotExpr, ExprOrNotExpr, ExprOrTrue, }; -pub use ast_expr::{ +pub(crate) use ast_expr::{ dict_get_with_none_default, use_capital_environment_variables, DictGetWithNoneDefault, UncapitalizedEnvironmentVariables, }; -pub use ast_if::{ +pub(crate) use ast_if::{ if_with_same_arms, manual_dict_lookup, needless_bool, nested_if_statements, use_dict_get_with_default, use_ternary_operator, CollapsibleIf, IfElseBlockInsteadOfDictGet, IfElseBlockInsteadOfDictLookup, IfElseBlockInsteadOfIfExp, IfWithSameArms, NeedlessBool, }; -pub use ast_ifexp::{ +pub(crate) use ast_ifexp::{ explicit_false_true_in_ifexpr, explicit_true_false_in_ifexpr, twisted_arms_in_ifexpr, IfExprWithFalseTrue, IfExprWithTrueFalse, IfExprWithTwistedArms, }; -pub use ast_unary_op::{ +pub(crate) use ast_unary_op::{ double_negation, negation_with_equal_op, negation_with_not_equal_op, DoubleNegation, NegateEqualOp, NegateNotEqualOp, }; -pub use ast_with::{multiple_with_statements, MultipleWithStatements}; -pub use key_in_dict::{key_in_dict_compare, key_in_dict_for, InDictKeys}; -pub use open_file_with_context_handler::{ +pub(crate) use ast_with::{multiple_with_statements, MultipleWithStatements}; +pub(crate) use key_in_dict::{key_in_dict_compare, key_in_dict_for, InDictKeys}; +pub(crate) use open_file_with_context_handler::{ open_file_with_context_handler, OpenFileWithContextHandler, }; -pub use reimplemented_builtin::{convert_for_loop_to_any_all, ReimplementedBuiltin}; -pub use return_in_try_except_finally::{return_in_try_except_finally, ReturnInTryExceptFinally}; -pub use suppressible_exception::{suppressible_exception, SuppressibleException}; -pub use yoda_conditions::{yoda_conditions, YodaConditions}; +pub(crate) use reimplemented_builtin::{convert_for_loop_to_any_all, ReimplementedBuiltin}; +pub(crate) use return_in_try_except_finally::{ + return_in_try_except_finally, ReturnInTryExceptFinally, +}; +pub(crate) use suppressible_exception::{suppressible_exception, SuppressibleException}; +pub(crate) use yoda_conditions::{yoda_conditions, YodaConditions}; mod ast_bool_op; mod ast_expr; diff --git a/crates/ruff/src/rules/flake8_simplify/rules/open_file_with_context_handler.rs b/crates/ruff/src/rules/flake8_simplify/rules/open_file_with_context_handler.rs index 381699217a..db06e57b52 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/open_file_with_context_handler.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/open_file_with_context_handler.rs @@ -113,7 +113,7 @@ fn match_exit_stack(checker: &Checker) -> bool { } /// SIM115 -pub fn open_file_with_context_handler(checker: &mut Checker, func: &Expr) { +pub(crate) fn open_file_with_context_handler(checker: &mut Checker, func: &Expr) { if checker .ctx .resolve_call_path(func) diff --git a/crates/ruff/src/rules/flake8_simplify/rules/reimplemented_builtin.rs b/crates/ruff/src/rules/flake8_simplify/rules/reimplemented_builtin.rs index 543c2ba31c..a841210afc 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/reimplemented_builtin.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/reimplemented_builtin.rs @@ -196,7 +196,11 @@ fn return_stmt(id: &str, test: &Expr, target: &Expr, iter: &Expr, stylist: &Styl } /// SIM110, SIM111 -pub fn convert_for_loop_to_any_all(checker: &mut Checker, stmt: &Stmt, sibling: Option<&Stmt>) { +pub(crate) fn convert_for_loop_to_any_all( + checker: &mut Checker, + stmt: &Stmt, + sibling: Option<&Stmt>, +) { // There are two cases to consider: // - `for` loop with an `else: return True` or `else: return False`. // - `for` loop followed by `return True` or `return False` diff --git a/crates/ruff/src/rules/flake8_simplify/rules/return_in_try_except_finally.rs b/crates/ruff/src/rules/flake8_simplify/rules/return_in_try_except_finally.rs index 2e99808541..664bd40343 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/return_in_try_except_finally.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/return_in_try_except_finally.rs @@ -56,7 +56,7 @@ fn find_return(stmts: &[Stmt]) -> Option<&Stmt> { } /// SIM107 -pub fn return_in_try_except_finally( +pub(crate) fn return_in_try_except_finally( checker: &mut Checker, body: &[Stmt], handlers: &[Excepthandler], diff --git a/crates/ruff/src/rules/flake8_simplify/rules/suppressible_exception.rs b/crates/ruff/src/rules/flake8_simplify/rules/suppressible_exception.rs index eadfea4914..dbb872cad5 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/suppressible_exception.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/suppressible_exception.rs @@ -35,7 +35,7 @@ impl Violation for SuppressibleException { } /// SIM105 -pub fn suppressible_exception( +pub(crate) fn suppressible_exception( checker: &mut Checker, stmt: &Stmt, try_body: &[Stmt], diff --git a/crates/ruff/src/rules/flake8_simplify/rules/yoda_conditions.rs b/crates/ruff/src/rules/flake8_simplify/rules/yoda_conditions.rs index 46dea18877..00dd021682 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/yoda_conditions.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/yoda_conditions.rs @@ -126,7 +126,7 @@ fn reverse_comparison(expr: &Expr, locator: &Locator, stylist: &Stylist) -> Resu } /// SIM300 -pub fn yoda_conditions( +pub(crate) fn yoda_conditions( checker: &mut Checker, expr: &Expr, left: &Expr, diff --git a/crates/ruff/src/rules/flake8_type_checking/helpers.rs b/crates/ruff/src/rules/flake8_type_checking/helpers.rs index 2d1f2b1580..12b5e67ffc 100644 --- a/crates/ruff/src/rules/flake8_type_checking/helpers.rs +++ b/crates/ruff/src/rules/flake8_type_checking/helpers.rs @@ -8,7 +8,7 @@ use ruff_python_semantic::context::Context; use ruff_python_semantic::scope::ScopeKind; /// Return `true` if [`Expr`] is a guard for a type-checking block. -pub fn is_type_checking_block(context: &Context, test: &Expr) -> bool { +pub(crate) fn is_type_checking_block(context: &Context, test: &Expr) -> bool { // Ex) `if False:` if matches!( test.node, @@ -41,7 +41,7 @@ pub fn is_type_checking_block(context: &Context, test: &Expr) -> bool { false } -pub const fn is_valid_runtime_import(binding: &Binding) -> bool { +pub(crate) const fn is_valid_runtime_import(binding: &Binding) -> bool { if matches!( binding.kind, BindingKind::Importation(..) @@ -54,7 +54,7 @@ pub const fn is_valid_runtime_import(binding: &Binding) -> bool { } } -pub fn runtime_evaluated( +pub(crate) fn runtime_evaluated( context: &Context, base_classes: &[String], decorators: &[String], diff --git a/crates/ruff/src/rules/flake8_type_checking/rules/empty_type_checking_block.rs b/crates/ruff/src/rules/flake8_type_checking/rules/empty_type_checking_block.rs index 455c2d98a1..2dbece9459 100644 --- a/crates/ruff/src/rules/flake8_type_checking/rules/empty_type_checking_block.rs +++ b/crates/ruff/src/rules/flake8_type_checking/rules/empty_type_checking_block.rs @@ -48,7 +48,7 @@ impl AlwaysAutofixableViolation for EmptyTypeCheckingBlock { } /// TCH005 -pub fn empty_type_checking_block<'a, 'b>( +pub(crate) fn empty_type_checking_block<'a, 'b>( checker: &mut Checker<'a>, stmt: &'a Stmt, body: &'a [Stmt], diff --git a/crates/ruff/src/rules/flake8_type_checking/rules/mod.rs b/crates/ruff/src/rules/flake8_type_checking/rules/mod.rs index 2b610f9833..3873ebd1e7 100644 --- a/crates/ruff/src/rules/flake8_type_checking/rules/mod.rs +++ b/crates/ruff/src/rules/flake8_type_checking/rules/mod.rs @@ -1,8 +1,8 @@ -pub use empty_type_checking_block::{empty_type_checking_block, EmptyTypeCheckingBlock}; -pub use runtime_import_in_type_checking_block::{ +pub(crate) use empty_type_checking_block::{empty_type_checking_block, EmptyTypeCheckingBlock}; +pub(crate) use runtime_import_in_type_checking_block::{ runtime_import_in_type_checking_block, RuntimeImportInTypeCheckingBlock, }; -pub use typing_only_runtime_import::{ +pub(crate) use typing_only_runtime_import::{ typing_only_runtime_import, TypingOnlyFirstPartyImport, TypingOnlyStandardLibraryImport, TypingOnlyThirdPartyImport, }; diff --git a/crates/ruff/src/rules/flake8_type_checking/rules/runtime_import_in_type_checking_block.rs b/crates/ruff/src/rules/flake8_type_checking/rules/runtime_import_in_type_checking_block.rs index 2c7befe22a..81eb309dc0 100644 --- a/crates/ruff/src/rules/flake8_type_checking/rules/runtime_import_in_type_checking_block.rs +++ b/crates/ruff/src/rules/flake8_type_checking/rules/runtime_import_in_type_checking_block.rs @@ -51,7 +51,7 @@ impl Violation for RuntimeImportInTypeCheckingBlock { } /// TCH004 -pub fn runtime_import_in_type_checking_block(binding: &Binding) -> Option { +pub(crate) fn runtime_import_in_type_checking_block(binding: &Binding) -> Option { let full_name = match &binding.kind { BindingKind::Importation(Importation { full_name, .. }) => full_name, BindingKind::FromImportation(FromImportation { full_name, .. }) => full_name.as_str(), diff --git a/crates/ruff/src/rules/flake8_type_checking/rules/typing_only_runtime_import.rs b/crates/ruff/src/rules/flake8_type_checking/rules/typing_only_runtime_import.rs index 82bb28f204..64b01fe628 100644 --- a/crates/ruff/src/rules/flake8_type_checking/rules/typing_only_runtime_import.rs +++ b/crates/ruff/src/rules/flake8_type_checking/rules/typing_only_runtime_import.rs @@ -240,7 +240,7 @@ fn is_exempt(name: &str, exempt_modules: &[&str]) -> bool { } /// TCH001 -pub fn typing_only_runtime_import( +pub(crate) fn typing_only_runtime_import( binding: &Binding, runtime_imports: &[&Binding], package: Option<&Path>, diff --git a/crates/ruff/src/rules/flake8_unused_arguments/helpers.rs b/crates/ruff/src/rules/flake8_unused_arguments/helpers.rs index 7f487f3522..4f887fceaa 100644 --- a/crates/ruff/src/rules/flake8_unused_arguments/helpers.rs +++ b/crates/ruff/src/rules/flake8_unused_arguments/helpers.rs @@ -38,7 +38,7 @@ fn is_empty_stmt(stmt: &Stmt) -> bool { false } -pub fn is_empty(body: &[Stmt]) -> bool { +pub(crate) fn is_empty(body: &[Stmt]) -> bool { match &body { [] => true, [stmt] => is_docstring_stmt(stmt) || is_empty_stmt(stmt), diff --git a/crates/ruff/src/rules/flake8_unused_arguments/rules.rs b/crates/ruff/src/rules/flake8_unused_arguments/rules.rs index 716cbbe56c..d91b55b9de 100644 --- a/crates/ruff/src/rules/flake8_unused_arguments/rules.rs +++ b/crates/ruff/src/rules/flake8_unused_arguments/rules.rs @@ -277,7 +277,7 @@ fn call<'a>( } /// ARG001, ARG002, ARG003, ARG004, ARG005 -pub fn unused_arguments( +pub(crate) fn unused_arguments( checker: &Checker, parent: &Scope, scope: &Scope, diff --git a/crates/ruff/src/rules/flake8_unused_arguments/types.rs b/crates/ruff/src/rules/flake8_unused_arguments/types.rs index b4a8c6d871..778e53c556 100644 --- a/crates/ruff/src/rules/flake8_unused_arguments/types.rs +++ b/crates/ruff/src/rules/flake8_unused_arguments/types.rs @@ -6,7 +6,7 @@ use super::rules; /// An AST node that can contain arguments. #[derive(Copy, Clone)] -pub enum Argumentable { +pub(crate) enum Argumentable { Function, Method, ClassMethod, @@ -15,7 +15,7 @@ pub enum Argumentable { } impl Argumentable { - pub fn check_for(self, name: String) -> DiagnosticKind { + pub(crate) fn check_for(self, name: String) -> DiagnosticKind { match self { Self::Function => rules::UnusedFunctionArgument { name }.into(), Self::Method => rules::UnusedMethodArgument { name }.into(), @@ -25,7 +25,7 @@ impl Argumentable { } } - pub const fn rule_code(self) -> Rule { + pub(crate) const fn rule_code(self) -> Rule { match self { Self::Function => Rule::UnusedFunctionArgument, Self::Method => Rule::UnusedMethodArgument, diff --git a/crates/ruff/src/rules/flake8_use_pathlib/helpers.rs b/crates/ruff/src/rules/flake8_use_pathlib/helpers.rs index 4a9378db09..e59596558d 100644 --- a/crates/ruff/src/rules/flake8_use_pathlib/helpers.rs +++ b/crates/ruff/src/rules/flake8_use_pathlib/helpers.rs @@ -11,7 +11,7 @@ use crate::rules::flake8_use_pathlib::violations::{ use crate::settings::types::PythonVersion; use ruff_diagnostics::{Diagnostic, DiagnosticKind}; -pub fn replaceable_by_pathlib(checker: &mut Checker, expr: &Expr) { +pub(crate) fn replaceable_by_pathlib(checker: &mut Checker, expr: &Expr) { if let Some(diagnostic_kind) = checker .ctx diff --git a/crates/ruff/src/rules/flynt/rules/mod.rs b/crates/ruff/src/rules/flynt/rules/mod.rs index 36bc617982..d3bd2e2746 100644 --- a/crates/ruff/src/rules/flynt/rules/mod.rs +++ b/crates/ruff/src/rules/flynt/rules/mod.rs @@ -1,3 +1,3 @@ mod static_join_to_fstring; -pub use static_join_to_fstring::{static_join_to_fstring, StaticJoinToFString}; +pub(crate) use static_join_to_fstring::{static_join_to_fstring, StaticJoinToFString}; diff --git a/crates/ruff/src/rules/flynt/rules/static_join_to_fstring.rs b/crates/ruff/src/rules/flynt/rules/static_join_to_fstring.rs index 85e8b4a657..486120cb7f 100644 --- a/crates/ruff/src/rules/flynt/rules/static_join_to_fstring.rs +++ b/crates/ruff/src/rules/flynt/rules/static_join_to_fstring.rs @@ -51,7 +51,7 @@ fn build_fstring(joiner: &str, joinees: &[Expr]) -> Option { })) } -pub fn static_join_to_fstring(checker: &mut Checker, expr: &Expr, joiner: &str) { +pub(crate) fn static_join_to_fstring(checker: &mut Checker, expr: &Expr, joiner: &str) { let ExprKind::Call(ast::ExprCall { args, keywords, diff --git a/crates/ruff/src/rules/isort/annotate.rs b/crates/ruff/src/rules/isort/annotate.rs index 1cfa1d1a2e..048d686d64 100644 --- a/crates/ruff/src/rules/isort/annotate.rs +++ b/crates/ruff/src/rules/isort/annotate.rs @@ -8,7 +8,7 @@ use super::helpers::trailing_comma; use super::types::{AliasData, TrailingComma}; use super::{AnnotatedAliasData, AnnotatedImport}; -pub fn annotate_imports<'a>( +pub(crate) fn annotate_imports<'a>( imports: &'a [&'a Stmt], comments: Vec>, locator: &Locator, diff --git a/crates/ruff/src/rules/isort/categorize.rs b/crates/ruff/src/rules/isort/categorize.rs index 4009baed60..2998f5c48a 100644 --- a/crates/ruff/src/rules/isort/categorize.rs +++ b/crates/ruff/src/rules/isort/categorize.rs @@ -136,7 +136,7 @@ fn match_sources<'a>(paths: &'a [PathBuf], base: &str) -> Option<&'a Path> { } #[allow(clippy::too_many_arguments)] -pub fn categorize_imports<'a>( +pub(crate) fn categorize_imports<'a>( block: ImportBlock<'a>, src: &[PathBuf], package: Option<&Path>, diff --git a/crates/ruff/src/rules/isort/comments.rs b/crates/ruff/src/rules/isort/comments.rs index af1040a4e4..7b4d7417d8 100644 --- a/crates/ruff/src/rules/isort/comments.rs +++ b/crates/ruff/src/rules/isort/comments.rs @@ -26,7 +26,7 @@ impl Comment<'_> { } /// Collect all comments in an import block. -pub fn collect_comments<'a>(range: TextRange, locator: &'a Locator) -> Vec> { +pub(crate) fn collect_comments<'a>(range: TextRange, locator: &'a Locator) -> Vec> { let contents = locator.slice(range); lexer::lex_starts_at(contents, Mode::Module, range.start()) .flatten() diff --git a/crates/ruff/src/rules/isort/format.rs b/crates/ruff/src/rules/isort/format.rs index da06c1b818..4304d86f5d 100644 --- a/crates/ruff/src/rules/isort/format.rs +++ b/crates/ruff/src/rules/isort/format.rs @@ -7,7 +7,7 @@ use super::types::{AliasData, CommentSet, ImportFromData, Importable}; const CAPACITY: usize = 200; /// Add a plain import statement to the [`RopeBuilder`]. -pub fn format_import( +pub(crate) fn format_import( alias: &AliasData, comments: &CommentSet, is_first: bool, @@ -40,7 +40,7 @@ pub fn format_import( /// Add an import-from statement to the [`RopeBuilder`]. #[allow(clippy::too_many_arguments)] -pub fn format_import_from( +pub(crate) fn format_import_from( import_from: &ImportFromData, comments: &CommentSet, aliases: &[(AliasData, CommentSet)], diff --git a/crates/ruff/src/rules/isort/helpers.rs b/crates/ruff/src/rules/isort/helpers.rs index 1bc40e4bf3..1a3bae8c5a 100644 --- a/crates/ruff/src/rules/isort/helpers.rs +++ b/crates/ruff/src/rules/isort/helpers.rs @@ -8,7 +8,7 @@ use crate::rules::isort::types::TrailingComma; /// Return `true` if a `StmtKind::ImportFrom` statement ends with a magic /// trailing comma. -pub fn trailing_comma(stmt: &Stmt, locator: &Locator) -> TrailingComma { +pub(crate) fn trailing_comma(stmt: &Stmt, locator: &Locator) -> TrailingComma { let contents = locator.slice(stmt.range()); let mut count: usize = 0; let mut trailing_comma = TrailingComma::Absent; @@ -36,7 +36,7 @@ pub fn trailing_comma(stmt: &Stmt, locator: &Locator) -> TrailingComma { } /// Return `true` if a [`Stmt`] is preceded by a "comment break" -pub fn has_comment_break(stmt: &Stmt, locator: &Locator) -> bool { +pub(crate) fn has_comment_break(stmt: &Stmt, locator: &Locator) -> bool { // Starting from the `Stmt` (`def f(): pass`), we want to detect patterns like // this: // diff --git a/crates/ruff/src/rules/isort/normalize.rs b/crates/ruff/src/rules/isort/normalize.rs index bce474247a..b626d03ede 100644 --- a/crates/ruff/src/rules/isort/normalize.rs +++ b/crates/ruff/src/rules/isort/normalize.rs @@ -4,7 +4,7 @@ use std::collections::BTreeSet; use super::types::{AliasData, ImportBlock, ImportFromData}; use super::AnnotatedImport; -pub fn normalize_imports<'a>( +pub(crate) fn normalize_imports<'a>( imports: Vec>, combine_as_imports: bool, force_single_line: bool, diff --git a/crates/ruff/src/rules/isort/order.rs b/crates/ruff/src/rules/isort/order.rs index 58c1c91740..1f1e786518 100644 --- a/crates/ruff/src/rules/isort/order.rs +++ b/crates/ruff/src/rules/isort/order.rs @@ -9,7 +9,7 @@ use super::settings::RelativeImportsOrder; use super::sorting::{cmp_import_from, cmp_members, cmp_modules}; use super::types::{AliasData, CommentSet, ImportBlock, OrderedImportBlock}; -pub fn order_imports<'a>( +pub(crate) fn order_imports<'a>( block: ImportBlock<'a>, order_by_type: bool, relative_imports_order: RelativeImportsOrder, diff --git a/crates/ruff/src/rules/isort/rules/add_required_imports.rs b/crates/ruff/src/rules/isort/rules/add_required_imports.rs index 8cd65dccc1..32fa9800be 100644 --- a/crates/ruff/src/rules/isort/rules/add_required_imports.rs +++ b/crates/ruff/src/rules/isort/rules/add_required_imports.rs @@ -129,7 +129,7 @@ fn add_required_import( } /// I002 -pub fn add_required_imports( +pub(crate) fn add_required_imports( blocks: &[&Block], python_ast: &Suite, locator: &Locator, diff --git a/crates/ruff/src/rules/isort/rules/mod.rs b/crates/ruff/src/rules/isort/rules/mod.rs index a6aded22ff..0184926441 100644 --- a/crates/ruff/src/rules/isort/rules/mod.rs +++ b/crates/ruff/src/rules/isort/rules/mod.rs @@ -1,5 +1,5 @@ -pub use add_required_imports::{add_required_imports, MissingRequiredImport}; -pub use organize_imports::{organize_imports, UnsortedImports}; +pub(crate) use add_required_imports::{add_required_imports, MissingRequiredImport}; +pub(crate) use organize_imports::{organize_imports, UnsortedImports}; -pub mod add_required_imports; -pub mod organize_imports; +pub(crate) mod add_required_imports; +pub(crate) mod organize_imports; diff --git a/crates/ruff/src/rules/isort/rules/organize_imports.rs b/crates/ruff/src/rules/isort/rules/organize_imports.rs index 1477fc84b9..2d44d0a2b2 100644 --- a/crates/ruff/src/rules/isort/rules/organize_imports.rs +++ b/crates/ruff/src/rules/isort/rules/organize_imports.rs @@ -78,7 +78,7 @@ fn matches_ignoring_indentation(val1: &str, val2: &str) -> bool { #[allow(clippy::cast_sign_loss)] /// I001 -pub fn organize_imports( +pub(crate) fn organize_imports( block: &Block, locator: &Locator, stylist: &Stylist, diff --git a/crates/ruff/src/rules/isort/sorting.rs b/crates/ruff/src/rules/isort/sorting.rs index 7686d6eb14..e5280dafde 100644 --- a/crates/ruff/src/rules/isort/sorting.rs +++ b/crates/ruff/src/rules/isort/sorting.rs @@ -11,7 +11,7 @@ use super::types::EitherImport::{Import, ImportFrom}; use super::types::{AliasData, EitherImport, ImportFromData}; #[derive(PartialOrd, Ord, PartialEq, Eq, Copy, Clone)] -pub enum Prefix { +pub(crate) enum Prefix { Constants, Classes, Variables, @@ -52,7 +52,7 @@ fn cmp_force_to_top(name1: &str, name2: &str, force_to_top: &BTreeSet) - } /// Compare two top-level modules. -pub fn cmp_modules( +pub(crate) fn cmp_modules( alias1: &AliasData, alias2: &AliasData, force_to_top: &BTreeSet, @@ -69,7 +69,7 @@ pub fn cmp_modules( } /// Compare two member imports within `StmtKind::ImportFrom` blocks. -pub fn cmp_members( +pub(crate) fn cmp_members( alias1: &AliasData, alias2: &AliasData, order_by_type: bool, @@ -94,7 +94,7 @@ pub fn cmp_members( } /// Compare two relative import levels. -pub fn cmp_levels( +pub(crate) fn cmp_levels( level1: Option, level2: Option, relative_imports_order: RelativeImportsOrder, @@ -111,7 +111,7 @@ pub fn cmp_levels( } /// Compare two `StmtKind::ImportFrom` blocks. -pub fn cmp_import_from( +pub(crate) fn cmp_import_from( import_from1: &ImportFromData, import_from2: &ImportFromData, relative_imports_order: RelativeImportsOrder, @@ -151,7 +151,7 @@ fn cmp_import_import_from( /// Compare two [`EitherImport`] enums which may be [`Import`] or [`ImportFrom`] /// structs. -pub fn cmp_either_import( +pub(crate) fn cmp_either_import( a: &EitherImport, b: &EitherImport, relative_imports_order: RelativeImportsOrder, diff --git a/crates/ruff/src/rules/isort/split.rs b/crates/ruff/src/rules/isort/split.rs index 70fd474e34..c2059bada0 100644 --- a/crates/ruff/src/rules/isort/split.rs +++ b/crates/ruff/src/rules/isort/split.rs @@ -17,7 +17,7 @@ fn find_block_index(forced_separate: &[String], imp: &dyn Importable) -> usize { /// patterns in `forced_separate`, in the order they appear in the /// `forced_separate` set. Empty blocks are retained for patterns that do not /// match any imports. -pub fn split_by_forced_separate<'a>( +pub(crate) fn split_by_forced_separate<'a>( block: ImportBlock<'a>, forced_separate: &[String], ) -> Vec> { diff --git a/crates/ruff/src/rules/isort/track.rs b/crates/ruff/src/rules/isort/track.rs index b0b33249df..9ceb7aa6d5 100644 --- a/crates/ruff/src/rules/isort/track.rs +++ b/crates/ruff/src/rules/isort/track.rs @@ -21,7 +21,7 @@ pub struct Block<'a> { pub trailer: Option, } -pub struct ImportTracker<'a> { +pub(crate) struct ImportTracker<'a> { locator: &'a Locator<'a>, is_stub: bool, blocks: Vec>, @@ -31,7 +31,11 @@ pub struct ImportTracker<'a> { } impl<'a> ImportTracker<'a> { - pub fn new(locator: &'a Locator<'a>, directives: &'a IsortDirectives, is_stub: bool) -> Self { + pub(crate) fn new( + locator: &'a Locator<'a>, + directives: &'a IsortDirectives, + is_stub: bool, + ) -> Self { Self { locator, is_stub, @@ -99,7 +103,7 @@ impl<'a> ImportTracker<'a> { } } - pub fn iter<'b>(&'a self) -> impl Iterator> + pub(crate) fn iter<'b>(&'a self) -> impl Iterator> where 'a: 'b, { diff --git a/crates/ruff/src/rules/isort/types.rs b/crates/ruff/src/rules/isort/types.rs index de23e5a2d0..c99b50e40f 100644 --- a/crates/ruff/src/rules/isort/types.rs +++ b/crates/ruff/src/rules/isort/types.rs @@ -12,9 +12,9 @@ pub enum TrailingComma { } #[derive(Debug, Hash, Ord, PartialOrd, Eq, PartialEq, Clone)] -pub struct ImportFromData<'a> { - pub module: Option<&'a str>, - pub level: Option, +pub(crate) struct ImportFromData<'a> { + pub(crate) module: Option<&'a str>, + pub(crate) level: Option, } #[derive(Debug, Hash, Ord, PartialOrd, Eq, PartialEq)] @@ -24,12 +24,12 @@ pub struct AliasData<'a> { } #[derive(Debug, Default, Clone)] -pub struct CommentSet<'a> { - pub atop: Vec>, - pub inline: Vec>, +pub(crate) struct CommentSet<'a> { + pub(crate) atop: Vec>, + pub(crate) inline: Vec>, } -pub trait Importable { +pub(crate) trait Importable { fn module_name(&self) -> String; fn module_base(&self) -> String; } @@ -55,26 +55,27 @@ impl Importable for ImportFromData<'_> { } #[derive(Debug, Default)] -pub struct ImportFromStatement<'a> { - pub comments: CommentSet<'a>, - pub aliases: FxHashMap, CommentSet<'a>>, - pub trailing_comma: TrailingComma, +pub(crate) struct ImportFromStatement<'a> { + pub(crate) comments: CommentSet<'a>, + pub(crate) aliases: FxHashMap, CommentSet<'a>>, + pub(crate) trailing_comma: TrailingComma, } #[derive(Debug, Default)] -pub struct ImportBlock<'a> { +pub(crate) struct ImportBlock<'a> { // Set of (name, asname), used to track regular imports. // Ex) `import module` - pub import: FxHashMap, CommentSet<'a>>, + pub(crate) import: FxHashMap, CommentSet<'a>>, // Map from (module, level) to `AliasData`, used to track 'from' imports. // Ex) `from module import member` - pub import_from: FxHashMap, ImportFromStatement<'a>>, + pub(crate) import_from: FxHashMap, ImportFromStatement<'a>>, // Set of (module, level, name, asname), used to track re-exported 'from' imports. // Ex) `from module import member as member` - pub import_from_as: FxHashMap<(ImportFromData<'a>, AliasData<'a>), ImportFromStatement<'a>>, + pub(crate) import_from_as: + FxHashMap<(ImportFromData<'a>, AliasData<'a>), ImportFromStatement<'a>>, // Map from (module, level) to `AliasData`, used to track star imports. // Ex) `from module import *` - pub import_from_star: FxHashMap, ImportFromStatement<'a>>, + pub(crate) import_from_star: FxHashMap, ImportFromStatement<'a>>, } type AliasDataWithComments<'a> = (AliasData<'a>, CommentSet<'a>); @@ -88,13 +89,13 @@ type ImportFrom<'a> = ( Vec>, ); -pub enum EitherImport<'a> { +pub(crate) enum EitherImport<'a> { Import(Import<'a>), ImportFrom(ImportFrom<'a>), } #[derive(Debug, Default)] -pub struct OrderedImportBlock<'a> { - pub import: Vec>, - pub import_from: Vec>, +pub(crate) struct OrderedImportBlock<'a> { + pub(crate) import: Vec>, + pub(crate) import_from: Vec>, } diff --git a/crates/ruff/src/rules/mccabe/rules.rs b/crates/ruff/src/rules/mccabe/rules.rs index c20d8a548e..73e6057242 100644 --- a/crates/ruff/src/rules/mccabe/rules.rs +++ b/crates/ruff/src/rules/mccabe/rules.rs @@ -136,7 +136,7 @@ fn get_complexity_number(stmts: &[Stmt]) -> usize { complexity } -pub fn function_is_too_complex( +pub(crate) fn function_is_too_complex( stmt: &Stmt, name: &str, body: &[Stmt], diff --git a/crates/ruff/src/rules/numpy/rules/deprecated_type_alias.rs b/crates/ruff/src/rules/numpy/rules/deprecated_type_alias.rs index 364213f89c..70ab2c2323 100644 --- a/crates/ruff/src/rules/numpy/rules/deprecated_type_alias.rs +++ b/crates/ruff/src/rules/numpy/rules/deprecated_type_alias.rs @@ -47,7 +47,7 @@ impl AlwaysAutofixableViolation for NumpyDeprecatedTypeAlias { } /// NPY001 -pub fn deprecated_type_alias(checker: &mut Checker, expr: &Expr) { +pub(crate) fn deprecated_type_alias(checker: &mut Checker, expr: &Expr) { if let Some(type_name) = checker.ctx.resolve_call_path(expr).and_then(|call_path| { if call_path.as_slice() == ["numpy", "bool"] || call_path.as_slice() == ["numpy", "int"] diff --git a/crates/ruff/src/rules/numpy/rules/mod.rs b/crates/ruff/src/rules/numpy/rules/mod.rs index 2b1a2eea9a..c82e79bc1c 100644 --- a/crates/ruff/src/rules/numpy/rules/mod.rs +++ b/crates/ruff/src/rules/numpy/rules/mod.rs @@ -1,5 +1,5 @@ -pub use deprecated_type_alias::{deprecated_type_alias, NumpyDeprecatedTypeAlias}; -pub use numpy_legacy_random::{numpy_legacy_random, NumpyLegacyRandom}; +pub(crate) use deprecated_type_alias::{deprecated_type_alias, NumpyDeprecatedTypeAlias}; +pub(crate) use numpy_legacy_random::{numpy_legacy_random, NumpyLegacyRandom}; mod deprecated_type_alias; mod numpy_legacy_random; diff --git a/crates/ruff/src/rules/numpy/rules/numpy_legacy_random.rs b/crates/ruff/src/rules/numpy/rules/numpy_legacy_random.rs index 804911db37..3a8a7b1fa7 100644 --- a/crates/ruff/src/rules/numpy/rules/numpy_legacy_random.rs +++ b/crates/ruff/src/rules/numpy/rules/numpy_legacy_random.rs @@ -56,7 +56,7 @@ impl Violation for NumpyLegacyRandom { } /// NPY002 -pub fn numpy_legacy_random(checker: &mut Checker, expr: &Expr) { +pub(crate) fn numpy_legacy_random(checker: &mut Checker, expr: &Expr) { if let Some(method_name) = checker.ctx.resolve_call_path(expr).and_then(|call_path| { // seeding state if call_path.as_slice() == ["numpy", "random", "seed"] diff --git a/crates/ruff/src/rules/pandas_vet/helpers.rs b/crates/ruff/src/rules/pandas_vet/helpers.rs index 99be263318..271f17f6f0 100644 --- a/crates/ruff/src/rules/pandas_vet/helpers.rs +++ b/crates/ruff/src/rules/pandas_vet/helpers.rs @@ -2,7 +2,7 @@ use rustpython_parser::ast::{Expr, ExprKind}; /// Return `true` if an `Expr` _could_ be a `DataFrame`. This rules out /// obviously-wrong cases, like constants and literals. -pub const fn is_dataframe_candidate(expr: &Expr) -> bool { +pub(crate) const fn is_dataframe_candidate(expr: &Expr) -> bool { !matches!( expr.node, ExprKind::Constant(_) diff --git a/crates/ruff/src/rules/pandas_vet/rules/assignment_to_df.rs b/crates/ruff/src/rules/pandas_vet/rules/assignment_to_df.rs index 3a0d4a69d7..8c0ab99784 100644 --- a/crates/ruff/src/rules/pandas_vet/rules/assignment_to_df.rs +++ b/crates/ruff/src/rules/pandas_vet/rules/assignment_to_df.rs @@ -14,7 +14,7 @@ impl Violation for PandasDfVariableName { } /// PD901 -pub fn assignment_to_df(targets: &[Expr]) -> Option { +pub(crate) fn assignment_to_df(targets: &[Expr]) -> Option { if targets.len() != 1 { return None; } diff --git a/crates/ruff/src/rules/pandas_vet/rules/check_attr.rs b/crates/ruff/src/rules/pandas_vet/rules/check_attr.rs index efdaab6115..2df6177cc1 100644 --- a/crates/ruff/src/rules/pandas_vet/rules/check_attr.rs +++ b/crates/ruff/src/rules/pandas_vet/rules/check_attr.rs @@ -49,7 +49,7 @@ impl Violation for PandasUseOfDotValues { } } -pub fn check_attr(checker: &mut Checker, attr: &str, value: &Expr, attr_expr: &Expr) { +pub(crate) fn check_attr(checker: &mut Checker, attr: &str, value: &Expr, attr_expr: &Expr) { let rules = &checker.settings.rules; let violation: DiagnosticKind = match attr { "ix" if rules.enabled(Rule::PandasUseOfDotIx) => PandasUseOfDotIx.into(), diff --git a/crates/ruff/src/rules/pandas_vet/rules/check_call.rs b/crates/ruff/src/rules/pandas_vet/rules/check_call.rs index 5abd56432d..ee057b80f9 100644 --- a/crates/ruff/src/rules/pandas_vet/rules/check_call.rs +++ b/crates/ruff/src/rules/pandas_vet/rules/check_call.rs @@ -61,7 +61,7 @@ impl Violation for PandasUseOfDotStack { } } -pub fn check_call(checker: &mut Checker, func: &Expr) { +pub(crate) fn check_call(checker: &mut Checker, func: &Expr) { let rules = &checker.settings.rules; let ExprKind::Attribute(ast::ExprAttribute { value, attr, .. } )= &func.node else {return}; let violation: DiagnosticKind = match attr.as_str() { diff --git a/crates/ruff/src/rules/pandas_vet/rules/inplace_argument.rs b/crates/ruff/src/rules/pandas_vet/rules/inplace_argument.rs index c91a2e21f2..c24fd8888c 100644 --- a/crates/ruff/src/rules/pandas_vet/rules/inplace_argument.rs +++ b/crates/ruff/src/rules/pandas_vet/rules/inplace_argument.rs @@ -49,7 +49,7 @@ impl Violation for PandasUseOfInplaceArgument { } /// PD002 -pub fn inplace_argument( +pub(crate) fn inplace_argument( checker: &Checker, expr: &Expr, func: &Expr, diff --git a/crates/ruff/src/rules/pandas_vet/rules/mod.rs b/crates/ruff/src/rules/pandas_vet/rules/mod.rs index 975d13b0ac..a4dfb12e58 100644 --- a/crates/ruff/src/rules/pandas_vet/rules/mod.rs +++ b/crates/ruff/src/rules/pandas_vet/rules/mod.rs @@ -1,16 +1,16 @@ -pub use assignment_to_df::{assignment_to_df, PandasDfVariableName}; -pub use check_attr::{ +pub(crate) use assignment_to_df::{assignment_to_df, PandasDfVariableName}; +pub(crate) use check_attr::{ check_attr, PandasUseOfDotAt, PandasUseOfDotIat, PandasUseOfDotIx, PandasUseOfDotValues, }; -pub use check_call::{ +pub(crate) use check_call::{ check_call, PandasUseOfDotIsNull, PandasUseOfDotNotNull, PandasUseOfDotPivotOrUnstack, PandasUseOfDotReadTable, PandasUseOfDotStack, }; -pub use inplace_argument::{inplace_argument, PandasUseOfInplaceArgument}; -pub use pd_merge::{use_of_pd_merge, PandasUseOfPdMerge}; +pub(crate) use inplace_argument::{inplace_argument, PandasUseOfInplaceArgument}; +pub(crate) use pd_merge::{use_of_pd_merge, PandasUseOfPdMerge}; -pub mod assignment_to_df; -pub mod check_attr; -pub mod check_call; -pub mod inplace_argument; -pub mod pd_merge; +pub(crate) mod assignment_to_df; +pub(crate) mod check_attr; +pub(crate) mod check_call; +pub(crate) mod inplace_argument; +pub(crate) mod pd_merge; diff --git a/crates/ruff/src/rules/pandas_vet/rules/pd_merge.rs b/crates/ruff/src/rules/pandas_vet/rules/pd_merge.rs index 1d1491cb14..6a01f7a134 100644 --- a/crates/ruff/src/rules/pandas_vet/rules/pd_merge.rs +++ b/crates/ruff/src/rules/pandas_vet/rules/pd_merge.rs @@ -17,7 +17,7 @@ impl Violation for PandasUseOfPdMerge { } /// PD015 -pub fn use_of_pd_merge(func: &Expr) -> Option { +pub(crate) fn use_of_pd_merge(func: &Expr) -> Option { if let ExprKind::Attribute(ast::ExprAttribute { attr, value, .. }) = &func.node { if let ExprKind::Name(ast::ExprName { id, .. }) = &value.node { if id == "pd" && attr == "merge" { diff --git a/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_acronym.rs b/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_acronym.rs index 481f6e40ce..b416c3235d 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_acronym.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_acronym.rs @@ -47,7 +47,7 @@ impl Violation for CamelcaseImportedAsAcronym { } /// N817 -pub fn camelcase_imported_as_acronym( +pub(crate) fn camelcase_imported_as_acronym( name: &str, asname: &str, alias: &Alias, diff --git a/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_constant.rs b/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_constant.rs index 05726ca4e8..98f3c1a2ae 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_constant.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_constant.rs @@ -44,7 +44,7 @@ impl Violation for CamelcaseImportedAsConstant { } /// N814 -pub fn camelcase_imported_as_constant( +pub(crate) fn camelcase_imported_as_constant( name: &str, asname: &str, alias: &Alias, diff --git a/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_lowercase.rs b/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_lowercase.rs index 8a025c3189..3a6560aa4d 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_lowercase.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_lowercase.rs @@ -43,7 +43,7 @@ impl Violation for CamelcaseImportedAsLowercase { } /// N813 -pub fn camelcase_imported_as_lowercase( +pub(crate) fn camelcase_imported_as_lowercase( name: &str, asname: &str, alias: &Alias, diff --git a/crates/ruff/src/rules/pep8_naming/rules/constant_imported_as_non_constant.rs b/crates/ruff/src/rules/pep8_naming/rules/constant_imported_as_non_constant.rs index 4e8ea242aa..a5cff55308 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/constant_imported_as_non_constant.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/constant_imported_as_non_constant.rs @@ -43,7 +43,7 @@ impl Violation for ConstantImportedAsNonConstant { } /// N811 -pub fn constant_imported_as_non_constant( +pub(crate) fn constant_imported_as_non_constant( name: &str, asname: &str, alias: &Alias, diff --git a/crates/ruff/src/rules/pep8_naming/rules/dunder_function_name.rs b/crates/ruff/src/rules/pep8_naming/rules/dunder_function_name.rs index 43b3f5827b..143576f057 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/dunder_function_name.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/dunder_function_name.rs @@ -41,7 +41,7 @@ impl Violation for DunderFunctionName { } /// N807 -pub fn dunder_function_name( +pub(crate) fn dunder_function_name( scope: &Scope, stmt: &Stmt, name: &str, diff --git a/crates/ruff/src/rules/pep8_naming/rules/error_suffix_on_exception_name.rs b/crates/ruff/src/rules/pep8_naming/rules/error_suffix_on_exception_name.rs index 9f753261b4..bc99b49af6 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/error_suffix_on_exception_name.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/error_suffix_on_exception_name.rs @@ -42,7 +42,7 @@ impl Violation for ErrorSuffixOnExceptionName { } /// N818 -pub fn error_suffix_on_exception_name( +pub(crate) fn error_suffix_on_exception_name( class_def: &Stmt, bases: &[Expr], name: &str, diff --git a/crates/ruff/src/rules/pep8_naming/rules/invalid_argument_name.rs b/crates/ruff/src/rules/pep8_naming/rules/invalid_argument_name.rs index e1b8ea509c..517eca1ed0 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/invalid_argument_name.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/invalid_argument_name.rs @@ -45,7 +45,11 @@ impl Violation for InvalidArgumentName { } /// N803 -pub fn invalid_argument_name(name: &str, arg: &Arg, ignore_names: &[String]) -> Option { +pub(crate) fn invalid_argument_name( + name: &str, + arg: &Arg, + ignore_names: &[String], +) -> Option { if ignore_names.iter().any(|ignore_name| ignore_name == name) { return None; } diff --git a/crates/ruff/src/rules/pep8_naming/rules/invalid_class_name.rs b/crates/ruff/src/rules/pep8_naming/rules/invalid_class_name.rs index 6e09b6c486..d4f8462a55 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/invalid_class_name.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/invalid_class_name.rs @@ -48,7 +48,11 @@ impl Violation for InvalidClassName { } /// N801 -pub fn invalid_class_name(class_def: &Stmt, name: &str, locator: &Locator) -> Option { +pub(crate) fn invalid_class_name( + class_def: &Stmt, + name: &str, + locator: &Locator, +) -> Option { let stripped = name.strip_prefix('_').unwrap_or(name); if !stripped.chars().next().map_or(false, char::is_uppercase) || stripped.contains('_') { return Some(Diagnostic::new( diff --git a/crates/ruff/src/rules/pep8_naming/rules/invalid_first_argument_name_for_class_method.rs b/crates/ruff/src/rules/pep8_naming/rules/invalid_first_argument_name_for_class_method.rs index cd78a698ff..f8390ca5df 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/invalid_first_argument_name_for_class_method.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/invalid_first_argument_name_for_class_method.rs @@ -55,7 +55,7 @@ impl Violation for InvalidFirstArgumentNameForClassMethod { } /// N804 -pub fn invalid_first_argument_name_for_class_method( +pub(crate) fn invalid_first_argument_name_for_class_method( checker: &Checker, scope: &Scope, name: &str, diff --git a/crates/ruff/src/rules/pep8_naming/rules/invalid_first_argument_name_for_method.rs b/crates/ruff/src/rules/pep8_naming/rules/invalid_first_argument_name_for_method.rs index faf1f4625c..757d5a17f5 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/invalid_first_argument_name_for_method.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/invalid_first_argument_name_for_method.rs @@ -52,7 +52,7 @@ impl Violation for InvalidFirstArgumentNameForMethod { } /// N805 -pub fn invalid_first_argument_name_for_method( +pub(crate) fn invalid_first_argument_name_for_method( checker: &Checker, scope: &Scope, name: &str, diff --git a/crates/ruff/src/rules/pep8_naming/rules/invalid_function_name.rs b/crates/ruff/src/rules/pep8_naming/rules/invalid_function_name.rs index b31c01724e..e8843a7a3f 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/invalid_function_name.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/invalid_function_name.rs @@ -48,7 +48,7 @@ impl Violation for InvalidFunctionName { } /// N802 -pub fn invalid_function_name( +pub(crate) fn invalid_function_name( stmt: &Stmt, name: &str, decorator_list: &[Expr], diff --git a/crates/ruff/src/rules/pep8_naming/rules/invalid_module_name.rs b/crates/ruff/src/rules/pep8_naming/rules/invalid_module_name.rs index 9c2a2eabf7..165f3036e0 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/invalid_module_name.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/invalid_module_name.rs @@ -45,7 +45,7 @@ impl Violation for InvalidModuleName { } /// N999 -pub fn invalid_module_name(path: &Path, package: Option<&Path>) -> Option { +pub(crate) fn invalid_module_name(path: &Path, package: Option<&Path>) -> Option { if !path .extension() .map_or(false, |ext| ext == "py" || ext == "pyi") diff --git a/crates/ruff/src/rules/pep8_naming/rules/lowercase_imported_as_non_lowercase.rs b/crates/ruff/src/rules/pep8_naming/rules/lowercase_imported_as_non_lowercase.rs index 886894d627..21f3a681cd 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/lowercase_imported_as_non_lowercase.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/lowercase_imported_as_non_lowercase.rs @@ -42,7 +42,7 @@ impl Violation for LowercaseImportedAsNonLowercase { } /// N812 -pub fn lowercase_imported_as_non_lowercase( +pub(crate) fn lowercase_imported_as_non_lowercase( name: &str, asname: &str, alias: &Alias, diff --git a/crates/ruff/src/rules/pep8_naming/rules/mixed_case_variable_in_class_scope.rs b/crates/ruff/src/rules/pep8_naming/rules/mixed_case_variable_in_class_scope.rs index 9be13b524d..4e06f21523 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/mixed_case_variable_in_class_scope.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/mixed_case_variable_in_class_scope.rs @@ -50,7 +50,7 @@ impl Violation for MixedCaseVariableInClassScope { } /// N815 -pub fn mixed_case_variable_in_class_scope( +pub(crate) fn mixed_case_variable_in_class_scope( checker: &mut Checker, expr: &Expr, stmt: &Stmt, diff --git a/crates/ruff/src/rules/pep8_naming/rules/mixed_case_variable_in_global_scope.rs b/crates/ruff/src/rules/pep8_naming/rules/mixed_case_variable_in_global_scope.rs index 5ac321dc8a..f2563fc5e0 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/mixed_case_variable_in_global_scope.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/mixed_case_variable_in_global_scope.rs @@ -60,7 +60,7 @@ impl Violation for MixedCaseVariableInGlobalScope { } /// N816 -pub fn mixed_case_variable_in_global_scope( +pub(crate) fn mixed_case_variable_in_global_scope( checker: &mut Checker, expr: &Expr, stmt: &Stmt, diff --git a/crates/ruff/src/rules/pep8_naming/rules/mod.rs b/crates/ruff/src/rules/pep8_naming/rules/mod.rs index 52072cd7c0..f842ca40ea 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/mod.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/mod.rs @@ -1,39 +1,39 @@ -pub use camelcase_imported_as_acronym::{ +pub(crate) use camelcase_imported_as_acronym::{ camelcase_imported_as_acronym, CamelcaseImportedAsAcronym, }; -pub use camelcase_imported_as_constant::{ +pub(crate) use camelcase_imported_as_constant::{ camelcase_imported_as_constant, CamelcaseImportedAsConstant, }; -pub use camelcase_imported_as_lowercase::{ +pub(crate) use camelcase_imported_as_lowercase::{ camelcase_imported_as_lowercase, CamelcaseImportedAsLowercase, }; -pub use constant_imported_as_non_constant::{ +pub(crate) use constant_imported_as_non_constant::{ constant_imported_as_non_constant, ConstantImportedAsNonConstant, }; -pub use dunder_function_name::{dunder_function_name, DunderFunctionName}; -pub use error_suffix_on_exception_name::{ +pub(crate) use dunder_function_name::{dunder_function_name, DunderFunctionName}; +pub(crate) use error_suffix_on_exception_name::{ error_suffix_on_exception_name, ErrorSuffixOnExceptionName, }; -pub use invalid_argument_name::{invalid_argument_name, InvalidArgumentName}; -pub use invalid_class_name::{invalid_class_name, InvalidClassName}; -pub use invalid_first_argument_name_for_class_method::{ +pub(crate) use invalid_argument_name::{invalid_argument_name, InvalidArgumentName}; +pub(crate) use invalid_class_name::{invalid_class_name, InvalidClassName}; +pub(crate) use invalid_first_argument_name_for_class_method::{ invalid_first_argument_name_for_class_method, InvalidFirstArgumentNameForClassMethod, }; -pub use invalid_first_argument_name_for_method::{ +pub(crate) use invalid_first_argument_name_for_method::{ invalid_first_argument_name_for_method, InvalidFirstArgumentNameForMethod, }; -pub use invalid_function_name::{invalid_function_name, InvalidFunctionName}; -pub use invalid_module_name::{invalid_module_name, InvalidModuleName}; -pub use lowercase_imported_as_non_lowercase::{ +pub(crate) use invalid_function_name::{invalid_function_name, InvalidFunctionName}; +pub(crate) use invalid_module_name::{invalid_module_name, InvalidModuleName}; +pub(crate) use lowercase_imported_as_non_lowercase::{ lowercase_imported_as_non_lowercase, LowercaseImportedAsNonLowercase, }; -pub use mixed_case_variable_in_class_scope::{ +pub(crate) use mixed_case_variable_in_class_scope::{ mixed_case_variable_in_class_scope, MixedCaseVariableInClassScope, }; -pub use mixed_case_variable_in_global_scope::{ +pub(crate) use mixed_case_variable_in_global_scope::{ mixed_case_variable_in_global_scope, MixedCaseVariableInGlobalScope, }; -pub use non_lowercase_variable_in_function::{ +pub(crate) use non_lowercase_variable_in_function::{ non_lowercase_variable_in_function, NonLowercaseVariableInFunction, }; diff --git a/crates/ruff/src/rules/pep8_naming/rules/non_lowercase_variable_in_function.rs b/crates/ruff/src/rules/pep8_naming/rules/non_lowercase_variable_in_function.rs index fc9d74a02c..e2c7beb63e 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/non_lowercase_variable_in_function.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/non_lowercase_variable_in_function.rs @@ -49,7 +49,7 @@ impl Violation for NonLowercaseVariableInFunction { } /// N806 -pub fn non_lowercase_variable_in_function( +pub(crate) fn non_lowercase_variable_in_function( checker: &mut Checker, expr: &Expr, stmt: &Stmt, diff --git a/crates/ruff/src/rules/pycodestyle/helpers.rs b/crates/ruff/src/rules/pycodestyle/helpers.rs index 26e43c75ba..93e973233d 100644 --- a/crates/ruff/src/rules/pycodestyle/helpers.rs +++ b/crates/ruff/src/rules/pycodestyle/helpers.rs @@ -5,11 +5,16 @@ use ruff_text_size::{TextLen, TextRange}; use rustpython_parser::ast::{self, Cmpop, Expr}; use unicode_width::{UnicodeWidthChar, UnicodeWidthStr}; -pub fn is_ambiguous_name(name: &str) -> bool { +pub(crate) fn is_ambiguous_name(name: &str) -> bool { name == "l" || name == "I" || name == "O" } -pub fn compare(left: &Expr, ops: &[Cmpop], comparators: &[Expr], stylist: &Stylist) -> String { +pub(crate) fn compare( + left: &Expr, + ops: &[Cmpop], + comparators: &[Expr], + stylist: &Stylist, +) -> String { unparse_expr( &create_expr(ast::ExprCompare { left: Box::new(left.clone()), diff --git a/crates/ruff/src/rules/pycodestyle/rules/ambiguous_class_name.rs b/crates/ruff/src/rules/pycodestyle/rules/ambiguous_class_name.rs index 0967b96930..d03b69ac62 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/ambiguous_class_name.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/ambiguous_class_name.rs @@ -34,7 +34,7 @@ impl Violation for AmbiguousClassName { } /// E742 -pub fn ambiguous_class_name(name: &str, locate: F) -> Option +pub(crate) fn ambiguous_class_name(name: &str, locate: F) -> Option where F: FnOnce() -> TextRange, { diff --git a/crates/ruff/src/rules/pycodestyle/rules/ambiguous_function_name.rs b/crates/ruff/src/rules/pycodestyle/rules/ambiguous_function_name.rs index df1f5e052e..c45bfda3a0 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/ambiguous_function_name.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/ambiguous_function_name.rs @@ -34,7 +34,7 @@ impl Violation for AmbiguousFunctionName { } /// E743 -pub fn ambiguous_function_name(name: &str, locate: F) -> Option +pub(crate) fn ambiguous_function_name(name: &str, locate: F) -> Option where F: FnOnce() -> TextRange, { diff --git a/crates/ruff/src/rules/pycodestyle/rules/ambiguous_variable_name.rs b/crates/ruff/src/rules/pycodestyle/rules/ambiguous_variable_name.rs index fb80afbbce..4aa2ecdbe4 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/ambiguous_variable_name.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/ambiguous_variable_name.rs @@ -37,7 +37,7 @@ impl Violation for AmbiguousVariableName { } /// E741 -pub fn ambiguous_variable_name(name: &str, range: TextRange) -> Option { +pub(crate) fn ambiguous_variable_name(name: &str, range: TextRange) -> Option { if is_ambiguous_name(name) { Some(Diagnostic::new( AmbiguousVariableName(name.to_string()), diff --git a/crates/ruff/src/rules/pycodestyle/rules/bare_except.rs b/crates/ruff/src/rules/pycodestyle/rules/bare_except.rs index c472df1d1b..6b22ac8dd3 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/bare_except.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/bare_except.rs @@ -45,7 +45,7 @@ impl Violation for BareExcept { } /// E722 -pub fn bare_except( +pub(crate) fn bare_except( type_: Option<&Expr>, body: &[Stmt], handler: &Excepthandler, diff --git a/crates/ruff/src/rules/pycodestyle/rules/compound_statements.rs b/crates/ruff/src/rules/pycodestyle/rules/compound_statements.rs index ae40de92e5..ce98fb2ee0 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/compound_statements.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/compound_statements.rs @@ -99,7 +99,7 @@ impl AlwaysAutofixableViolation for UselessSemicolon { } /// E701, E702, E703 -pub fn compound_statements(lxr: &[LexResult], settings: &Settings) -> Vec { +pub(crate) fn compound_statements(lxr: &[LexResult], settings: &Settings) -> Vec { let mut diagnostics = vec![]; // Track the last seen instance of a variety of tokens. diff --git a/crates/ruff/src/rules/pycodestyle/rules/errors.rs b/crates/ruff/src/rules/pycodestyle/rules/errors.rs index f3427e0c9e..ad6c56caaf 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/errors.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/errors.rs @@ -34,7 +34,7 @@ impl Violation for SyntaxError { } /// E901 -pub fn syntax_error( +pub(crate) fn syntax_error( diagnostics: &mut Vec, parse_error: &ParseError, locator: &Locator, diff --git a/crates/ruff/src/rules/pycodestyle/rules/imports.rs b/crates/ruff/src/rules/pycodestyle/rules/imports.rs index b86e6bfe56..814a943c37 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/imports.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/imports.rs @@ -73,7 +73,7 @@ impl Violation for ModuleImportNotAtTopOfFile { } /// E401 -pub fn multiple_imports_on_one_line(checker: &mut Checker, stmt: &Stmt, names: &[Alias]) { +pub(crate) fn multiple_imports_on_one_line(checker: &mut Checker, stmt: &Stmt, names: &[Alias]) { if names.len() > 1 { checker .diagnostics @@ -82,7 +82,11 @@ pub fn multiple_imports_on_one_line(checker: &mut Checker, stmt: &Stmt, names: & } /// E402 -pub fn module_import_not_at_top_of_file(checker: &mut Checker, stmt: &Stmt, locator: &Locator) { +pub(crate) fn module_import_not_at_top_of_file( + checker: &mut Checker, + stmt: &Stmt, + locator: &Locator, +) { if checker.ctx.seen_import_boundary && locator.is_at_start_of_line(stmt.start()) { checker .diagnostics diff --git a/crates/ruff/src/rules/pycodestyle/rules/invalid_escape_sequence.rs b/crates/ruff/src/rules/pycodestyle/rules/invalid_escape_sequence.rs index 5335a88764..ceef5cd796 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/invalid_escape_sequence.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/invalid_escape_sequence.rs @@ -55,7 +55,7 @@ fn extract_quote(text: &str) -> Result<&str> { } /// W605 -pub fn invalid_escape_sequence( +pub(crate) fn invalid_escape_sequence( locator: &Locator, range: TextRange, autofix: bool, diff --git a/crates/ruff/src/rules/pycodestyle/rules/lambda_assignment.rs b/crates/ruff/src/rules/pycodestyle/rules/lambda_assignment.rs index 5521a35b89..068836c3e7 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/lambda_assignment.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/lambda_assignment.rs @@ -56,7 +56,7 @@ impl Violation for LambdaAssignment { } /// E731 -pub fn lambda_assignment( +pub(crate) fn lambda_assignment( checker: &mut Checker, target: &Expr, value: &Expr, diff --git a/crates/ruff/src/rules/pycodestyle/rules/literal_comparisons.rs b/crates/ruff/src/rules/pycodestyle/rules/literal_comparisons.rs index 35298f330c..480ae18380 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/literal_comparisons.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/literal_comparisons.rs @@ -131,7 +131,7 @@ impl AlwaysAutofixableViolation for TrueFalseComparison { } /// E711, E712 -pub fn literal_comparisons( +pub(crate) fn literal_comparisons( checker: &mut Checker, expr: &Expr, left: &Expr, diff --git a/crates/ruff/src/rules/pycodestyle/rules/logical_lines/mod.rs b/crates/ruff/src/rules/pycodestyle/rules/logical_lines/mod.rs index 94d07ed9ff..59e6ca39e4 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/logical_lines/mod.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/logical_lines/mod.rs @@ -83,7 +83,7 @@ pub(crate) struct LogicalLines<'a> { } impl<'a> LogicalLines<'a> { - pub fn from_tokens(tokens: &'a [LexResult], locator: &'a Locator<'a>) -> Self { + pub(crate) fn from_tokens(tokens: &'a [LexResult], locator: &'a Locator<'a>) -> Self { assert!(u32::try_from(tokens.len()).is_ok()); let mut builder = LogicalLinesBuilder::with_capacity(tokens.len()); @@ -154,12 +154,12 @@ pub(crate) struct LogicalLine<'a> { impl<'a> LogicalLine<'a> { /// Returns `true` if this is a comment only line - pub fn is_comment_only(&self) -> bool { + pub(crate) fn is_comment_only(&self) -> bool { self.flags() == TokenFlags::COMMENT } /// Returns logical line's text including comments, indents, dedent and trailing new lines. - pub fn text(&self) -> &'a str { + pub(crate) fn text(&self) -> &'a str { let tokens = self.tokens(); match (tokens.first(), tokens.last()) { (Some(first), Some(last)) => self @@ -172,7 +172,7 @@ impl<'a> LogicalLine<'a> { /// Returns the text without any leading or trailing newline, comment, indent, or dedent of this line #[cfg(test)] - pub fn text_trimmed(&self) -> &'a str { + pub(crate) fn text_trimmed(&self) -> &'a str { let tokens = self.tokens_trimmed(); match (tokens.first(), tokens.last()) { @@ -184,7 +184,7 @@ impl<'a> LogicalLine<'a> { } } - pub fn tokens_trimmed(&self) -> &'a [LogicalLineToken] { + pub(crate) fn tokens_trimmed(&self) -> &'a [LogicalLineToken] { let tokens = self.tokens(); let start = tokens @@ -222,7 +222,7 @@ impl<'a> LogicalLine<'a> { /// Returns the text after `token` #[inline] - pub fn text_after(&self, token: &'a LogicalLineToken) -> &str { + pub(crate) fn text_after(&self, token: &'a LogicalLineToken) -> &str { // SAFETY: The line must have at least one token or `token` would not belong to this line. let last_token = self.tokens().last().unwrap(); self.lines @@ -232,7 +232,7 @@ impl<'a> LogicalLine<'a> { /// Returns the text before `token` #[inline] - pub fn text_before(&self, token: &'a LogicalLineToken) -> &str { + pub(crate) fn text_before(&self, token: &'a LogicalLineToken) -> &str { // SAFETY: The line must have at least one token or `token` would not belong to this line. let first_token = self.tokens().first().unwrap(); self.lines @@ -241,26 +241,29 @@ impl<'a> LogicalLine<'a> { } /// Returns the whitespace *after* the `token` with the byte length - pub fn trailing_whitespace(&self, token: &'a LogicalLineToken) -> (Whitespace, TextSize) { + pub(crate) fn trailing_whitespace( + &self, + token: &'a LogicalLineToken, + ) -> (Whitespace, TextSize) { Whitespace::leading(self.text_after(token)) } /// Returns the whitespace and whitespace byte-length *before* the `token` - pub fn leading_whitespace(&self, token: &'a LogicalLineToken) -> (Whitespace, TextSize) { + pub(crate) fn leading_whitespace(&self, token: &'a LogicalLineToken) -> (Whitespace, TextSize) { Whitespace::trailing(self.text_before(token)) } /// Returns all tokens of the line, including comments and trailing new lines. - pub fn tokens(&self) -> &'a [LogicalLineToken] { + pub(crate) fn tokens(&self) -> &'a [LogicalLineToken] { &self.lines.tokens[self.line.tokens_start as usize..self.line.tokens_end as usize] } - pub fn first_token(&self) -> Option<&'a LogicalLineToken> { + pub(crate) fn first_token(&self) -> Option<&'a LogicalLineToken> { self.tokens().first() } /// Returns the line's flags - pub const fn flags(&self) -> TokenFlags { + pub(crate) const fn flags(&self) -> TokenFlags { self.line.flags } } @@ -326,25 +329,25 @@ pub(crate) struct LogicalLineToken { impl LogicalLineToken { /// Returns the token's kind #[inline] - pub const fn kind(&self) -> TokenKind { + pub(crate) const fn kind(&self) -> TokenKind { self.kind } /// Returns the token's start location #[inline] - pub const fn start(&self) -> TextSize { + pub(crate) const fn start(&self) -> TextSize { self.range.start() } /// Returns the token's end location #[inline] - pub const fn end(&self) -> TextSize { + pub(crate) const fn end(&self) -> TextSize { self.range.end() } /// Returns a tuple with the token's `(start, end)` locations #[inline] - pub const fn range(&self) -> TextRange { + pub(crate) const fn range(&self) -> TextRange { self.range } } diff --git a/crates/ruff/src/rules/pycodestyle/rules/missing_newline_at_end_of_file.rs b/crates/ruff/src/rules/pycodestyle/rules/missing_newline_at_end_of_file.rs index ccfdba9c94..58bb6d12c7 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/missing_newline_at_end_of_file.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/missing_newline_at_end_of_file.rs @@ -35,7 +35,7 @@ impl AlwaysAutofixableViolation for MissingNewlineAtEndOfFile { } /// W292 -pub fn no_newline_at_end_of_file( +pub(crate) fn no_newline_at_end_of_file( locator: &Locator, stylist: &Stylist, autofix: bool, diff --git a/crates/ruff/src/rules/pycodestyle/rules/mod.rs b/crates/ruff/src/rules/pycodestyle/rules/mod.rs index 4a5c3a1ba0..6209c41cf3 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/mod.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/mod.rs @@ -1,30 +1,33 @@ -pub use ambiguous_class_name::{ambiguous_class_name, AmbiguousClassName}; -pub use ambiguous_function_name::{ambiguous_function_name, AmbiguousFunctionName}; -pub use ambiguous_variable_name::{ambiguous_variable_name, AmbiguousVariableName}; -pub use bare_except::{bare_except, BareExcept}; -pub use compound_statements::{ +pub(crate) use ambiguous_class_name::{ambiguous_class_name, AmbiguousClassName}; +pub(crate) use ambiguous_function_name::{ambiguous_function_name, AmbiguousFunctionName}; +pub(crate) use ambiguous_variable_name::{ambiguous_variable_name, AmbiguousVariableName}; +pub(crate) use bare_except::{bare_except, BareExcept}; +pub(crate) use compound_statements::{ compound_statements, MultipleStatementsOnOneLineColon, MultipleStatementsOnOneLineSemicolon, UselessSemicolon, }; pub(crate) use doc_line_too_long::{doc_line_too_long, DocLineTooLong}; -pub use errors::{syntax_error, IOError, SyntaxError}; -pub use imports::{ +pub use errors::IOError; +pub(crate) use errors::{syntax_error, SyntaxError}; +pub(crate) use imports::{ module_import_not_at_top_of_file, multiple_imports_on_one_line, ModuleImportNotAtTopOfFile, MultipleImportsOnOneLine, }; -pub use invalid_escape_sequence::{invalid_escape_sequence, InvalidEscapeSequence}; -pub use lambda_assignment::{lambda_assignment, LambdaAssignment}; +pub(crate) use invalid_escape_sequence::{invalid_escape_sequence, InvalidEscapeSequence}; +pub(crate) use lambda_assignment::{lambda_assignment, LambdaAssignment}; pub(crate) use line_too_long::{line_too_long, LineTooLong}; -pub use literal_comparisons::{literal_comparisons, NoneComparison, TrueFalseComparison}; -pub use missing_newline_at_end_of_file::{no_newline_at_end_of_file, MissingNewlineAtEndOfFile}; +pub(crate) use literal_comparisons::{literal_comparisons, NoneComparison, TrueFalseComparison}; +pub(crate) use missing_newline_at_end_of_file::{ + no_newline_at_end_of_file, MissingNewlineAtEndOfFile, +}; pub(crate) use mixed_spaces_and_tabs::{mixed_spaces_and_tabs, MixedSpacesAndTabs}; -pub use not_tests::{not_tests, NotInTest, NotIsTest}; +pub(crate) use not_tests::{not_tests, NotInTest, NotIsTest}; pub(crate) use tab_indentation::{tab_indentation, TabIndentation}; pub(crate) use trailing_whitespace::{ trailing_whitespace, BlankLineWithWhitespace, TrailingWhitespace, }; -pub use type_comparison::{type_comparison, TypeComparison}; +pub(crate) use type_comparison::{type_comparison, TypeComparison}; mod ambiguous_class_name; mod ambiguous_function_name; diff --git a/crates/ruff/src/rules/pycodestyle/rules/not_tests.rs b/crates/ruff/src/rules/pycodestyle/rules/not_tests.rs index f58fec2fb8..685104ef07 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/not_tests.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/not_tests.rs @@ -74,7 +74,7 @@ impl AlwaysAutofixableViolation for NotIsTest { } /// E713, E714 -pub fn not_tests( +pub(crate) fn not_tests( checker: &mut Checker, expr: &Expr, op: &Unaryop, diff --git a/crates/ruff/src/rules/pycodestyle/rules/type_comparison.rs b/crates/ruff/src/rules/pycodestyle/rules/type_comparison.rs index 5adcb251fa..350f47cf26 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/type_comparison.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/type_comparison.rs @@ -37,7 +37,12 @@ impl Violation for TypeComparison { } /// E721 -pub fn type_comparison(checker: &mut Checker, expr: &Expr, ops: &[Cmpop], comparators: &[Expr]) { +pub(crate) fn type_comparison( + checker: &mut Checker, + expr: &Expr, + ops: &[Cmpop], + comparators: &[Expr], +) { for (op, right) in izip!(ops, comparators) { if !matches!(op, Cmpop::Is | Cmpop::IsNot | Cmpop::Eq | Cmpop::NotEq) { continue; diff --git a/crates/ruff/src/rules/pydocstyle/rules/backslashes.rs b/crates/ruff/src/rules/pydocstyle/rules/backslashes.rs index c5de4b50f7..7bd2b326fd 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/backslashes.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/backslashes.rs @@ -20,7 +20,7 @@ impl Violation for EscapeSequenceInDocstring { static BACKSLASH_REGEX: Lazy = Lazy::new(|| Regex::new(r"\\[^(\r\n|\n)uN]").unwrap()); /// D301 -pub fn backslashes(checker: &mut Checker, docstring: &Docstring) { +pub(crate) fn backslashes(checker: &mut Checker, docstring: &Docstring) { let contents = docstring.contents; // Docstring is already raw. diff --git a/crates/ruff/src/rules/pydocstyle/rules/blank_after_summary.rs b/crates/ruff/src/rules/pydocstyle/rules/blank_after_summary.rs index 92d15382f5..830d5ec45e 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/blank_after_summary.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/blank_after_summary.rs @@ -32,7 +32,7 @@ impl Violation for BlankLineAfterSummary { } /// D205 -pub fn blank_after_summary(checker: &mut Checker, docstring: &Docstring) { +pub(crate) fn blank_after_summary(checker: &mut Checker, docstring: &Docstring) { let body = docstring.body(); let mut lines_count: usize = 1; diff --git a/crates/ruff/src/rules/pydocstyle/rules/blank_before_after_class.rs b/crates/ruff/src/rules/pydocstyle/rules/blank_before_after_class.rs index 4040e31131..61318d8dca 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/blank_before_after_class.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/blank_before_after_class.rs @@ -57,7 +57,7 @@ impl AlwaysAutofixableViolation for BlankLineBeforeClass { } /// D203, D204, D211 -pub fn blank_before_after_class(checker: &mut Checker, docstring: &Docstring) { +pub(crate) fn blank_before_after_class(checker: &mut Checker, docstring: &Docstring) { let Definition::Member(Member { kind: MemberKind::Class | MemberKind::NestedClass , stmt, diff --git a/crates/ruff/src/rules/pydocstyle/rules/blank_before_after_function.rs b/crates/ruff/src/rules/pydocstyle/rules/blank_before_after_function.rs index 3b977000d0..dd81c317c7 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/blank_before_after_function.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/blank_before_after_function.rs @@ -49,7 +49,7 @@ static INNER_FUNCTION_OR_CLASS_REGEX: Lazy = Lazy::new(|| Regex::new(r"^\s+(?:(?:class|def|async def)\s|@)").unwrap()); /// D201, D202 -pub fn blank_before_after_function(checker: &mut Checker, docstring: &Docstring) { +pub(crate) fn blank_before_after_function(checker: &mut Checker, docstring: &Docstring) { let Definition::Member(Member { kind: MemberKind::Function | MemberKind::NestedFunction | MemberKind::Method, stmt, diff --git a/crates/ruff/src/rules/pydocstyle/rules/capitalized.rs b/crates/ruff/src/rules/pydocstyle/rules/capitalized.rs index 3c3c947c44..ad47747d81 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/capitalized.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/capitalized.rs @@ -32,7 +32,7 @@ impl AlwaysAutofixableViolation for FirstLineCapitalized { } /// D403 -pub fn capitalized(checker: &mut Checker, docstring: &Docstring) { +pub(crate) fn capitalized(checker: &mut Checker, docstring: &Docstring) { if !matches!( docstring.definition, Definition::Member(Member { diff --git a/crates/ruff/src/rules/pydocstyle/rules/ends_with_period.rs b/crates/ruff/src/rules/pydocstyle/rules/ends_with_period.rs index e861e8dfcd..cff4e62038 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/ends_with_period.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/ends_with_period.rs @@ -26,7 +26,7 @@ impl AlwaysAutofixableViolation for EndsInPeriod { } /// D400 -pub fn ends_with_period(checker: &mut Checker, docstring: &Docstring) { +pub(crate) fn ends_with_period(checker: &mut Checker, docstring: &Docstring) { let body = docstring.body(); if let Some(first_line) = body.trim().universal_newlines().next() { diff --git a/crates/ruff/src/rules/pydocstyle/rules/ends_with_punctuation.rs b/crates/ruff/src/rules/pydocstyle/rules/ends_with_punctuation.rs index b1273da496..1139d60e5d 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/ends_with_punctuation.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/ends_with_punctuation.rs @@ -26,7 +26,7 @@ impl AlwaysAutofixableViolation for EndsInPunctuation { } /// D415 -pub fn ends_with_punctuation(checker: &mut Checker, docstring: &Docstring) { +pub(crate) fn ends_with_punctuation(checker: &mut Checker, docstring: &Docstring) { let body = docstring.body(); if let Some(first_line) = body.trim().universal_newlines().next() { diff --git a/crates/ruff/src/rules/pydocstyle/rules/if_needed.rs b/crates/ruff/src/rules/pydocstyle/rules/if_needed.rs index cd63b09765..87cf83fee4 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/if_needed.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/if_needed.rs @@ -19,7 +19,7 @@ impl Violation for OverloadWithDocstring { } /// D418 -pub fn if_needed(checker: &mut Checker, docstring: &Docstring) { +pub(crate) fn if_needed(checker: &mut Checker, docstring: &Docstring) { let Definition::Member(Member { kind: MemberKind::Function | MemberKind::NestedFunction | MemberKind::Method, stmt, diff --git a/crates/ruff/src/rules/pydocstyle/rules/indent.rs b/crates/ruff/src/rules/pydocstyle/rules/indent.rs index e03ab155f0..e76c3bf420 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/indent.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/indent.rs @@ -48,7 +48,7 @@ impl AlwaysAutofixableViolation for OverIndentation { } /// D206, D207, D208 -pub fn indent(checker: &mut Checker, docstring: &Docstring) { +pub(crate) fn indent(checker: &mut Checker, docstring: &Docstring) { let body = docstring.body(); // Split the docstring into lines. diff --git a/crates/ruff/src/rules/pydocstyle/rules/mod.rs b/crates/ruff/src/rules/pydocstyle/rules/mod.rs index 88b6d9bcaa..2cb62ffe0a 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/mod.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/mod.rs @@ -1,39 +1,41 @@ -pub use backslashes::{backslashes, EscapeSequenceInDocstring}; -pub use blank_after_summary::{blank_after_summary, BlankLineAfterSummary}; -pub use blank_before_after_class::{ +pub(crate) use backslashes::{backslashes, EscapeSequenceInDocstring}; +pub(crate) use blank_after_summary::{blank_after_summary, BlankLineAfterSummary}; +pub(crate) use blank_before_after_class::{ blank_before_after_class, BlankLineBeforeClass, OneBlankLineAfterClass, OneBlankLineBeforeClass, }; -pub use blank_before_after_function::{ +pub(crate) use blank_before_after_function::{ blank_before_after_function, NoBlankLineAfterFunction, NoBlankLineBeforeFunction, }; -pub use capitalized::{capitalized, FirstLineCapitalized}; -pub use ends_with_period::{ends_with_period, EndsInPeriod}; -pub use ends_with_punctuation::{ends_with_punctuation, EndsInPunctuation}; -pub use if_needed::{if_needed, OverloadWithDocstring}; -pub use indent::{indent, IndentWithSpaces, OverIndentation, UnderIndentation}; -pub use multi_line_summary_start::{ +pub(crate) use capitalized::{capitalized, FirstLineCapitalized}; +pub(crate) use ends_with_period::{ends_with_period, EndsInPeriod}; +pub(crate) use ends_with_punctuation::{ends_with_punctuation, EndsInPunctuation}; +pub(crate) use if_needed::{if_needed, OverloadWithDocstring}; +pub(crate) use indent::{indent, IndentWithSpaces, OverIndentation, UnderIndentation}; +pub(crate) use multi_line_summary_start::{ multi_line_summary_start, MultiLineSummaryFirstLine, MultiLineSummarySecondLine, }; -pub use newline_after_last_paragraph::{newline_after_last_paragraph, NewLineAfterLastParagraph}; -pub use no_signature::{no_signature, NoSignature}; -pub use no_surrounding_whitespace::{no_surrounding_whitespace, SurroundingWhitespace}; -pub use non_imperative_mood::{non_imperative_mood, NonImperativeMood}; -pub use not_empty::{not_empty, EmptyDocstring}; -pub use not_missing::{ +pub(crate) use newline_after_last_paragraph::{ + newline_after_last_paragraph, NewLineAfterLastParagraph, +}; +pub(crate) use no_signature::{no_signature, NoSignature}; +pub(crate) use no_surrounding_whitespace::{no_surrounding_whitespace, SurroundingWhitespace}; +pub(crate) use non_imperative_mood::{non_imperative_mood, NonImperativeMood}; +pub(crate) use not_empty::{not_empty, EmptyDocstring}; +pub(crate) use not_missing::{ not_missing, UndocumentedMagicMethod, UndocumentedPublicClass, UndocumentedPublicFunction, UndocumentedPublicInit, UndocumentedPublicMethod, UndocumentedPublicModule, UndocumentedPublicNestedClass, UndocumentedPublicPackage, }; -pub use one_liner::{one_liner, FitsOnOneLine}; -pub use sections::{ +pub(crate) use one_liner::{one_liner, FitsOnOneLine}; +pub(crate) use sections::{ sections, BlankLineAfterLastSection, BlankLinesBetweenHeaderAndContent, CapitalizeSectionName, DashedUnderlineAfterSection, EmptyDocstringSection, NewLineAfterSectionName, NoBlankLineAfterSection, NoBlankLineBeforeSection, SectionNameEndsInColon, SectionNotOverIndented, SectionUnderlineAfterName, SectionUnderlineMatchesSectionLength, SectionUnderlineNotOverIndented, UndocumentedParam, }; -pub use starts_with_this::{starts_with_this, DocstringStartsWithThis}; -pub use triple_quotes::{triple_quotes, TripleSingleQuotes}; +pub(crate) use starts_with_this::{starts_with_this, DocstringStartsWithThis}; +pub(crate) use triple_quotes::{triple_quotes, TripleSingleQuotes}; mod backslashes; mod blank_after_summary; diff --git a/crates/ruff/src/rules/pydocstyle/rules/multi_line_summary_start.rs b/crates/ruff/src/rules/pydocstyle/rules/multi_line_summary_start.rs index c179623714..7bcbac89aa 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/multi_line_summary_start.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/multi_line_summary_start.rs @@ -39,7 +39,7 @@ impl AlwaysAutofixableViolation for MultiLineSummarySecondLine { } /// D212, D213 -pub fn multi_line_summary_start(checker: &mut Checker, docstring: &Docstring) { +pub(crate) fn multi_line_summary_start(checker: &mut Checker, docstring: &Docstring) { let contents = docstring.contents; let body = docstring.body(); diff --git a/crates/ruff/src/rules/pydocstyle/rules/newline_after_last_paragraph.rs b/crates/ruff/src/rules/pydocstyle/rules/newline_after_last_paragraph.rs index 9d5d518b45..05adc5ab97 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/newline_after_last_paragraph.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/newline_after_last_paragraph.rs @@ -23,7 +23,7 @@ impl AlwaysAutofixableViolation for NewLineAfterLastParagraph { } /// D209 -pub fn newline_after_last_paragraph(checker: &mut Checker, docstring: &Docstring) { +pub(crate) fn newline_after_last_paragraph(checker: &mut Checker, docstring: &Docstring) { let contents = docstring.contents; let body = docstring.body(); diff --git a/crates/ruff/src/rules/pydocstyle/rules/no_signature.rs b/crates/ruff/src/rules/pydocstyle/rules/no_signature.rs index a389bbc9b6..8abffb86ec 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/no_signature.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/no_signature.rs @@ -19,7 +19,7 @@ impl Violation for NoSignature { } /// D402 -pub fn no_signature(checker: &mut Checker, docstring: &Docstring) { +pub(crate) fn no_signature(checker: &mut Checker, docstring: &Docstring) { let Definition::Member(Member { kind: MemberKind::Function | MemberKind::NestedFunction | MemberKind::Method, stmt, diff --git a/crates/ruff/src/rules/pydocstyle/rules/no_surrounding_whitespace.rs b/crates/ruff/src/rules/pydocstyle/rules/no_surrounding_whitespace.rs index 2ef5eda776..ea2e61a8b4 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/no_surrounding_whitespace.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/no_surrounding_whitespace.rs @@ -25,7 +25,7 @@ impl Violation for SurroundingWhitespace { } /// D210 -pub fn no_surrounding_whitespace(checker: &mut Checker, docstring: &Docstring) { +pub(crate) fn no_surrounding_whitespace(checker: &mut Checker, docstring: &Docstring) { let body = docstring.body(); let mut lines = NewlineWithTrailingNewline::from(body.as_str()); diff --git a/crates/ruff/src/rules/pydocstyle/rules/non_imperative_mood.rs b/crates/ruff/src/rules/pydocstyle/rules/non_imperative_mood.rs index c4522142bf..39ec77b9ec 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/non_imperative_mood.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/non_imperative_mood.rs @@ -18,7 +18,7 @@ use crate::rules::pydocstyle::helpers::normalize_word; static MOOD: Lazy = Lazy::new(Mood::new); /// D401 -pub fn non_imperative_mood( +pub(crate) fn non_imperative_mood( checker: &mut Checker, docstring: &Docstring, property_decorators: &BTreeSet, diff --git a/crates/ruff/src/rules/pydocstyle/rules/not_empty.rs b/crates/ruff/src/rules/pydocstyle/rules/not_empty.rs index 410ccb4a21..804bea5ee0 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/not_empty.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/not_empty.rs @@ -16,7 +16,7 @@ impl Violation for EmptyDocstring { } /// D419 -pub fn not_empty(checker: &mut Checker, docstring: &Docstring) -> bool { +pub(crate) fn not_empty(checker: &mut Checker, docstring: &Docstring) -> bool { if !docstring.body().trim().is_empty() { return true; } diff --git a/crates/ruff/src/rules/pydocstyle/rules/not_missing.rs b/crates/ruff/src/rules/pydocstyle/rules/not_missing.rs index 74d7330daa..82d29685c4 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/not_missing.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/not_missing.rs @@ -93,7 +93,11 @@ impl Violation for UndocumentedPublicInit { } /// D100, D101, D102, D103, D104, D105, D106, D107 -pub fn not_missing(checker: &mut Checker, definition: &Definition, visibility: Visibility) -> bool { +pub(crate) fn not_missing( + checker: &mut Checker, + definition: &Definition, + visibility: Visibility, +) -> bool { if visibility.is_private() { return true; } diff --git a/crates/ruff/src/rules/pydocstyle/rules/one_liner.rs b/crates/ruff/src/rules/pydocstyle/rules/one_liner.rs index 2a528c6f5f..87ef30556b 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/one_liner.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/one_liner.rs @@ -24,7 +24,7 @@ impl Violation for FitsOnOneLine { } /// D200 -pub fn one_liner(checker: &mut Checker, docstring: &Docstring) { +pub(crate) fn one_liner(checker: &mut Checker, docstring: &Docstring) { let mut line_count = 0; let mut non_empty_line_count = 0; for line in NewlineWithTrailingNewline::from(docstring.body().as_str()) { diff --git a/crates/ruff/src/rules/pydocstyle/rules/sections.rs b/crates/ruff/src/rules/pydocstyle/rules/sections.rs index b6172ccebe..f5893264ed 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/sections.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/sections.rs @@ -270,7 +270,11 @@ impl AlwaysAutofixableViolation for BlankLinesBetweenHeaderAndContent { /// D212, D214, D215, D405, D406, D407, D408, D409, D410, D411, D412, D413, /// D414, D416, D417 -pub fn sections(checker: &mut Checker, docstring: &Docstring, convention: Option<&Convention>) { +pub(crate) fn sections( + checker: &mut Checker, + docstring: &Docstring, + convention: Option<&Convention>, +) { match convention { Some(Convention::Google) => { parse_google_sections( diff --git a/crates/ruff/src/rules/pydocstyle/rules/starts_with_this.rs b/crates/ruff/src/rules/pydocstyle/rules/starts_with_this.rs index 076eae502a..efe015b802 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/starts_with_this.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/starts_with_this.rs @@ -16,7 +16,7 @@ impl Violation for DocstringStartsWithThis { } /// D404 -pub fn starts_with_this(checker: &mut Checker, docstring: &Docstring) { +pub(crate) fn starts_with_this(checker: &mut Checker, docstring: &Docstring) { let body = docstring.body(); let trimmed = body.trim(); diff --git a/crates/ruff/src/rules/pydocstyle/rules/triple_quotes.rs b/crates/ruff/src/rules/pydocstyle/rules/triple_quotes.rs index 6576995579..5cf020ce38 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/triple_quotes.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/triple_quotes.rs @@ -15,7 +15,7 @@ impl Violation for TripleSingleQuotes { } /// D300 -pub fn triple_quotes(checker: &mut Checker, docstring: &Docstring) { +pub(crate) fn triple_quotes(checker: &mut Checker, docstring: &Docstring) { let body = docstring.body(); let leading_quote = docstring.leading_quote().to_ascii_lowercase(); diff --git a/crates/ruff/src/rules/pyflakes/cformat.rs b/crates/ruff/src/rules/pyflakes/cformat.rs index ceb56ad69c..e398ecf571 100644 --- a/crates/ruff/src/rules/pyflakes/cformat.rs +++ b/crates/ruff/src/rules/pyflakes/cformat.rs @@ -8,9 +8,9 @@ use rustpython_common::cformat::{ }; pub(crate) struct CFormatSummary { - pub starred: bool, - pub num_positional: usize, - pub keywords: FxHashSet, + pub(crate) starred: bool, + pub(crate) num_positional: usize, + pub(crate) keywords: FxHashSet, } impl From<&CFormatString> for CFormatSummary { diff --git a/crates/ruff/src/rules/pyflakes/fixes.rs b/crates/ruff/src/rules/pyflakes/fixes.rs index e96eef8e4c..81d442fa45 100644 --- a/crates/ruff/src/rules/pyflakes/fixes.rs +++ b/crates/ruff/src/rules/pyflakes/fixes.rs @@ -16,7 +16,7 @@ use crate::cst::matchers::{ }; /// Generate a [`Edit`] to remove unused keys from format dict. -pub fn remove_unused_format_arguments_from_dict( +pub(crate) fn remove_unused_format_arguments_from_dict( unused_arguments: &[&str], stmt: &Expr, locator: &Locator, @@ -44,7 +44,7 @@ pub fn remove_unused_format_arguments_from_dict( } /// Generate a [`Edit`] to remove unused keyword arguments from a `format` call. -pub fn remove_unused_keyword_arguments_from_format_call( +pub(crate) fn remove_unused_keyword_arguments_from_format_call( unused_arguments: &[&str], location: TextRange, locator: &Locator, @@ -126,7 +126,7 @@ fn update_field_types(format_string: &FormatString, min_unused: usize) -> String } /// Generate a [`Edit`] to remove unused positional arguments from a `format` call. -pub fn remove_unused_positional_arguments_from_format_call( +pub(crate) fn remove_unused_positional_arguments_from_format_call( unused_arguments: &[usize], location: TextRange, locator: &Locator, @@ -172,7 +172,7 @@ pub fn remove_unused_positional_arguments_from_format_call( } /// Generate a [`Edit`] to remove the binding from an exception handler. -pub fn remove_exception_handler_assignment( +pub(crate) fn remove_exception_handler_assignment( excepthandler: &Excepthandler, locator: &Locator, ) -> Result { diff --git a/crates/ruff/src/rules/pyflakes/format.rs b/crates/ruff/src/rules/pyflakes/format.rs index 3452a37ef4..ea6901b295 100644 --- a/crates/ruff/src/rules/pyflakes/format.rs +++ b/crates/ruff/src/rules/pyflakes/format.rs @@ -22,11 +22,11 @@ pub(crate) fn error_to_string(err: &FormatParseError) -> String { #[derive(Debug)] pub(crate) struct FormatSummary { - pub autos: Vec, - pub indices: Vec, - pub keywords: Vec, - pub has_nested_parts: bool, - pub format_string: FormatString, + pub(crate) autos: Vec, + pub(crate) indices: Vec, + pub(crate) keywords: Vec, + pub(crate) has_nested_parts: bool, + pub(crate) format_string: FormatString, } impl TryFrom<&str> for FormatSummary { diff --git a/crates/ruff/src/rules/pyflakes/rules/assert_tuple.rs b/crates/ruff/src/rules/pyflakes/rules/assert_tuple.rs index 3c1be41c05..fe968945a8 100644 --- a/crates/ruff/src/rules/pyflakes/rules/assert_tuple.rs +++ b/crates/ruff/src/rules/pyflakes/rules/assert_tuple.rs @@ -16,7 +16,7 @@ impl Violation for AssertTuple { } /// F631 -pub fn assert_tuple(checker: &mut Checker, stmt: &Stmt, test: &Expr) { +pub(crate) fn assert_tuple(checker: &mut Checker, stmt: &Stmt, test: &Expr) { if let ExprKind::Tuple(ast::ExprTuple { elts, .. }) = &test.node { if !elts.is_empty() { checker diff --git a/crates/ruff/src/rules/pyflakes/rules/break_outside_loop.rs b/crates/ruff/src/rules/pyflakes/rules/break_outside_loop.rs index 6a3c3e6ac5..11e8567c2d 100644 --- a/crates/ruff/src/rules/pyflakes/rules/break_outside_loop.rs +++ b/crates/ruff/src/rules/pyflakes/rules/break_outside_loop.rs @@ -14,7 +14,7 @@ impl Violation for BreakOutsideLoop { } /// F701 -pub fn break_outside_loop<'a>( +pub(crate) fn break_outside_loop<'a>( stmt: &'a Stmt, parents: &mut impl Iterator, ) -> Option { diff --git a/crates/ruff/src/rules/pyflakes/rules/continue_outside_loop.rs b/crates/ruff/src/rules/pyflakes/rules/continue_outside_loop.rs index 63077f9a9e..4b7156e0e1 100644 --- a/crates/ruff/src/rules/pyflakes/rules/continue_outside_loop.rs +++ b/crates/ruff/src/rules/pyflakes/rules/continue_outside_loop.rs @@ -14,7 +14,7 @@ impl Violation for ContinueOutsideLoop { } /// F702 -pub fn continue_outside_loop<'a>( +pub(crate) fn continue_outside_loop<'a>( stmt: &'a Stmt, parents: &mut impl Iterator, ) -> Option { diff --git a/crates/ruff/src/rules/pyflakes/rules/default_except_not_last.rs b/crates/ruff/src/rules/pyflakes/rules/default_except_not_last.rs index a8879fa826..df8c303a59 100644 --- a/crates/ruff/src/rules/pyflakes/rules/default_except_not_last.rs +++ b/crates/ruff/src/rules/pyflakes/rules/default_except_not_last.rs @@ -16,7 +16,7 @@ impl Violation for DefaultExceptNotLast { } /// F707 -pub fn default_except_not_last( +pub(crate) fn default_except_not_last( handlers: &[Excepthandler], locator: &Locator, ) -> Option { diff --git a/crates/ruff/src/rules/pyflakes/rules/f_string_missing_placeholders.rs b/crates/ruff/src/rules/pyflakes/rules/f_string_missing_placeholders.rs index df57139cb9..195e76b265 100644 --- a/crates/ruff/src/rules/pyflakes/rules/f_string_missing_placeholders.rs +++ b/crates/ruff/src/rules/pyflakes/rules/f_string_missing_placeholders.rs @@ -98,7 +98,7 @@ fn fix_f_string_missing_placeholders( } /// F541 -pub fn f_string_missing_placeholders(expr: &Expr, values: &[Expr], checker: &mut Checker) { +pub(crate) fn f_string_missing_placeholders(expr: &Expr, values: &[Expr], checker: &mut Checker) { if !values .iter() .any(|value| matches!(value.node, ExprKind::FormattedValue(_))) diff --git a/crates/ruff/src/rules/pyflakes/rules/if_tuple.rs b/crates/ruff/src/rules/pyflakes/rules/if_tuple.rs index 282e2e567d..603cbf6ac1 100644 --- a/crates/ruff/src/rules/pyflakes/rules/if_tuple.rs +++ b/crates/ruff/src/rules/pyflakes/rules/if_tuple.rs @@ -16,7 +16,7 @@ impl Violation for IfTuple { } /// F634 -pub fn if_tuple(checker: &mut Checker, stmt: &Stmt, test: &Expr) { +pub(crate) fn if_tuple(checker: &mut Checker, stmt: &Stmt, test: &Expr) { if let ExprKind::Tuple(ast::ExprTuple { elts, .. }) = &test.node { if !elts.is_empty() { checker diff --git a/crates/ruff/src/rules/pyflakes/rules/imports.rs b/crates/ruff/src/rules/pyflakes/rules/imports.rs index cf9f9290cb..0cc8305b0c 100644 --- a/crates/ruff/src/rules/pyflakes/rules/imports.rs +++ b/crates/ruff/src/rules/pyflakes/rules/imports.rs @@ -135,7 +135,7 @@ impl Violation for FutureFeatureNotDefined { } } -pub fn future_feature_not_defined(checker: &mut Checker, alias: &Alias) { +pub(crate) fn future_feature_not_defined(checker: &mut Checker, alias: &Alias) { if !ALL_FEATURE_NAMES.contains(&alias.node.name.as_str()) { checker.diagnostics.push(Diagnostic::new( FutureFeatureNotDefined { diff --git a/crates/ruff/src/rules/pyflakes/rules/invalid_literal_comparisons.rs b/crates/ruff/src/rules/pyflakes/rules/invalid_literal_comparisons.rs index 630e34efea..cb415c3ee3 100644 --- a/crates/ruff/src/rules/pyflakes/rules/invalid_literal_comparisons.rs +++ b/crates/ruff/src/rules/pyflakes/rules/invalid_literal_comparisons.rs @@ -12,7 +12,7 @@ use crate::checkers::ast::Checker; use crate::registry::AsRule; #[derive(Debug, PartialEq, Eq, Copy, Clone)] -pub enum IsCmpop { +pub(crate) enum IsCmpop { Is, IsNot, } @@ -52,7 +52,7 @@ impl AlwaysAutofixableViolation for IsLiteral { } /// F632 -pub fn invalid_literal_comparison( +pub(crate) fn invalid_literal_comparison( checker: &mut Checker, left: &Expr, ops: &[Cmpop], diff --git a/crates/ruff/src/rules/pyflakes/rules/invalid_print_syntax.rs b/crates/ruff/src/rules/pyflakes/rules/invalid_print_syntax.rs index f75ecf9a52..3539bc6786 100644 --- a/crates/ruff/src/rules/pyflakes/rules/invalid_print_syntax.rs +++ b/crates/ruff/src/rules/pyflakes/rules/invalid_print_syntax.rs @@ -16,7 +16,7 @@ impl Violation for InvalidPrintSyntax { } /// F633 -pub fn invalid_print_syntax(checker: &mut Checker, left: &Expr) { +pub(crate) fn invalid_print_syntax(checker: &mut Checker, left: &Expr) { let ExprKind::Name(ast::ExprName { id, .. }) = &left.node else { return; }; diff --git a/crates/ruff/src/rules/pyflakes/rules/mod.rs b/crates/ruff/src/rules/pyflakes/rules/mod.rs index 4f466f57f1..530a920a56 100644 --- a/crates/ruff/src/rules/pyflakes/rules/mod.rs +++ b/crates/ruff/src/rules/pyflakes/rules/mod.rs @@ -1,26 +1,26 @@ -pub use assert_tuple::{assert_tuple, AssertTuple}; -pub use break_outside_loop::{break_outside_loop, BreakOutsideLoop}; -pub use continue_outside_loop::{continue_outside_loop, ContinueOutsideLoop}; -pub use default_except_not_last::{default_except_not_last, DefaultExceptNotLast}; -pub use f_string_missing_placeholders::{ +pub(crate) use assert_tuple::{assert_tuple, AssertTuple}; +pub(crate) use break_outside_loop::{break_outside_loop, BreakOutsideLoop}; +pub(crate) use continue_outside_loop::{continue_outside_loop, ContinueOutsideLoop}; +pub(crate) use default_except_not_last::{default_except_not_last, DefaultExceptNotLast}; +pub(crate) use f_string_missing_placeholders::{ f_string_missing_placeholders, FStringMissingPlaceholders, }; -pub use forward_annotation_syntax_error::ForwardAnnotationSyntaxError; -pub use if_tuple::{if_tuple, IfTuple}; -pub use imports::{ +pub(crate) use forward_annotation_syntax_error::ForwardAnnotationSyntaxError; +pub(crate) use if_tuple::{if_tuple, IfTuple}; +pub(crate) use imports::{ future_feature_not_defined, FutureFeatureNotDefined, ImportShadowedByLoopVar, LateFutureImport, UndefinedLocalWithImportStar, UndefinedLocalWithImportStarUsage, UndefinedLocalWithNestedImportStarUsage, UnusedImport, UnusedImportContext, }; -pub use invalid_literal_comparisons::{invalid_literal_comparison, IsLiteral}; -pub use invalid_print_syntax::{invalid_print_syntax, InvalidPrintSyntax}; -pub use raise_not_implemented::{raise_not_implemented, RaiseNotImplemented}; -pub use redefined_while_unused::RedefinedWhileUnused; -pub use repeated_keys::{ +pub(crate) use invalid_literal_comparisons::{invalid_literal_comparison, IsLiteral}; +pub(crate) use invalid_print_syntax::{invalid_print_syntax, InvalidPrintSyntax}; +pub(crate) use raise_not_implemented::{raise_not_implemented, RaiseNotImplemented}; +pub(crate) use redefined_while_unused::RedefinedWhileUnused; +pub(crate) use repeated_keys::{ repeated_keys, MultiValueRepeatedKeyLiteral, MultiValueRepeatedKeyVariable, }; -pub use return_outside_function::{return_outside_function, ReturnOutsideFunction}; -pub use starred_expressions::{ +pub(crate) use return_outside_function::{return_outside_function, ReturnOutsideFunction}; +pub(crate) use starred_expressions::{ starred_expressions, ExpressionsInStarAssignment, MultipleStarredExpressions, }; pub(crate) use strings::{ @@ -37,12 +37,12 @@ pub(crate) use strings::{ StringDotFormatExtraPositionalArguments, StringDotFormatInvalidFormat, StringDotFormatMissingArguments, StringDotFormatMixingAutomatic, }; -pub use undefined_export::{undefined_export, UndefinedExport}; -pub use undefined_local::{undefined_local, UndefinedLocal}; -pub use undefined_name::UndefinedName; -pub use unused_annotation::{unused_annotation, UnusedAnnotation}; -pub use unused_variable::{unused_variable, UnusedVariable}; -pub use yield_outside_function::{yield_outside_function, YieldOutsideFunction}; +pub(crate) use undefined_export::{undefined_export, UndefinedExport}; +pub(crate) use undefined_local::{undefined_local, UndefinedLocal}; +pub(crate) use undefined_name::UndefinedName; +pub(crate) use unused_annotation::{unused_annotation, UnusedAnnotation}; +pub(crate) use unused_variable::{unused_variable, UnusedVariable}; +pub(crate) use yield_outside_function::{yield_outside_function, YieldOutsideFunction}; mod assert_tuple; mod break_outside_loop; diff --git a/crates/ruff/src/rules/pyflakes/rules/raise_not_implemented.rs b/crates/ruff/src/rules/pyflakes/rules/raise_not_implemented.rs index fef06dfef0..89f43a0392 100644 --- a/crates/ruff/src/rules/pyflakes/rules/raise_not_implemented.rs +++ b/crates/ruff/src/rules/pyflakes/rules/raise_not_implemented.rs @@ -40,7 +40,7 @@ fn match_not_implemented(expr: &Expr) -> Option<&Expr> { } /// F901 -pub fn raise_not_implemented(checker: &mut Checker, expr: &Expr) { +pub(crate) fn raise_not_implemented(checker: &mut Checker, expr: &Expr) { let Some(expr) = match_not_implemented(expr) else { return; }; diff --git a/crates/ruff/src/rules/pyflakes/rules/repeated_keys.rs b/crates/ruff/src/rules/pyflakes/rules/repeated_keys.rs index b21b7212e6..1d80f9550d 100644 --- a/crates/ruff/src/rules/pyflakes/rules/repeated_keys.rs +++ b/crates/ruff/src/rules/pyflakes/rules/repeated_keys.rs @@ -83,7 +83,7 @@ fn into_dictionary_key(expr: &Expr) -> Option { } /// F601, F602 -pub fn repeated_keys(checker: &mut Checker, keys: &[Option], values: &[Expr]) { +pub(crate) fn repeated_keys(checker: &mut Checker, keys: &[Option], values: &[Expr]) { // Generate a map from key to (index, value). let mut seen: FxHashMap> = FxHashMap::with_capacity_and_hasher(keys.len(), BuildHasherDefault::default()); diff --git a/crates/ruff/src/rules/pyflakes/rules/return_outside_function.rs b/crates/ruff/src/rules/pyflakes/rules/return_outside_function.rs index 262c7163de..c67e4b6159 100644 --- a/crates/ruff/src/rules/pyflakes/rules/return_outside_function.rs +++ b/crates/ruff/src/rules/pyflakes/rules/return_outside_function.rs @@ -16,7 +16,7 @@ impl Violation for ReturnOutsideFunction { } } -pub fn return_outside_function(checker: &mut Checker, stmt: &Stmt) { +pub(crate) fn return_outside_function(checker: &mut Checker, stmt: &Stmt) { if matches!( checker.ctx.scope().kind, ScopeKind::Class(_) | ScopeKind::Module diff --git a/crates/ruff/src/rules/pyflakes/rules/starred_expressions.rs b/crates/ruff/src/rules/pyflakes/rules/starred_expressions.rs index b2d327e141..90ea89588e 100644 --- a/crates/ruff/src/rules/pyflakes/rules/starred_expressions.rs +++ b/crates/ruff/src/rules/pyflakes/rules/starred_expressions.rs @@ -25,7 +25,7 @@ impl Violation for MultipleStarredExpressions { } /// F621, F622 -pub fn starred_expressions( +pub(crate) fn starred_expressions( elts: &[Expr], check_too_many_expressions: bool, check_two_starred_expressions: bool, diff --git a/crates/ruff/src/rules/pyflakes/rules/undefined_export.rs b/crates/ruff/src/rules/pyflakes/rules/undefined_export.rs index e792c4eb23..1ad222cbf1 100644 --- a/crates/ruff/src/rules/pyflakes/rules/undefined_export.rs +++ b/crates/ruff/src/rules/pyflakes/rules/undefined_export.rs @@ -17,7 +17,7 @@ impl Violation for UndefinedExport { } /// F822 -pub fn undefined_export(names: &[&str], range: TextRange, scope: &Scope) -> Vec { +pub(crate) fn undefined_export(names: &[&str], range: TextRange, scope: &Scope) -> Vec { let mut diagnostics = Vec::new(); if !scope.uses_star_imports() { for name in names { diff --git a/crates/ruff/src/rules/pyflakes/rules/undefined_local.rs b/crates/ruff/src/rules/pyflakes/rules/undefined_local.rs index 78388aaad4..1d7a4b868f 100644 --- a/crates/ruff/src/rules/pyflakes/rules/undefined_local.rs +++ b/crates/ruff/src/rules/pyflakes/rules/undefined_local.rs @@ -19,7 +19,7 @@ impl Violation for UndefinedLocal { } /// F823 -pub fn undefined_local(checker: &mut Checker, name: &str) { +pub(crate) fn undefined_local(checker: &mut Checker, name: &str) { // If the name hasn't already been defined in the current scope... let current = checker.ctx.scope(); if !current.kind.is_function() || current.defines(name) { diff --git a/crates/ruff/src/rules/pyflakes/rules/unused_annotation.rs b/crates/ruff/src/rules/pyflakes/rules/unused_annotation.rs index f83443113d..b29e52bbcf 100644 --- a/crates/ruff/src/rules/pyflakes/rules/unused_annotation.rs +++ b/crates/ruff/src/rules/pyflakes/rules/unused_annotation.rs @@ -18,7 +18,7 @@ impl Violation for UnusedAnnotation { } /// F842 -pub fn unused_annotation(checker: &mut Checker, scope: ScopeId) { +pub(crate) fn unused_annotation(checker: &mut Checker, scope: ScopeId) { let scope = &checker.ctx.scopes[scope]; for (name, binding) in scope .bindings() diff --git a/crates/ruff/src/rules/pyflakes/rules/unused_variable.rs b/crates/ruff/src/rules/pyflakes/rules/unused_variable.rs index 77a4c1ff72..e0f5b54074 100644 --- a/crates/ruff/src/rules/pyflakes/rules/unused_variable.rs +++ b/crates/ruff/src/rules/pyflakes/rules/unused_variable.rs @@ -310,7 +310,7 @@ fn remove_unused_variable( } /// F841 -pub fn unused_variable(checker: &mut Checker, scope: ScopeId) { +pub(crate) fn unused_variable(checker: &mut Checker, scope: ScopeId) { let scope = &checker.ctx.scopes[scope]; if scope.uses_locals && matches!(scope.kind, ScopeKind::Function(..)) { return; diff --git a/crates/ruff/src/rules/pyflakes/rules/yield_outside_function.rs b/crates/ruff/src/rules/pyflakes/rules/yield_outside_function.rs index afb234367b..cf615d5bc5 100644 --- a/crates/ruff/src/rules/pyflakes/rules/yield_outside_function.rs +++ b/crates/ruff/src/rules/pyflakes/rules/yield_outside_function.rs @@ -9,7 +9,7 @@ use ruff_python_semantic::scope::ScopeKind; use crate::checkers::ast::Checker; #[derive(Debug, PartialEq, Eq)] -pub enum DeferralKeyword { +pub(crate) enum DeferralKeyword { Yield, YieldFrom, Await, @@ -38,7 +38,7 @@ impl Violation for YieldOutsideFunction { } } -pub fn yield_outside_function(checker: &mut Checker, expr: &Expr) { +pub(crate) fn yield_outside_function(checker: &mut Checker, expr: &Expr) { if matches!( checker.ctx.scope().kind, ScopeKind::Class(_) | ScopeKind::Module diff --git a/crates/ruff/src/rules/pygrep_hooks/rules/deprecated_log_warn.rs b/crates/ruff/src/rules/pygrep_hooks/rules/deprecated_log_warn.rs index 6ad7c75ff2..b49582ebcf 100644 --- a/crates/ruff/src/rules/pygrep_hooks/rules/deprecated_log_warn.rs +++ b/crates/ruff/src/rules/pygrep_hooks/rules/deprecated_log_warn.rs @@ -42,7 +42,7 @@ impl Violation for DeprecatedLogWarn { } /// PGH002 -pub fn deprecated_log_warn(checker: &mut Checker, func: &Expr) { +pub(crate) fn deprecated_log_warn(checker: &mut Checker, func: &Expr) { if checker .ctx .resolve_call_path(func) diff --git a/crates/ruff/src/rules/pygrep_hooks/rules/invalid_mock_access.rs b/crates/ruff/src/rules/pygrep_hooks/rules/invalid_mock_access.rs index 4c148bfbe5..ff0e073cbb 100644 --- a/crates/ruff/src/rules/pygrep_hooks/rules/invalid_mock_access.rs +++ b/crates/ruff/src/rules/pygrep_hooks/rules/invalid_mock_access.rs @@ -48,7 +48,7 @@ impl Violation for InvalidMockAccess { } /// PGH005 -pub fn uncalled_mock_method(checker: &mut Checker, expr: &Expr) { +pub(crate) fn uncalled_mock_method(checker: &mut Checker, expr: &Expr) { if let ExprKind::Attribute(ast::ExprAttribute { attr, .. }) = &expr.node { if matches!( attr.as_str(), @@ -71,7 +71,7 @@ pub fn uncalled_mock_method(checker: &mut Checker, expr: &Expr) { } /// PGH005 -pub fn non_existent_mock_method(checker: &mut Checker, test: &Expr) { +pub(crate) fn non_existent_mock_method(checker: &mut Checker, test: &Expr) { let attr = match &test.node { ExprKind::Attribute(ast::ExprAttribute { attr, .. }) => attr, ExprKind::Call(ast::ExprCall { func, .. }) => match &func.node { diff --git a/crates/ruff/src/rules/pygrep_hooks/rules/no_eval.rs b/crates/ruff/src/rules/pygrep_hooks/rules/no_eval.rs index d0513921e9..6dcdf7e852 100644 --- a/crates/ruff/src/rules/pygrep_hooks/rules/no_eval.rs +++ b/crates/ruff/src/rules/pygrep_hooks/rules/no_eval.rs @@ -39,7 +39,7 @@ impl Violation for Eval { } /// PGH001 -pub fn no_eval(checker: &mut Checker, func: &Expr) { +pub(crate) fn no_eval(checker: &mut Checker, func: &Expr) { let ExprKind::Name(ast::ExprName { id, .. }) = &func.node else { return; }; diff --git a/crates/ruff/src/rules/pylint/helpers.rs b/crates/ruff/src/rules/pylint/helpers.rs index ca3e84daa6..1c51bef4b0 100644 --- a/crates/ruff/src/rules/pylint/helpers.rs +++ b/crates/ruff/src/rules/pylint/helpers.rs @@ -4,7 +4,7 @@ use ruff_python_semantic::scope::{FunctionDef, ScopeKind}; use crate::checkers::ast::Checker; -pub fn in_dunder_init(checker: &Checker) -> bool { +pub(crate) fn in_dunder_init(checker: &Checker) -> bool { let scope = checker.ctx.scope(); let ScopeKind::Function(FunctionDef { name, diff --git a/crates/ruff/src/rules/pylint/rules/assert_on_string_literal.rs b/crates/ruff/src/rules/pylint/rules/assert_on_string_literal.rs index ebac688071..35351db205 100644 --- a/crates/ruff/src/rules/pylint/rules/assert_on_string_literal.rs +++ b/crates/ruff/src/rules/pylint/rules/assert_on_string_literal.rs @@ -42,7 +42,7 @@ impl Violation for AssertOnStringLiteral { } /// PLW0129 -pub fn assert_on_string_literal(checker: &mut Checker, test: &Expr) { +pub(crate) fn assert_on_string_literal(checker: &mut Checker, test: &Expr) { match &test.node { ExprKind::Constant(ast::ExprConstant { value, .. }) => match value { Constant::Str(value, ..) => { diff --git a/crates/ruff/src/rules/pylint/rules/await_outside_async.rs b/crates/ruff/src/rules/pylint/rules/await_outside_async.rs index fdc54f37e8..b13276f9ca 100644 --- a/crates/ruff/src/rules/pylint/rules/await_outside_async.rs +++ b/crates/ruff/src/rules/pylint/rules/await_outside_async.rs @@ -17,7 +17,7 @@ impl Violation for AwaitOutsideAsync { } /// PLE1142 -pub fn await_outside_async(checker: &mut Checker, expr: &Expr) { +pub(crate) fn await_outside_async(checker: &mut Checker, expr: &Expr) { if !checker .ctx .scopes() diff --git a/crates/ruff/src/rules/pylint/rules/bad_str_strip_call.rs b/crates/ruff/src/rules/pylint/rules/bad_str_strip_call.rs index d49bd42adf..17bc52cc01 100644 --- a/crates/ruff/src/rules/pylint/rules/bad_str_strip_call.rs +++ b/crates/ruff/src/rules/pylint/rules/bad_str_strip_call.rs @@ -30,14 +30,14 @@ impl Violation for BadStrStripCall { } #[derive(Debug, PartialEq, Eq, Copy, Clone)] -pub enum StripKind { +pub(crate) enum StripKind { Strip, LStrip, RStrip, } impl StripKind { - pub fn from_str(s: &str) -> Option { + pub(crate) fn from_str(s: &str) -> Option { match s { "strip" => Some(Self::Strip), "lstrip" => Some(Self::LStrip), @@ -59,13 +59,13 @@ impl fmt::Display for StripKind { } #[derive(Debug, PartialEq, Eq, Copy, Clone)] -pub enum RemovalKind { +pub(crate) enum RemovalKind { RemovePrefix, RemoveSuffix, } impl RemovalKind { - pub fn for_strip(s: StripKind) -> Option { + pub(crate) fn for_strip(s: StripKind) -> Option { match s { StripKind::Strip => None, StripKind::LStrip => Some(Self::RemovePrefix), @@ -106,7 +106,7 @@ fn has_duplicates(s: &str) -> bool { } /// PLE1310 -pub fn bad_str_strip_call(checker: &mut Checker, func: &Expr, args: &[Expr]) { +pub(crate) fn bad_str_strip_call(checker: &mut Checker, func: &Expr, args: &[Expr]) { if let ExprKind::Attribute(ast::ExprAttribute { value, attr, .. }) = &func.node { if matches!( value.node, diff --git a/crates/ruff/src/rules/pylint/rules/bad_string_format_type.rs b/crates/ruff/src/rules/pylint/rules/bad_string_format_type.rs index c1b322d991..6da4fa492d 100644 --- a/crates/ruff/src/rules/pylint/rules/bad_string_format_type.rs +++ b/crates/ruff/src/rules/pylint/rules/bad_string_format_type.rs @@ -241,7 +241,7 @@ fn is_valid_dict( } /// PLE1307 -pub fn bad_string_format_type(checker: &mut Checker, expr: &Expr, right: &Expr) { +pub(crate) fn bad_string_format_type(checker: &mut Checker, expr: &Expr, right: &Expr) { // Grab each string segment (in case there's an implicit concatenation). let content = checker.locator.slice(expr.range()); let mut strings: Vec = vec![]; diff --git a/crates/ruff/src/rules/pylint/rules/bidirectional_unicode.rs b/crates/ruff/src/rules/pylint/rules/bidirectional_unicode.rs index 769ac2de90..f48db58407 100644 --- a/crates/ruff/src/rules/pylint/rules/bidirectional_unicode.rs +++ b/crates/ruff/src/rules/pylint/rules/bidirectional_unicode.rs @@ -33,7 +33,7 @@ impl Violation for BidirectionalUnicode { } /// PLE2502 -pub fn bidirectional_unicode(line: &Line) -> Vec { +pub(crate) fn bidirectional_unicode(line: &Line) -> Vec { let mut diagnostics = Vec::new(); if line.contains(BIDI_UNICODE) { diagnostics.push(Diagnostic::new(BidirectionalUnicode, line.full_range())); diff --git a/crates/ruff/src/rules/pylint/rules/binary_op_exception.rs b/crates/ruff/src/rules/pylint/rules/binary_op_exception.rs index ef3d7cda55..e25f277111 100644 --- a/crates/ruff/src/rules/pylint/rules/binary_op_exception.rs +++ b/crates/ruff/src/rules/pylint/rules/binary_op_exception.rs @@ -62,7 +62,7 @@ impl Violation for BinaryOpException { } /// PLW0711 -pub fn binary_op_exception(checker: &mut Checker, excepthandler: &Excepthandler) { +pub(crate) fn binary_op_exception(checker: &mut Checker, excepthandler: &Excepthandler) { let ExcepthandlerKind::ExceptHandler(ast::ExcepthandlerExceptHandler { type_, .. }) = &excepthandler.node; diff --git a/crates/ruff/src/rules/pylint/rules/collapsible_else_if.rs b/crates/ruff/src/rules/pylint/rules/collapsible_else_if.rs index 875397cbf2..82eafe5af8 100644 --- a/crates/ruff/src/rules/pylint/rules/collapsible_else_if.rs +++ b/crates/ruff/src/rules/pylint/rules/collapsible_else_if.rs @@ -15,7 +15,7 @@ impl Violation for CollapsibleElseIf { } /// PLR5501 -pub fn collapsible_else_if(orelse: &[Stmt], locator: &Locator) -> Option { +pub(crate) fn collapsible_else_if(orelse: &[Stmt], locator: &Locator) -> Option { if orelse.len() == 1 { let first = &orelse[0]; if matches!(first.node, StmtKind::If(_)) { diff --git a/crates/ruff/src/rules/pylint/rules/compare_to_empty_string.rs b/crates/ruff/src/rules/pylint/rules/compare_to_empty_string.rs index 7f0fd30f7a..8fbcabaa90 100644 --- a/crates/ruff/src/rules/pylint/rules/compare_to_empty_string.rs +++ b/crates/ruff/src/rules/pylint/rules/compare_to_empty_string.rs @@ -9,7 +9,7 @@ use ruff_python_ast::helpers::{unparse_constant, unparse_expr}; use crate::checkers::ast::Checker; #[derive(Debug, PartialEq, Eq, Copy, Clone)] -pub enum EmptyStringCmpop { +pub(crate) enum EmptyStringCmpop { Is, IsNot, Eq, @@ -31,7 +31,7 @@ impl TryFrom<&Cmpop> for EmptyStringCmpop { } impl EmptyStringCmpop { - pub fn into_unary(self) -> &'static str { + pub(crate) fn into_unary(self) -> &'static str { match self { Self::Is | Self::Eq => "not ", Self::IsNot | Self::NotEq => "", @@ -91,7 +91,7 @@ impl Violation for CompareToEmptyString { } } -pub fn compare_to_empty_string( +pub(crate) fn compare_to_empty_string( checker: &mut Checker, left: &Expr, ops: &[Cmpop], diff --git a/crates/ruff/src/rules/pylint/rules/comparison_of_constant.rs b/crates/ruff/src/rules/pylint/rules/comparison_of_constant.rs index 79879d284c..2bb1f6fa7f 100644 --- a/crates/ruff/src/rules/pylint/rules/comparison_of_constant.rs +++ b/crates/ruff/src/rules/pylint/rules/comparison_of_constant.rs @@ -10,7 +10,7 @@ use ruff_python_ast::helpers::unparse_constant; use crate::checkers::ast::Checker; #[derive(Debug, PartialEq, Eq, Copy, Clone)] -pub enum ViolationsCmpop { +pub(crate) enum ViolationsCmpop { Eq, NotEq, Lt, @@ -82,7 +82,7 @@ impl Violation for ComparisonOfConstant { } /// PLR0133 -pub fn comparison_of_constant( +pub(crate) fn comparison_of_constant( checker: &mut Checker, left: &Expr, ops: &[Cmpop], diff --git a/crates/ruff/src/rules/pylint/rules/continue_in_finally.rs b/crates/ruff/src/rules/pylint/rules/continue_in_finally.rs index abf952d1d1..675ec8bf7a 100644 --- a/crates/ruff/src/rules/pylint/rules/continue_in_finally.rs +++ b/crates/ruff/src/rules/pylint/rules/continue_in_finally.rs @@ -75,6 +75,6 @@ fn traverse_body(checker: &mut Checker, body: &[Stmt]) { } /// PLE0116 -pub fn continue_in_finally(checker: &mut Checker, body: &[Stmt]) { +pub(crate) fn continue_in_finally(checker: &mut Checker, body: &[Stmt]) { traverse_body(checker, body); } diff --git a/crates/ruff/src/rules/pylint/rules/global_statement.rs b/crates/ruff/src/rules/pylint/rules/global_statement.rs index 357eaa9dc4..1a8114eaaa 100644 --- a/crates/ruff/src/rules/pylint/rules/global_statement.rs +++ b/crates/ruff/src/rules/pylint/rules/global_statement.rs @@ -52,7 +52,7 @@ impl Violation for GlobalStatement { } /// PLW0603 -pub fn global_statement(checker: &mut Checker, name: &str) { +pub(crate) fn global_statement(checker: &mut Checker, name: &str) { let scope = checker.ctx.scope(); if let Some(index) = scope.get(name) { let binding = &checker.ctx.bindings[*index]; diff --git a/crates/ruff/src/rules/pylint/rules/import_self.rs b/crates/ruff/src/rules/pylint/rules/import_self.rs index 1020a0174f..18a39fdfea 100644 --- a/crates/ruff/src/rules/pylint/rules/import_self.rs +++ b/crates/ruff/src/rules/pylint/rules/import_self.rs @@ -18,7 +18,7 @@ impl Violation for ImportSelf { } /// PLW0406 -pub fn import_self(alias: &Alias, module_path: Option<&[String]>) -> Option { +pub(crate) fn import_self(alias: &Alias, module_path: Option<&[String]>) -> Option { let Some(module_path) = module_path else { return None; }; @@ -36,7 +36,7 @@ pub fn import_self(alias: &Alias, module_path: Option<&[String]>) -> Option, module: Option<&str>, names: &[Alias], diff --git a/crates/ruff/src/rules/pylint/rules/invalid_all_format.rs b/crates/ruff/src/rules/pylint/rules/invalid_all_format.rs index ad9525fc52..b293f74d15 100644 --- a/crates/ruff/src/rules/pylint/rules/invalid_all_format.rs +++ b/crates/ruff/src/rules/pylint/rules/invalid_all_format.rs @@ -14,6 +14,6 @@ impl Violation for InvalidAllFormat { } /// PLE0605 -pub fn invalid_all_format(expr: &Expr) -> Diagnostic { +pub(crate) fn invalid_all_format(expr: &Expr) -> Diagnostic { Diagnostic::new(InvalidAllFormat, expr.range()) } diff --git a/crates/ruff/src/rules/pylint/rules/invalid_all_object.rs b/crates/ruff/src/rules/pylint/rules/invalid_all_object.rs index 542182b163..667880aab1 100644 --- a/crates/ruff/src/rules/pylint/rules/invalid_all_object.rs +++ b/crates/ruff/src/rules/pylint/rules/invalid_all_object.rs @@ -14,6 +14,6 @@ impl Violation for InvalidAllObject { } /// PLE0604 -pub fn invalid_all_object(expr: &Expr) -> Diagnostic { +pub(crate) fn invalid_all_object(expr: &Expr) -> Diagnostic { Diagnostic::new(InvalidAllObject, expr.range()) } diff --git a/crates/ruff/src/rules/pylint/rules/invalid_envvar_default.rs b/crates/ruff/src/rules/pylint/rules/invalid_envvar_default.rs index d0e33487a2..975326f5a9 100644 --- a/crates/ruff/src/rules/pylint/rules/invalid_envvar_default.rs +++ b/crates/ruff/src/rules/pylint/rules/invalid_envvar_default.rs @@ -76,7 +76,7 @@ fn is_valid_default(expr: &Expr) -> bool { } /// PLW1508 -pub fn invalid_envvar_default( +pub(crate) fn invalid_envvar_default( checker: &mut Checker, func: &Expr, args: &[Expr], diff --git a/crates/ruff/src/rules/pylint/rules/invalid_envvar_value.rs b/crates/ruff/src/rules/pylint/rules/invalid_envvar_value.rs index b4315923dd..a701dadadc 100644 --- a/crates/ruff/src/rules/pylint/rules/invalid_envvar_value.rs +++ b/crates/ruff/src/rules/pylint/rules/invalid_envvar_value.rs @@ -73,7 +73,7 @@ fn is_valid_key(expr: &Expr) -> bool { } /// PLE1507 -pub fn invalid_envvar_value( +pub(crate) fn invalid_envvar_value( checker: &mut Checker, func: &Expr, args: &[Expr], diff --git a/crates/ruff/src/rules/pylint/rules/invalid_string_characters.rs b/crates/ruff/src/rules/pylint/rules/invalid_string_characters.rs index 701a03545a..7a792d3bcb 100644 --- a/crates/ruff/src/rules/pylint/rules/invalid_string_characters.rs +++ b/crates/ruff/src/rules/pylint/rules/invalid_string_characters.rs @@ -171,7 +171,7 @@ impl AlwaysAutofixableViolation for InvalidCharacterZeroWidthSpace { } /// PLE2510, PLE2512, PLE2513, PLE2514, PLE2515 -pub fn invalid_string_characters(locator: &Locator, range: TextRange) -> Vec { +pub(crate) fn invalid_string_characters(locator: &Locator, range: TextRange) -> Vec { let mut diagnostics = Vec::new(); let text = locator.slice(range); diff --git a/crates/ruff/src/rules/pylint/rules/load_before_global_declaration.rs b/crates/ruff/src/rules/pylint/rules/load_before_global_declaration.rs index 21f8a98838..3884d3a4dd 100644 --- a/crates/ruff/src/rules/pylint/rules/load_before_global_declaration.rs +++ b/crates/ruff/src/rules/pylint/rules/load_before_global_declaration.rs @@ -21,7 +21,7 @@ impl Violation for LoadBeforeGlobalDeclaration { } } /// PLE0118 -pub fn load_before_global_declaration(checker: &mut Checker, name: &str, expr: &Expr) { +pub(crate) fn load_before_global_declaration(checker: &mut Checker, name: &str, expr: &Expr) { let globals = match &checker.ctx.scope().kind { ScopeKind::Class(class_def) => &class_def.globals, ScopeKind::Function(function_def) => &function_def.globals, diff --git a/crates/ruff/src/rules/pylint/rules/logging.rs b/crates/ruff/src/rules/pylint/rules/logging.rs index 12459fb01a..f101d47e82 100644 --- a/crates/ruff/src/rules/pylint/rules/logging.rs +++ b/crates/ruff/src/rules/pylint/rules/logging.rs @@ -86,7 +86,12 @@ impl Violation for LoggingTooManyArgs { /// PLE1205 /// PLE1206 -pub fn logging_call(checker: &mut Checker, func: &Expr, args: &[Expr], keywords: &[Keyword]) { +pub(crate) fn logging_call( + checker: &mut Checker, + func: &Expr, + args: &[Expr], + keywords: &[Keyword], +) { // If there are any starred arguments, abort. if args .iter() diff --git a/crates/ruff/src/rules/pylint/rules/magic_value_comparison.rs b/crates/ruff/src/rules/pylint/rules/magic_value_comparison.rs index ed2e0d5364..65dad6c06d 100644 --- a/crates/ruff/src/rules/pylint/rules/magic_value_comparison.rs +++ b/crates/ruff/src/rules/pylint/rules/magic_value_comparison.rs @@ -61,7 +61,7 @@ fn is_magic_value(constant: &Constant, allowed_types: &[ConstantType]) -> bool { } /// PLR2004 -pub fn magic_value_comparison(checker: &mut Checker, left: &Expr, comparators: &[Expr]) { +pub(crate) fn magic_value_comparison(checker: &mut Checker, left: &Expr, comparators: &[Expr]) { for (left, right) in std::iter::once(left) .chain(comparators.iter()) .tuple_windows() diff --git a/crates/ruff/src/rules/pylint/rules/manual_import_from.rs b/crates/ruff/src/rules/pylint/rules/manual_import_from.rs index 5a007f0a2e..76fe5d7643 100644 --- a/crates/ruff/src/rules/pylint/rules/manual_import_from.rs +++ b/crates/ruff/src/rules/pylint/rules/manual_import_from.rs @@ -29,7 +29,12 @@ impl Violation for ManualFromImport { } /// PLR0402 -pub fn manual_from_import(checker: &mut Checker, stmt: &Stmt, alias: &Alias, names: &[Alias]) { +pub(crate) fn manual_from_import( + checker: &mut Checker, + stmt: &Stmt, + alias: &Alias, + names: &[Alias], +) { let Some(asname) = &alias.node.asname else { return; }; diff --git a/crates/ruff/src/rules/pylint/rules/mod.rs b/crates/ruff/src/rules/pylint/rules/mod.rs index 3eedc61243..19ac6fb52f 100644 --- a/crates/ruff/src/rules/pylint/rules/mod.rs +++ b/crates/ruff/src/rules/pylint/rules/mod.rs @@ -1,51 +1,51 @@ -pub use assert_on_string_literal::{assert_on_string_literal, AssertOnStringLiteral}; -pub use await_outside_async::{await_outside_async, AwaitOutsideAsync}; -pub use bad_str_strip_call::{bad_str_strip_call, BadStrStripCall}; -pub use bad_string_format_type::{bad_string_format_type, BadStringFormatType}; -pub use bidirectional_unicode::{bidirectional_unicode, BidirectionalUnicode}; -pub use binary_op_exception::{binary_op_exception, BinaryOpException}; -pub use collapsible_else_if::{collapsible_else_if, CollapsibleElseIf}; -pub use compare_to_empty_string::{compare_to_empty_string, CompareToEmptyString}; -pub use comparison_of_constant::{comparison_of_constant, ComparisonOfConstant}; -pub use continue_in_finally::{continue_in_finally, ContinueInFinally}; -pub use global_statement::{global_statement, GlobalStatement}; -pub use global_variable_not_assigned::GlobalVariableNotAssigned; -pub use import_self::{import_from_self, import_self, ImportSelf}; -pub use invalid_all_format::{invalid_all_format, InvalidAllFormat}; -pub use invalid_all_object::{invalid_all_object, InvalidAllObject}; -pub use invalid_envvar_default::{invalid_envvar_default, InvalidEnvvarDefault}; -pub use invalid_envvar_value::{invalid_envvar_value, InvalidEnvvarValue}; -pub use invalid_string_characters::{ +pub(crate) use assert_on_string_literal::{assert_on_string_literal, AssertOnStringLiteral}; +pub(crate) use await_outside_async::{await_outside_async, AwaitOutsideAsync}; +pub(crate) use bad_str_strip_call::{bad_str_strip_call, BadStrStripCall}; +pub(crate) use bad_string_format_type::{bad_string_format_type, BadStringFormatType}; +pub(crate) use bidirectional_unicode::{bidirectional_unicode, BidirectionalUnicode}; +pub(crate) use binary_op_exception::{binary_op_exception, BinaryOpException}; +pub(crate) use collapsible_else_if::{collapsible_else_if, CollapsibleElseIf}; +pub(crate) use compare_to_empty_string::{compare_to_empty_string, CompareToEmptyString}; +pub(crate) use comparison_of_constant::{comparison_of_constant, ComparisonOfConstant}; +pub(crate) use continue_in_finally::{continue_in_finally, ContinueInFinally}; +pub(crate) use global_statement::{global_statement, GlobalStatement}; +pub(crate) use global_variable_not_assigned::GlobalVariableNotAssigned; +pub(crate) use import_self::{import_from_self, import_self, ImportSelf}; +pub(crate) use invalid_all_format::{invalid_all_format, InvalidAllFormat}; +pub(crate) use invalid_all_object::{invalid_all_object, InvalidAllObject}; +pub(crate) use invalid_envvar_default::{invalid_envvar_default, InvalidEnvvarDefault}; +pub(crate) use invalid_envvar_value::{invalid_envvar_value, InvalidEnvvarValue}; +pub(crate) use invalid_string_characters::{ invalid_string_characters, InvalidCharacterBackspace, InvalidCharacterEsc, InvalidCharacterNul, InvalidCharacterSub, InvalidCharacterZeroWidthSpace, }; -pub use load_before_global_declaration::{ +pub(crate) use load_before_global_declaration::{ load_before_global_declaration, LoadBeforeGlobalDeclaration, }; -pub use logging::{logging_call, LoggingTooFewArgs, LoggingTooManyArgs}; -pub use magic_value_comparison::{magic_value_comparison, MagicValueComparison}; -pub use manual_import_from::{manual_from_import, ManualFromImport}; -pub use nested_min_max::{nested_min_max, NestedMinMax}; -pub use nonlocal_without_binding::NonlocalWithoutBinding; -pub use property_with_parameters::{property_with_parameters, PropertyWithParameters}; -pub use redefined_loop_name::{redefined_loop_name, RedefinedLoopName}; -pub use repeated_isinstance_calls::{repeated_isinstance_calls, RepeatedIsinstanceCalls}; -pub use return_in_init::{return_in_init, ReturnInInit}; -pub use sys_exit_alias::{sys_exit_alias, SysExitAlias}; -pub use too_many_arguments::{too_many_arguments, TooManyArguments}; -pub use too_many_branches::{too_many_branches, TooManyBranches}; -pub use too_many_return_statements::{too_many_return_statements, TooManyReturnStatements}; -pub use too_many_statements::{too_many_statements, TooManyStatements}; -pub use unexpected_special_method_signature::{ +pub(crate) use logging::{logging_call, LoggingTooFewArgs, LoggingTooManyArgs}; +pub(crate) use magic_value_comparison::{magic_value_comparison, MagicValueComparison}; +pub(crate) use manual_import_from::{manual_from_import, ManualFromImport}; +pub(crate) use nested_min_max::{nested_min_max, NestedMinMax}; +pub(crate) use nonlocal_without_binding::NonlocalWithoutBinding; +pub(crate) use property_with_parameters::{property_with_parameters, PropertyWithParameters}; +pub(crate) use redefined_loop_name::{redefined_loop_name, RedefinedLoopName}; +pub(crate) use repeated_isinstance_calls::{repeated_isinstance_calls, RepeatedIsinstanceCalls}; +pub(crate) use return_in_init::{return_in_init, ReturnInInit}; +pub(crate) use sys_exit_alias::{sys_exit_alias, SysExitAlias}; +pub(crate) use too_many_arguments::{too_many_arguments, TooManyArguments}; +pub(crate) use too_many_branches::{too_many_branches, TooManyBranches}; +pub(crate) use too_many_return_statements::{too_many_return_statements, TooManyReturnStatements}; +pub(crate) use too_many_statements::{too_many_statements, TooManyStatements}; +pub(crate) use unexpected_special_method_signature::{ unexpected_special_method_signature, UnexpectedSpecialMethodSignature, }; -pub use unnecessary_direct_lambda_call::{ +pub(crate) use unnecessary_direct_lambda_call::{ unnecessary_direct_lambda_call, UnnecessaryDirectLambdaCall, }; -pub use useless_else_on_loop::{useless_else_on_loop, UselessElseOnLoop}; -pub use useless_import_alias::{useless_import_alias, UselessImportAlias}; -pub use useless_return::{useless_return, UselessReturn}; -pub use yield_in_init::{yield_in_init, YieldInInit}; +pub(crate) use useless_else_on_loop::{useless_else_on_loop, UselessElseOnLoop}; +pub(crate) use useless_import_alias::{useless_import_alias, UselessImportAlias}; +pub(crate) use useless_return::{useless_return, UselessReturn}; +pub(crate) use yield_in_init::{yield_in_init, YieldInInit}; mod assert_on_string_literal; mod await_outside_async; diff --git a/crates/ruff/src/rules/pylint/rules/nested_min_max.rs b/crates/ruff/src/rules/pylint/rules/nested_min_max.rs index f8e596b75a..ab9988a6fd 100644 --- a/crates/ruff/src/rules/pylint/rules/nested_min_max.rs +++ b/crates/ruff/src/rules/pylint/rules/nested_min_max.rs @@ -9,7 +9,7 @@ use ruff_python_semantic::context::Context; use crate::{checkers::ast::Checker, registry::AsRule}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum MinMax { +pub(crate) enum MinMax { Min, Max, } @@ -87,7 +87,7 @@ fn collect_nested_args(context: &Context, min_max: MinMax, args: &[Expr]) -> Vec } /// W3301 -pub fn nested_min_max( +pub(crate) fn nested_min_max( checker: &mut Checker, expr: &Expr, func: &Expr, diff --git a/crates/ruff/src/rules/pylint/rules/property_with_parameters.rs b/crates/ruff/src/rules/pylint/rules/property_with_parameters.rs index 93496c0c73..22431feebe 100644 --- a/crates/ruff/src/rules/pylint/rules/property_with_parameters.rs +++ b/crates/ruff/src/rules/pylint/rules/property_with_parameters.rs @@ -17,7 +17,7 @@ impl Violation for PropertyWithParameters { } /// PLR0206 -pub fn property_with_parameters( +pub(crate) fn property_with_parameters( checker: &mut Checker, stmt: &Stmt, decorator_list: &[Expr], diff --git a/crates/ruff/src/rules/pylint/rules/redefined_loop_name.rs b/crates/ruff/src/rules/pylint/rules/redefined_loop_name.rs index 72d4099e89..333e186536 100644 --- a/crates/ruff/src/rules/pylint/rules/redefined_loop_name.rs +++ b/crates/ruff/src/rules/pylint/rules/redefined_loop_name.rs @@ -14,7 +14,7 @@ use ruff_python_semantic::context::Context; use crate::checkers::ast::Checker; #[derive(Debug, PartialEq, Eq, Clone, Copy)] -pub enum OuterBindingKind { +pub(crate) enum OuterBindingKind { For, With, } @@ -29,7 +29,7 @@ impl fmt::Display for OuterBindingKind { } #[derive(Debug, PartialEq, Eq, Clone, Copy)] -pub enum InnerBindingKind { +pub(crate) enum InnerBindingKind { For, With, Assignment, @@ -332,7 +332,7 @@ fn assignment_targets_from_assign_targets<'a, U>( } /// PLW2901 -pub fn redefined_loop_name<'a, 'b>(checker: &'a mut Checker<'b>, node: &Node<'b>) { +pub(crate) fn redefined_loop_name<'a, 'b>(checker: &'a mut Checker<'b>, node: &Node<'b>) { let (outer_assignment_targets, inner_assignment_targets) = match node { Node::Stmt(stmt) => match &stmt.node { // With. diff --git a/crates/ruff/src/rules/pylint/rules/repeated_isinstance_calls.rs b/crates/ruff/src/rules/pylint/rules/repeated_isinstance_calls.rs index 73779f10ff..3799d4255c 100644 --- a/crates/ruff/src/rules/pylint/rules/repeated_isinstance_calls.rs +++ b/crates/ruff/src/rules/pylint/rules/repeated_isinstance_calls.rs @@ -25,7 +25,12 @@ impl Violation for RepeatedIsinstanceCalls { } /// PLR1701 -pub fn repeated_isinstance_calls(checker: &mut Checker, expr: &Expr, op: &Boolop, values: &[Expr]) { +pub(crate) fn repeated_isinstance_calls( + checker: &mut Checker, + expr: &Expr, + op: &Boolop, + values: &[Expr], +) { if !matches!(op, Boolop::Or) || !checker.ctx.is_builtin("isinstance") { return; } diff --git a/crates/ruff/src/rules/pylint/rules/return_in_init.rs b/crates/ruff/src/rules/pylint/rules/return_in_init.rs index 98f620ed9e..e40b7db8e4 100644 --- a/crates/ruff/src/rules/pylint/rules/return_in_init.rs +++ b/crates/ruff/src/rules/pylint/rules/return_in_init.rs @@ -43,7 +43,7 @@ impl Violation for ReturnInInit { } /// PLE0101 -pub fn return_in_init(checker: &mut Checker, stmt: &Stmt) { +pub(crate) fn return_in_init(checker: &mut Checker, stmt: &Stmt) { if let StmtKind::Return(ast::StmtReturn { value }) = &stmt.node { if let Some(expr) = value { if matches!( diff --git a/crates/ruff/src/rules/pylint/rules/sys_exit_alias.rs b/crates/ruff/src/rules/pylint/rules/sys_exit_alias.rs index 0984da585e..1ff6dc1d12 100644 --- a/crates/ruff/src/rules/pylint/rules/sys_exit_alias.rs +++ b/crates/ruff/src/rules/pylint/rules/sys_exit_alias.rs @@ -28,7 +28,7 @@ impl Violation for SysExitAlias { } /// PLR1722 -pub fn sys_exit_alias(checker: &mut Checker, func: &Expr) { +pub(crate) fn sys_exit_alias(checker: &mut Checker, func: &Expr) { let ExprKind::Name(ast::ExprName { id, .. }) = &func.node else { return; }; diff --git a/crates/ruff/src/rules/pylint/rules/too_many_arguments.rs b/crates/ruff/src/rules/pylint/rules/too_many_arguments.rs index 8a4a15a266..cf201ec220 100644 --- a/crates/ruff/src/rules/pylint/rules/too_many_arguments.rs +++ b/crates/ruff/src/rules/pylint/rules/too_many_arguments.rs @@ -21,7 +21,7 @@ impl Violation for TooManyArguments { } /// PLR0913 -pub fn too_many_arguments(checker: &mut Checker, args: &Arguments, stmt: &Stmt) { +pub(crate) fn too_many_arguments(checker: &mut Checker, args: &Arguments, stmt: &Stmt) { let num_args = args .args .iter() diff --git a/crates/ruff/src/rules/pylint/rules/too_many_branches.rs b/crates/ruff/src/rules/pylint/rules/too_many_branches.rs index 2854eb2247..e2532b6258 100644 --- a/crates/ruff/src/rules/pylint/rules/too_many_branches.rs +++ b/crates/ruff/src/rules/pylint/rules/too_many_branches.rs @@ -96,7 +96,7 @@ fn num_branches(stmts: &[Stmt]) -> usize { } /// PLR0912 -pub fn too_many_branches( +pub(crate) fn too_many_branches( stmt: &Stmt, body: &[Stmt], max_branches: usize, diff --git a/crates/ruff/src/rules/pylint/rules/too_many_return_statements.rs b/crates/ruff/src/rules/pylint/rules/too_many_return_statements.rs index 5b6d43dd2b..bdb59212dd 100644 --- a/crates/ruff/src/rules/pylint/rules/too_many_return_statements.rs +++ b/crates/ruff/src/rules/pylint/rules/too_many_return_statements.rs @@ -31,7 +31,7 @@ fn num_returns(body: &[Stmt]) -> usize { } /// PLR0911 -pub fn too_many_return_statements( +pub(crate) fn too_many_return_statements( stmt: &Stmt, body: &[Stmt], max_returns: usize, diff --git a/crates/ruff/src/rules/pylint/rules/too_many_statements.rs b/crates/ruff/src/rules/pylint/rules/too_many_statements.rs index bde1847404..774a692875 100644 --- a/crates/ruff/src/rules/pylint/rules/too_many_statements.rs +++ b/crates/ruff/src/rules/pylint/rules/too_many_statements.rs @@ -103,7 +103,7 @@ fn num_statements(stmts: &[Stmt]) -> usize { } /// PLR0915 -pub fn too_many_statements( +pub(crate) fn too_many_statements( stmt: &Stmt, body: &[Stmt], max_statements: usize, diff --git a/crates/ruff/src/rules/pylint/rules/unexpected_special_method_signature.rs b/crates/ruff/src/rules/pylint/rules/unexpected_special_method_signature.rs index 078def1def..200f568689 100644 --- a/crates/ruff/src/rules/pylint/rules/unexpected_special_method_signature.rs +++ b/crates/ruff/src/rules/pylint/rules/unexpected_special_method_signature.rs @@ -11,7 +11,7 @@ use ruff_python_semantic::analyze::visibility::is_staticmethod; use crate::checkers::ast::Checker; #[derive(Debug, Eq, PartialEq)] -pub enum ExpectedParams { +pub(crate) enum ExpectedParams { Fixed(usize), Range(usize, usize), } @@ -100,7 +100,7 @@ impl Violation for UnexpectedSpecialMethodSignature { } /// PLE0302 -pub fn unexpected_special_method_signature( +pub(crate) fn unexpected_special_method_signature( checker: &mut Checker, stmt: &Stmt, name: &str, diff --git a/crates/ruff/src/rules/pylint/rules/unnecessary_direct_lambda_call.rs b/crates/ruff/src/rules/pylint/rules/unnecessary_direct_lambda_call.rs index fffc3c3cf6..6306c6e24b 100644 --- a/crates/ruff/src/rules/pylint/rules/unnecessary_direct_lambda_call.rs +++ b/crates/ruff/src/rules/pylint/rules/unnecessary_direct_lambda_call.rs @@ -35,7 +35,7 @@ impl Violation for UnnecessaryDirectLambdaCall { } /// PLC3002 -pub fn unnecessary_direct_lambda_call(checker: &mut Checker, expr: &Expr, func: &Expr) { +pub(crate) fn unnecessary_direct_lambda_call(checker: &mut Checker, expr: &Expr, func: &Expr) { if let ExprKind::Lambda(_) = &func.node { checker .diagnostics diff --git a/crates/ruff/src/rules/pylint/rules/useless_else_on_loop.rs b/crates/ruff/src/rules/pylint/rules/useless_else_on_loop.rs index 9608d15e5e..78163fb21c 100644 --- a/crates/ruff/src/rules/pylint/rules/useless_else_on_loop.rs +++ b/crates/ruff/src/rules/pylint/rules/useless_else_on_loop.rs @@ -60,7 +60,12 @@ fn loop_exits_early(body: &[Stmt]) -> bool { } /// PLW0120 -pub fn useless_else_on_loop(checker: &mut Checker, stmt: &Stmt, body: &[Stmt], orelse: &[Stmt]) { +pub(crate) fn useless_else_on_loop( + checker: &mut Checker, + stmt: &Stmt, + body: &[Stmt], + orelse: &[Stmt], +) { if !orelse.is_empty() && !loop_exits_early(body) { checker.diagnostics.push(Diagnostic::new( UselessElseOnLoop, diff --git a/crates/ruff/src/rules/pylint/rules/useless_import_alias.rs b/crates/ruff/src/rules/pylint/rules/useless_import_alias.rs index d2f4aeacc0..acf1e28449 100644 --- a/crates/ruff/src/rules/pylint/rules/useless_import_alias.rs +++ b/crates/ruff/src/rules/pylint/rules/useless_import_alias.rs @@ -36,7 +36,7 @@ impl AlwaysAutofixableViolation for UselessImportAlias { } /// PLC0414 -pub fn useless_import_alias(checker: &mut Checker, alias: &Alias) { +pub(crate) fn useless_import_alias(checker: &mut Checker, alias: &Alias) { let Some(asname) = &alias.node.asname else { return; }; diff --git a/crates/ruff/src/rules/pylint/rules/useless_return.rs b/crates/ruff/src/rules/pylint/rules/useless_return.rs index 1ccf8c3fa8..704ab701e9 100644 --- a/crates/ruff/src/rules/pylint/rules/useless_return.rs +++ b/crates/ruff/src/rules/pylint/rules/useless_return.rs @@ -46,7 +46,7 @@ impl AlwaysAutofixableViolation for UselessReturn { } /// PLR1711 -pub fn useless_return<'a>( +pub(crate) fn useless_return<'a>( checker: &mut Checker<'a>, stmt: &'a Stmt, body: &'a [Stmt], diff --git a/crates/ruff/src/rules/pylint/rules/yield_in_init.rs b/crates/ruff/src/rules/pylint/rules/yield_in_init.rs index cee9a9cffd..00cb177a02 100644 --- a/crates/ruff/src/rules/pylint/rules/yield_in_init.rs +++ b/crates/ruff/src/rules/pylint/rules/yield_in_init.rs @@ -38,7 +38,7 @@ impl Violation for YieldInInit { } /// PLE0100 -pub fn yield_in_init(checker: &mut Checker, expr: &Expr) { +pub(crate) fn yield_in_init(checker: &mut Checker, expr: &Expr) { if in_dunder_init(checker) { checker .diagnostics diff --git a/crates/ruff/src/rules/pyupgrade/fixes.rs b/crates/ruff/src/rules/pyupgrade/fixes.rs index baf259423c..0bc8a66e41 100644 --- a/crates/ruff/src/rules/pyupgrade/fixes.rs +++ b/crates/ruff/src/rules/pyupgrade/fixes.rs @@ -13,7 +13,7 @@ use ruff_python_ast::source_code::{Locator, Stylist}; use crate::cst::matchers::match_module; /// Safely adjust the indentation of the indented block at [`TextRange`]. -pub fn adjust_indentation( +pub(crate) fn adjust_indentation( range: TextRange, indentation: &str, locator: &Locator, @@ -50,7 +50,11 @@ pub fn adjust_indentation( } /// Generate a fix to remove arguments from a `super` call. -pub fn remove_super_arguments(locator: &Locator, stylist: &Stylist, expr: &Expr) -> Option { +pub(crate) fn remove_super_arguments( + locator: &Locator, + stylist: &Stylist, + expr: &Expr, +) -> Option { let range = expr.range(); let contents = locator.slice(range); @@ -81,7 +85,7 @@ pub fn remove_super_arguments(locator: &Locator, stylist: &Stylist, expr: &Expr) } /// Remove any imports matching `members` from an import-from statement. -pub fn remove_import_members(contents: &str, members: &[&str]) -> String { +pub(crate) fn remove_import_members(contents: &str, members: &[&str]) -> String { let mut names: Vec = vec![]; let mut commas: Vec = vec![]; let mut removal_indices: Vec = vec![]; diff --git a/crates/ruff/src/rules/pyupgrade/helpers.rs b/crates/ruff/src/rules/pyupgrade/helpers.rs index 6d3cfa8dbb..b035b2b1e6 100644 --- a/crates/ruff/src/rules/pyupgrade/helpers.rs +++ b/crates/ruff/src/rules/pyupgrade/helpers.rs @@ -3,7 +3,7 @@ use regex::{Captures, Regex}; static CURLY_BRACES: Lazy = Lazy::new(|| Regex::new(r"(\\N\{[^}]+})|([{}])").unwrap()); -pub fn curly_escape(text: &str) -> String { +pub(crate) fn curly_escape(text: &str) -> String { // Match all curly braces. This will include named unicode escapes (like // \N{SNOWMAN}), which we _don't_ want to escape, so take care to preserve them. CURLY_BRACES diff --git a/crates/ruff/src/rules/pyupgrade/rules/convert_named_tuple_functional_to_class.rs b/crates/ruff/src/rules/pyupgrade/rules/convert_named_tuple_functional_to_class.rs index 8917829df3..177a200cda 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/convert_named_tuple_functional_to_class.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/convert_named_tuple_functional_to_class.rs @@ -171,7 +171,7 @@ fn convert_to_class( } /// UP014 -pub fn convert_named_tuple_functional_to_class( +pub(crate) fn convert_named_tuple_functional_to_class( checker: &mut Checker, stmt: &Stmt, targets: &[Expr], diff --git a/crates/ruff/src/rules/pyupgrade/rules/convert_typed_dict_functional_to_class.rs b/crates/ruff/src/rules/pyupgrade/rules/convert_typed_dict_functional_to_class.rs index af28ea9c87..cb43b134c3 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/convert_typed_dict_functional_to_class.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/convert_typed_dict_functional_to_class.rs @@ -221,7 +221,7 @@ fn convert_to_class( } /// UP013 -pub fn convert_typed_dict_functional_to_class( +pub(crate) fn convert_typed_dict_functional_to_class( checker: &mut Checker, stmt: &Stmt, targets: &[Expr], diff --git a/crates/ruff/src/rules/pyupgrade/rules/datetime_utc_alias.rs b/crates/ruff/src/rules/pyupgrade/rules/datetime_utc_alias.rs index 5afe1081d2..02008f3bac 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/datetime_utc_alias.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/datetime_utc_alias.rs @@ -26,7 +26,7 @@ impl Violation for DatetimeTimezoneUTC { } /// UP017 -pub fn datetime_utc_alias(checker: &mut Checker, expr: &Expr) { +pub(crate) fn datetime_utc_alias(checker: &mut Checker, expr: &Expr) { if checker .ctx .resolve_call_path(expr) diff --git a/crates/ruff/src/rules/pyupgrade/rules/deprecated_c_element_tree.rs b/crates/ruff/src/rules/pyupgrade/rules/deprecated_c_element_tree.rs index 68b9f8579e..69ced4a0ac 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/deprecated_c_element_tree.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/deprecated_c_element_tree.rs @@ -34,7 +34,7 @@ fn add_check_for_node(checker: &mut Checker, node: &Attributed) { } /// UP023 -pub fn deprecated_c_element_tree(checker: &mut Checker, stmt: &Stmt) { +pub(crate) fn deprecated_c_element_tree(checker: &mut Checker, stmt: &Stmt) { match &stmt.node { StmtKind::Import(ast::StmtImport { names }) => { // Ex) `import xml.etree.cElementTree as ET` diff --git a/crates/ruff/src/rules/pyupgrade/rules/deprecated_import.rs b/crates/ruff/src/rules/pyupgrade/rules/deprecated_import.rs index 147c1ce405..b163f4d857 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/deprecated_import.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/deprecated_import.rs @@ -505,7 +505,7 @@ impl<'a> ImportReplacer<'a> { } /// UP035 -pub fn deprecated_import( +pub(crate) fn deprecated_import( checker: &mut Checker, stmt: &Stmt, names: &[Alias], diff --git a/crates/ruff/src/rules/pyupgrade/rules/deprecated_mock_import.rs b/crates/ruff/src/rules/pyupgrade/rules/deprecated_mock_import.rs index 70c8617572..f67824d0cf 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/deprecated_mock_import.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/deprecated_mock_import.rs @@ -17,7 +17,7 @@ use crate::cst::matchers::{match_import, match_import_from, match_module}; use crate::registry::{AsRule, Rule}; #[derive(Debug, PartialEq, Eq, Copy, Clone)] -pub enum MockReference { +pub(crate) enum MockReference { Import, Attribute, } @@ -245,7 +245,7 @@ fn format_import_from( } /// UP026 -pub fn deprecated_mock_attribute(checker: &mut Checker, expr: &Expr) { +pub(crate) fn deprecated_mock_attribute(checker: &mut Checker, expr: &Expr) { if let ExprKind::Attribute(ast::ExprAttribute { value, .. }) = &expr.node { if collect_call_path(value) .map_or(false, |call_path| call_path.as_slice() == ["mock", "mock"]) @@ -269,7 +269,7 @@ pub fn deprecated_mock_attribute(checker: &mut Checker, expr: &Expr) { } /// UP026 -pub fn deprecated_mock_import(checker: &mut Checker, stmt: &Stmt) { +pub(crate) fn deprecated_mock_import(checker: &mut Checker, stmt: &Stmt) { match &stmt.node { StmtKind::Import(ast::StmtImport { names }) => { // Find all `mock` imports. diff --git a/crates/ruff/src/rules/pyupgrade/rules/deprecated_unittest_alias.rs b/crates/ruff/src/rules/pyupgrade/rules/deprecated_unittest_alias.rs index dd5c9978ac..a61b790b57 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/deprecated_unittest_alias.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/deprecated_unittest_alias.rs @@ -48,7 +48,7 @@ static DEPRECATED_ALIASES: Lazy> = Lazy::n }); /// UP005 -pub fn deprecated_unittest_alias(checker: &mut Checker, expr: &Expr) { +pub(crate) fn deprecated_unittest_alias(checker: &mut Checker, expr: &Expr) { let ExprKind::Attribute(ast::ExprAttribute { value, attr, .. }) = &expr.node else { return; }; diff --git a/crates/ruff/src/rules/pyupgrade/rules/extraneous_parentheses.rs b/crates/ruff/src/rules/pyupgrade/rules/extraneous_parentheses.rs index b3a6300dee..701846502d 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/extraneous_parentheses.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/extraneous_parentheses.rs @@ -117,7 +117,7 @@ fn match_extraneous_parentheses(tokens: &[LexResult], mut i: usize) -> Option<(u } /// UP034 -pub fn extraneous_parentheses( +pub(crate) fn extraneous_parentheses( tokens: &[LexResult], locator: &Locator, settings: &Settings, diff --git a/crates/ruff/src/rules/pyupgrade/rules/lru_cache_with_maxsize_none.rs b/crates/ruff/src/rules/pyupgrade/rules/lru_cache_with_maxsize_none.rs index 18405c6846..8e435e35f8 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/lru_cache_with_maxsize_none.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/lru_cache_with_maxsize_none.rs @@ -23,7 +23,7 @@ impl AlwaysAutofixableViolation for LRUCacheWithMaxsizeNone { } /// UP033 -pub fn lru_cache_with_maxsize_none(checker: &mut Checker, decorator_list: &[Expr]) { +pub(crate) fn lru_cache_with_maxsize_none(checker: &mut Checker, decorator_list: &[Expr]) { for expr in decorator_list.iter() { let ExprKind::Call(ast::ExprCall { func, diff --git a/crates/ruff/src/rules/pyupgrade/rules/lru_cache_without_parameters.rs b/crates/ruff/src/rules/pyupgrade/rules/lru_cache_without_parameters.rs index 1144859acf..dbb07e5607 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/lru_cache_without_parameters.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/lru_cache_without_parameters.rs @@ -23,7 +23,7 @@ impl AlwaysAutofixableViolation for LRUCacheWithoutParameters { } /// UP011 -pub fn lru_cache_without_parameters(checker: &mut Checker, decorator_list: &[Expr]) { +pub(crate) fn lru_cache_without_parameters(checker: &mut Checker, decorator_list: &[Expr]) { for expr in decorator_list.iter() { let ExprKind::Call(ast::ExprCall { func, diff --git a/crates/ruff/src/rules/pyupgrade/rules/native_literals.rs b/crates/ruff/src/rules/pyupgrade/rules/native_literals.rs index 57d844e758..a44324c148 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/native_literals.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/native_literals.rs @@ -10,7 +10,7 @@ use crate::checkers::ast::Checker; use crate::registry::AsRule; #[derive(Debug, PartialEq, Eq, Copy, Clone)] -pub enum LiteralType { +pub(crate) enum LiteralType { Str, Bytes, } @@ -43,7 +43,7 @@ impl AlwaysAutofixableViolation for NativeLiterals { } /// UP018 -pub fn native_literals( +pub(crate) fn native_literals( checker: &mut Checker, expr: &Expr, func: &Expr, diff --git a/crates/ruff/src/rules/pyupgrade/rules/open_alias.rs b/crates/ruff/src/rules/pyupgrade/rules/open_alias.rs index 21f697501c..d12941f087 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/open_alias.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/open_alias.rs @@ -23,7 +23,7 @@ impl Violation for OpenAlias { } /// UP020 -pub fn open_alias(checker: &mut Checker, expr: &Expr, func: &Expr) { +pub(crate) fn open_alias(checker: &mut Checker, expr: &Expr, func: &Expr) { if checker .ctx .resolve_call_path(func) diff --git a/crates/ruff/src/rules/pyupgrade/rules/os_error_alias.rs b/crates/ruff/src/rules/pyupgrade/rules/os_error_alias.rs index 2034bec781..c6c6f6a152 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/os_error_alias.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/os_error_alias.rs @@ -130,7 +130,7 @@ fn tuple_diagnostic(checker: &mut Checker, target: &Expr, aliases: &[&Expr]) { } /// UP024 -pub fn os_error_alias_handlers(checker: &mut Checker, handlers: &[Excepthandler]) { +pub(crate) fn os_error_alias_handlers(checker: &mut Checker, handlers: &[Excepthandler]) { for handler in handlers { let ExcepthandlerKind::ExceptHandler(ast::ExcepthandlerExceptHandler { type_, .. }) = &handler.node; @@ -161,14 +161,14 @@ pub fn os_error_alias_handlers(checker: &mut Checker, handlers: &[Excepthandler] } /// UP024 -pub fn os_error_alias_call(checker: &mut Checker, func: &Expr) { +pub(crate) fn os_error_alias_call(checker: &mut Checker, func: &Expr) { if is_alias(&checker.ctx, func) { atom_diagnostic(checker, func); } } /// UP024 -pub fn os_error_alias_raise(checker: &mut Checker, expr: &Expr) { +pub(crate) fn os_error_alias_raise(checker: &mut Checker, expr: &Expr) { if matches!(expr.node, ExprKind::Name(_) | ExprKind::Attribute(_)) { if is_alias(&checker.ctx, expr) { atom_diagnostic(checker, expr); diff --git a/crates/ruff/src/rules/pyupgrade/rules/outdated_version_block.rs b/crates/ruff/src/rules/pyupgrade/rules/outdated_version_block.rs index 200b532fef..bc3451964e 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/outdated_version_block.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/outdated_version_block.rs @@ -303,7 +303,7 @@ fn fix_py3_block( } /// UP036 -pub fn outdated_version_block( +pub(crate) fn outdated_version_block( checker: &mut Checker, stmt: &Stmt, test: &Expr, diff --git a/crates/ruff/src/rules/pyupgrade/rules/quoted_annotation.rs b/crates/ruff/src/rules/pyupgrade/rules/quoted_annotation.rs index 5f5f29422b..967abefee0 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/quoted_annotation.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/quoted_annotation.rs @@ -20,7 +20,7 @@ impl AlwaysAutofixableViolation for QuotedAnnotation { } /// UP037 -pub fn quoted_annotation(checker: &mut Checker, annotation: &str, range: TextRange) { +pub(crate) fn quoted_annotation(checker: &mut Checker, annotation: &str, range: TextRange) { let mut diagnostic = Diagnostic::new(QuotedAnnotation, range); if checker.patch(Rule::QuotedAnnotation) { #[allow(deprecated)] diff --git a/crates/ruff/src/rules/pyupgrade/rules/redundant_open_modes.rs b/crates/ruff/src/rules/pyupgrade/rules/redundant_open_modes.rs index 796ade1ed8..bcc04e3aa3 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/redundant_open_modes.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/redundant_open_modes.rs @@ -170,7 +170,7 @@ fn create_remove_param_fix(locator: &Locator, expr: &Expr, mode_param: &Expr) -> } /// UP015 -pub fn redundant_open_modes(checker: &mut Checker, expr: &Expr) { +pub(crate) fn redundant_open_modes(checker: &mut Checker, expr: &Expr) { // If `open` has been rebound, skip this check entirely. if !checker.ctx.is_builtin(OPEN_FUNC_NAME) { return; diff --git a/crates/ruff/src/rules/pyupgrade/rules/replace_stdout_stderr.rs b/crates/ruff/src/rules/pyupgrade/rules/replace_stdout_stderr.rs index 88069dc908..3a5c4a737c 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/replace_stdout_stderr.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/replace_stdout_stderr.rs @@ -53,7 +53,7 @@ fn generate_fix( } /// UP022 -pub fn replace_stdout_stderr( +pub(crate) fn replace_stdout_stderr( checker: &mut Checker, expr: &Expr, func: &Expr, diff --git a/crates/ruff/src/rules/pyupgrade/rules/replace_universal_newlines.rs b/crates/ruff/src/rules/pyupgrade/rules/replace_universal_newlines.rs index 2a050167ce..3fe0913a83 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/replace_universal_newlines.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/replace_universal_newlines.rs @@ -23,7 +23,7 @@ impl AlwaysAutofixableViolation for ReplaceUniversalNewlines { } /// UP021 -pub fn replace_universal_newlines(checker: &mut Checker, func: &Expr, kwargs: &[Keyword]) { +pub(crate) fn replace_universal_newlines(checker: &mut Checker, func: &Expr, kwargs: &[Keyword]) { if checker .ctx .resolve_call_path(func) diff --git a/crates/ruff/src/rules/pyupgrade/rules/super_call_with_parameters.rs b/crates/ruff/src/rules/pyupgrade/rules/super_call_with_parameters.rs index 5eea2ed6e5..907b792300 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/super_call_with_parameters.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/super_call_with_parameters.rs @@ -32,7 +32,12 @@ fn is_super_call_with_arguments(func: &Expr, args: &[Expr]) -> bool { } /// UP008 -pub fn super_call_with_parameters(checker: &mut Checker, expr: &Expr, func: &Expr, args: &[Expr]) { +pub(crate) fn super_call_with_parameters( + checker: &mut Checker, + expr: &Expr, + func: &Expr, + args: &[Expr], +) { // Only bother going through the super check at all if we're in a `super` call. // (We check this in `super_args` too, so this is just an optimization.) if !is_super_call_with_arguments(func, args) { diff --git a/crates/ruff/src/rules/pyupgrade/rules/type_of_primitive.rs b/crates/ruff/src/rules/pyupgrade/rules/type_of_primitive.rs index c593a3f3d3..25601270d1 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/type_of_primitive.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/type_of_primitive.rs @@ -27,7 +27,7 @@ impl AlwaysAutofixableViolation for TypeOfPrimitive { } /// UP003 -pub fn type_of_primitive(checker: &mut Checker, expr: &Expr, func: &Expr, args: &[Expr]) { +pub(crate) fn type_of_primitive(checker: &mut Checker, expr: &Expr, func: &Expr, args: &[Expr]) { if args.len() != 1 { return; } diff --git a/crates/ruff/src/rules/pyupgrade/rules/typing_text_str_alias.rs b/crates/ruff/src/rules/pyupgrade/rules/typing_text_str_alias.rs index bd8b49fdc9..1f47507aab 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/typing_text_str_alias.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/typing_text_str_alias.rs @@ -21,7 +21,7 @@ impl AlwaysAutofixableViolation for TypingTextStrAlias { } /// UP019 -pub fn typing_text_str_alias(checker: &mut Checker, expr: &Expr) { +pub(crate) fn typing_text_str_alias(checker: &mut Checker, expr: &Expr) { if checker .ctx .resolve_call_path(expr) diff --git a/crates/ruff/src/rules/pyupgrade/rules/unicode_kind_prefix.rs b/crates/ruff/src/rules/pyupgrade/rules/unicode_kind_prefix.rs index 258072053b..4d14c743b3 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/unicode_kind_prefix.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/unicode_kind_prefix.rs @@ -22,7 +22,7 @@ impl AlwaysAutofixableViolation for UnicodeKindPrefix { } /// UP025 -pub fn unicode_kind_prefix(checker: &mut Checker, expr: &Expr, kind: Option<&str>) { +pub(crate) fn unicode_kind_prefix(checker: &mut Checker, expr: &Expr, kind: Option<&str>) { if let Some(const_kind) = kind { if const_kind.to_lowercase() == "u" { let mut diagnostic = Diagnostic::new(UnicodeKindPrefix, expr.range()); diff --git a/crates/ruff/src/rules/pyupgrade/rules/unnecessary_builtin_import.rs b/crates/ruff/src/rules/pyupgrade/rules/unnecessary_builtin_import.rs index a945469e18..6c2f1af90d 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/unnecessary_builtin_import.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/unnecessary_builtin_import.rs @@ -65,7 +65,7 @@ const SIX: &[&str] = &["callable", "next"]; const SIX_MOVES: &[&str] = &["filter", "input", "map", "range", "zip"]; /// UP029 -pub fn unnecessary_builtin_import( +pub(crate) fn unnecessary_builtin_import( checker: &mut Checker, stmt: &Stmt, module: &str, diff --git a/crates/ruff/src/rules/pyupgrade/rules/unnecessary_encode_utf8.rs b/crates/ruff/src/rules/pyupgrade/rules/unnecessary_encode_utf8.rs index bf36be59c0..d777504ec1 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/unnecessary_encode_utf8.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/unnecessary_encode_utf8.rs @@ -11,7 +11,7 @@ use crate::checkers::ast::Checker; use crate::registry::Rule; #[derive(Debug, PartialEq, Eq)] -pub enum Reason { +pub(crate) enum Reason { BytesLiteral, DefaultArgument, } @@ -134,7 +134,7 @@ fn replace_with_bytes_literal(locator: &Locator, expr: &Expr) -> Fix { } /// UP012 -pub fn unnecessary_encode_utf8( +pub(crate) fn unnecessary_encode_utf8( checker: &mut Checker, expr: &Expr, func: &Expr, diff --git a/crates/ruff/src/rules/pyupgrade/rules/unnecessary_future_import.rs b/crates/ruff/src/rules/pyupgrade/rules/unnecessary_future_import.rs index 3fca159635..2915abc688 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/unnecessary_future_import.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/unnecessary_future_import.rs @@ -57,7 +57,7 @@ const PY37_PLUS_REMOVE_FUTURES: &[&str] = &[ ]; /// UP010 -pub fn unnecessary_future_import( +pub(crate) fn unnecessary_future_import( checker: &mut Checker, stmt: &Stmt, names: &[Attributed], diff --git a/crates/ruff/src/rules/pyupgrade/rules/unpacked_list_comprehension.rs b/crates/ruff/src/rules/pyupgrade/rules/unpacked_list_comprehension.rs index b86ebe8253..99df775412 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/unpacked_list_comprehension.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/unpacked_list_comprehension.rs @@ -93,7 +93,7 @@ fn contains_await(expr: &Expr) -> bool { } /// UP027 -pub fn unpacked_list_comprehension(checker: &mut Checker, targets: &[Expr], value: &Expr) { +pub(crate) fn unpacked_list_comprehension(checker: &mut Checker, targets: &[Expr], value: &Expr) { let Some(target) = targets.get(0) else { return; }; diff --git a/crates/ruff/src/rules/pyupgrade/rules/use_pep585_annotation.rs b/crates/ruff/src/rules/pyupgrade/rules/use_pep585_annotation.rs index 6d7fe89729..43b83f0cff 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/use_pep585_annotation.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/use_pep585_annotation.rs @@ -32,7 +32,7 @@ impl Violation for NonPEP585Annotation { } /// UP006 -pub fn use_pep585_annotation(checker: &mut Checker, expr: &Expr) { +pub(crate) fn use_pep585_annotation(checker: &mut Checker, expr: &Expr) { if let Some(binding) = checker .ctx .resolve_call_path(expr) diff --git a/crates/ruff/src/rules/pyupgrade/rules/use_pep604_annotation.rs b/crates/ruff/src/rules/pyupgrade/rules/use_pep604_annotation.rs index 3c94ee816d..5f8c4ad3dc 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/use_pep604_annotation.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/use_pep604_annotation.rs @@ -76,7 +76,12 @@ enum TypingMember { } /// UP007 -pub fn use_pep604_annotation(checker: &mut Checker, expr: &Expr, value: &Expr, slice: &Expr) { +pub(crate) fn use_pep604_annotation( + checker: &mut Checker, + expr: &Expr, + value: &Expr, + slice: &Expr, +) { // If any of the _arguments_ are forward references, we can't use PEP 604. // Ex) `Union["str", "int"]` can't be converted to `"str" | "int"`. if any_arg_is_str(slice) { diff --git a/crates/ruff/src/rules/pyupgrade/rules/use_pep604_isinstance.rs b/crates/ruff/src/rules/pyupgrade/rules/use_pep604_isinstance.rs index 881e366194..1950fcfb45 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/use_pep604_isinstance.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/use_pep604_isinstance.rs @@ -11,7 +11,7 @@ use crate::checkers::ast::Checker; use crate::registry::AsRule; #[derive(Debug, PartialEq, Eq, Copy, Clone)] -pub enum CallKind { +pub(crate) enum CallKind { Isinstance, Issubclass, } @@ -26,7 +26,7 @@ impl fmt::Display for CallKind { } impl CallKind { - pub fn from_name(name: &str) -> Option { + pub(crate) fn from_name(name: &str) -> Option { match name { "isinstance" => Some(CallKind::Isinstance), "issubclass" => Some(CallKind::Issubclass), @@ -67,7 +67,12 @@ fn union(elts: &[Expr]) -> Expr { } /// UP038 -pub fn use_pep604_isinstance(checker: &mut Checker, expr: &Expr, func: &Expr, args: &[Expr]) { +pub(crate) fn use_pep604_isinstance( + checker: &mut Checker, + expr: &Expr, + func: &Expr, + args: &[Expr], +) { if let ExprKind::Name(ast::ExprName { id, .. }) = &func.node { let Some(kind) = CallKind::from_name(id) else { return; diff --git a/crates/ruff/src/rules/pyupgrade/rules/useless_metaclass_type.rs b/crates/ruff/src/rules/pyupgrade/rules/useless_metaclass_type.rs index 85f84fe9c2..1167c8f2d7 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/useless_metaclass_type.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/useless_metaclass_type.rs @@ -44,7 +44,12 @@ fn rule(targets: &[Expr], value: &Expr, location: TextRange) -> Option Optio } /// UP004 -pub fn useless_object_inheritance( +pub(crate) fn useless_object_inheritance( checker: &mut Checker, stmt: &Stmt, name: &str, diff --git a/crates/ruff/src/rules/pyupgrade/rules/yield_in_for_loop.rs b/crates/ruff/src/rules/pyupgrade/rules/yield_in_for_loop.rs index aa37f2db70..15d342fe48 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/yield_in_for_loop.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/yield_in_for_loop.rs @@ -139,7 +139,7 @@ impl<'a> Visitor<'a> for ReferenceVisitor<'a> { } /// UP028 -pub fn yield_in_for_loop(checker: &mut Checker, stmt: &Stmt) { +pub(crate) fn yield_in_for_loop(checker: &mut Checker, stmt: &Stmt) { // Intentionally omit async functions. if let StmtKind::FunctionDef(ast::StmtFunctionDef { body, .. }) = &stmt.node { let yields = { diff --git a/crates/ruff/src/rules/pyupgrade/types.rs b/crates/ruff/src/rules/pyupgrade/types.rs index b94c983f21..ab7223aa8e 100644 --- a/crates/ruff/src/rules/pyupgrade/types.rs +++ b/crates/ruff/src/rules/pyupgrade/types.rs @@ -2,7 +2,7 @@ use rustpython_parser::ast::Constant; use serde::{Deserialize, Serialize}; #[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub enum Primitive { +pub(crate) enum Primitive { Bool, Str, Bytes, @@ -12,7 +12,7 @@ pub enum Primitive { } impl Primitive { - pub const fn from_constant(constant: &Constant) -> Option { + pub(crate) const fn from_constant(constant: &Constant) -> Option { match constant { Constant::Bool(_) => Some(Self::Bool), Constant::Str(_) => Some(Self::Str), @@ -24,7 +24,7 @@ impl Primitive { } } - pub fn builtin(self) -> String { + pub(crate) fn builtin(self) -> String { match self { Self::Bool => "bool".to_string(), Self::Str => "str".to_string(), diff --git a/crates/ruff/src/rules/ruff/rules/ambiguous_unicode_character.rs b/crates/ruff/src/rules/ruff/rules/ambiguous_unicode_character.rs index 216eba5bd1..c82fafc0be 100644 --- a/crates/ruff/src/rules/ruff/rules/ambiguous_unicode_character.rs +++ b/crates/ruff/src/rules/ruff/rules/ambiguous_unicode_character.rs @@ -93,7 +93,7 @@ impl AlwaysAutofixableViolation for AmbiguousUnicodeCharacterComment { } } -pub fn ambiguous_unicode_character( +pub(crate) fn ambiguous_unicode_character( locator: &Locator, range: TextRange, context: Context, diff --git a/crates/ruff/src/rules/ruff/rules/asyncio_dangling_task.rs b/crates/ruff/src/rules/ruff/rules/asyncio_dangling_task.rs index b883143a39..b4831a5336 100644 --- a/crates/ruff/src/rules/ruff/rules/asyncio_dangling_task.rs +++ b/crates/ruff/src/rules/ruff/rules/asyncio_dangling_task.rs @@ -63,7 +63,7 @@ impl Violation for AsyncioDanglingTask { } #[derive(Debug, PartialEq, Eq, Copy, Clone)] -pub enum Method { +pub(crate) enum Method { CreateTask, EnsureFuture, } @@ -78,7 +78,10 @@ impl fmt::Display for Method { } /// RUF006 -pub fn asyncio_dangling_task<'a, F>(expr: &'a Expr, resolve_call_path: F) -> Option +pub(crate) fn asyncio_dangling_task<'a, F>( + expr: &'a Expr, + resolve_call_path: F, +) -> Option where F: FnOnce(&'a Expr) -> Option>, { diff --git a/crates/ruff/src/rules/ruff/rules/collection_literal_concatenation.rs b/crates/ruff/src/rules/ruff/rules/collection_literal_concatenation.rs index 9cf3b55fda..9fcd7aec5b 100644 --- a/crates/ruff/src/rules/ruff/rules/collection_literal_concatenation.rs +++ b/crates/ruff/src/rules/ruff/rules/collection_literal_concatenation.rs @@ -54,7 +54,7 @@ enum Kind { /// RUF005 /// This suggestion could be unsafe if the non-literal expression in the /// expression has overridden the `__add__` (or `__radd__`) magic methods. -pub fn collection_literal_concatenation(checker: &mut Checker, expr: &Expr) { +pub(crate) fn collection_literal_concatenation(checker: &mut Checker, expr: &Expr) { let ExprKind::BinOp(ast::ExprBinOp { left, op: Operator::Add, right }) = &expr.node else { return; }; diff --git a/crates/ruff/src/rules/ruff/rules/mod.rs b/crates/ruff/src/rules/ruff/rules/mod.rs index 089bceaaf4..9756e09927 100644 --- a/crates/ruff/src/rules/ruff/rules/mod.rs +++ b/crates/ruff/src/rules/ruff/rules/mod.rs @@ -6,23 +6,23 @@ mod mutable_defaults_in_dataclass_fields; mod pairwise_over_zipped; mod unused_noqa; -pub use ambiguous_unicode_character::{ +pub(crate) use ambiguous_unicode_character::{ ambiguous_unicode_character, AmbiguousUnicodeCharacterComment, AmbiguousUnicodeCharacterDocstring, AmbiguousUnicodeCharacterString, }; -pub use asyncio_dangling_task::{asyncio_dangling_task, AsyncioDanglingTask}; -pub use collection_literal_concatenation::{ +pub(crate) use asyncio_dangling_task::{asyncio_dangling_task, AsyncioDanglingTask}; +pub(crate) use collection_literal_concatenation::{ collection_literal_concatenation, CollectionLiteralConcatenation, }; -pub use mutable_defaults_in_dataclass_fields::{ +pub(crate) use mutable_defaults_in_dataclass_fields::{ function_call_in_dataclass_defaults, is_dataclass, mutable_dataclass_default, FunctionCallInDataclassDefaultArgument, MutableDataclassDefault, }; -pub use pairwise_over_zipped::{pairwise_over_zipped, PairwiseOverZipped}; -pub use unused_noqa::{UnusedCodes, UnusedNOQA}; +pub(crate) use pairwise_over_zipped::{pairwise_over_zipped, PairwiseOverZipped}; +pub(crate) use unused_noqa::{UnusedCodes, UnusedNOQA}; #[derive(Clone, Copy)] -pub enum Context { +pub(crate) enum Context { String, Docstring, Comment, diff --git a/crates/ruff/src/rules/ruff/rules/mutable_defaults_in_dataclass_fields.rs b/crates/ruff/src/rules/ruff/rules/mutable_defaults_in_dataclass_fields.rs index 92217019f0..eb2dfb3f84 100644 --- a/crates/ruff/src/rules/ruff/rules/mutable_defaults_in_dataclass_fields.rs +++ b/crates/ruff/src/rules/ruff/rules/mutable_defaults_in_dataclass_fields.rs @@ -179,7 +179,7 @@ fn is_class_var_annotation(context: &Context, annotation: &Expr) -> bool { } /// RUF009 -pub fn function_call_in_dataclass_defaults(checker: &mut Checker, body: &[Stmt]) { +pub(crate) fn function_call_in_dataclass_defaults(checker: &mut Checker, body: &[Stmt]) { let extend_immutable_calls: Vec = checker .settings .flake8_bugbear @@ -215,7 +215,7 @@ pub fn function_call_in_dataclass_defaults(checker: &mut Checker, body: &[Stmt]) } /// RUF008 -pub fn mutable_dataclass_default(checker: &mut Checker, body: &[Stmt]) { +pub(crate) fn mutable_dataclass_default(checker: &mut Checker, body: &[Stmt]) { for statement in body { match &statement.node { StmtKind::AnnAssign(ast::StmtAnnAssign { @@ -244,7 +244,7 @@ pub fn mutable_dataclass_default(checker: &mut Checker, body: &[Stmt]) { } } -pub fn is_dataclass(checker: &Checker, decorator_list: &[Expr]) -> bool { +pub(crate) fn is_dataclass(checker: &Checker, decorator_list: &[Expr]) -> bool { decorator_list.iter().any(|decorator| { checker .ctx diff --git a/crates/ruff/src/rules/ruff/rules/pairwise_over_zipped.rs b/crates/ruff/src/rules/ruff/rules/pairwise_over_zipped.rs index fc95c612a5..61e2290157 100644 --- a/crates/ruff/src/rules/ruff/rules/pairwise_over_zipped.rs +++ b/crates/ruff/src/rules/ruff/rules/pairwise_over_zipped.rs @@ -23,7 +23,7 @@ struct SliceInfo { } impl SliceInfo { - pub fn new(arg_name: String, slice_start: Option) -> Self { + pub(crate) fn new(arg_name: String, slice_start: Option) -> Self { Self { arg_name, slice_start, @@ -87,7 +87,7 @@ fn to_bound(expr: &Expr) -> Option { } /// RUF007 -pub fn pairwise_over_zipped(checker: &mut Checker, func: &Expr, args: &[Expr]) { +pub(crate) fn pairwise_over_zipped(checker: &mut Checker, func: &Expr, args: &[Expr]) { let ExprKind::Name(ast::ExprName { id, .. }) = &func.node else { return; }; diff --git a/crates/ruff/src/rules/tryceratops/helpers.rs b/crates/ruff/src/rules/tryceratops/helpers.rs index 36641f9069..72954fd9e3 100644 --- a/crates/ruff/src/rules/tryceratops/helpers.rs +++ b/crates/ruff/src/rules/tryceratops/helpers.rs @@ -6,13 +6,13 @@ use ruff_python_semantic::analyze::logging; use ruff_python_semantic::context::Context; /// Collect `logging`-like calls from an AST. -pub struct LoggerCandidateVisitor<'a> { +pub(crate) struct LoggerCandidateVisitor<'a> { context: &'a Context<'a>, - pub calls: Vec<(&'a Expr, &'a Expr)>, + pub(crate) calls: Vec<(&'a Expr, &'a Expr)>, } impl<'a> LoggerCandidateVisitor<'a> { - pub fn new(context: &'a Context<'a>) -> Self { + pub(crate) fn new(context: &'a Context<'a>) -> Self { LoggerCandidateVisitor { context, calls: Vec::new(), diff --git a/crates/ruff/src/rules/tryceratops/rules/error_instead_of_exception.rs b/crates/ruff/src/rules/tryceratops/rules/error_instead_of_exception.rs index 0ad5ef2fe5..6bb21e2f6f 100644 --- a/crates/ruff/src/rules/tryceratops/rules/error_instead_of_exception.rs +++ b/crates/ruff/src/rules/tryceratops/rules/error_instead_of_exception.rs @@ -53,7 +53,7 @@ impl Violation for ErrorInsteadOfException { } /// TRY400 -pub fn error_instead_of_exception(checker: &mut Checker, handlers: &[Excepthandler]) { +pub(crate) fn error_instead_of_exception(checker: &mut Checker, handlers: &[Excepthandler]) { for handler in handlers { let ExcepthandlerKind::ExceptHandler(ast::ExcepthandlerExceptHandler { body, .. }) = &handler.node; diff --git a/crates/ruff/src/rules/tryceratops/rules/mod.rs b/crates/ruff/src/rules/tryceratops/rules/mod.rs index c1ee2203f5..109b37918f 100644 --- a/crates/ruff/src/rules/tryceratops/rules/mod.rs +++ b/crates/ruff/src/rules/tryceratops/rules/mod.rs @@ -1,12 +1,14 @@ -pub use error_instead_of_exception::{error_instead_of_exception, ErrorInsteadOfException}; -pub use raise_vanilla_args::{raise_vanilla_args, RaiseVanillaArgs}; -pub use raise_vanilla_class::{raise_vanilla_class, RaiseVanillaClass}; -pub use raise_within_try::{raise_within_try, RaiseWithinTry}; -pub use reraise_no_cause::{reraise_no_cause, ReraiseNoCause}; -pub use try_consider_else::{try_consider_else, TryConsiderElse}; -pub use type_check_without_type_error::{type_check_without_type_error, TypeCheckWithoutTypeError}; -pub use verbose_log_message::{verbose_log_message, VerboseLogMessage}; -pub use verbose_raise::{verbose_raise, VerboseRaise}; +pub(crate) use error_instead_of_exception::{error_instead_of_exception, ErrorInsteadOfException}; +pub(crate) use raise_vanilla_args::{raise_vanilla_args, RaiseVanillaArgs}; +pub(crate) use raise_vanilla_class::{raise_vanilla_class, RaiseVanillaClass}; +pub(crate) use raise_within_try::{raise_within_try, RaiseWithinTry}; +pub(crate) use reraise_no_cause::{reraise_no_cause, ReraiseNoCause}; +pub(crate) use try_consider_else::{try_consider_else, TryConsiderElse}; +pub(crate) use type_check_without_type_error::{ + type_check_without_type_error, TypeCheckWithoutTypeError, +}; +pub(crate) use verbose_log_message::{verbose_log_message, VerboseLogMessage}; +pub(crate) use verbose_raise::{verbose_raise, VerboseRaise}; mod error_instead_of_exception; mod raise_vanilla_args; diff --git a/crates/ruff/src/rules/tryceratops/rules/raise_vanilla_args.rs b/crates/ruff/src/rules/tryceratops/rules/raise_vanilla_args.rs index 0da77ad04d..9bc7cf131b 100644 --- a/crates/ruff/src/rules/tryceratops/rules/raise_vanilla_args.rs +++ b/crates/ruff/src/rules/tryceratops/rules/raise_vanilla_args.rs @@ -76,7 +76,7 @@ where } /// TRY003 -pub fn raise_vanilla_args(checker: &mut Checker, expr: &Expr) { +pub(crate) fn raise_vanilla_args(checker: &mut Checker, expr: &Expr) { if let ExprKind::Call(ast::ExprCall { args, .. }) = &expr.node { if let Some(arg) = args.first() { if any_string(arg, |part| part.chars().any(char::is_whitespace)) { diff --git a/crates/ruff/src/rules/tryceratops/rules/raise_vanilla_class.rs b/crates/ruff/src/rules/tryceratops/rules/raise_vanilla_class.rs index 5a1f080947..319e38d850 100644 --- a/crates/ruff/src/rules/tryceratops/rules/raise_vanilla_class.rs +++ b/crates/ruff/src/rules/tryceratops/rules/raise_vanilla_class.rs @@ -61,7 +61,7 @@ impl Violation for RaiseVanillaClass { } /// TRY002 -pub fn raise_vanilla_class(checker: &mut Checker, expr: &Expr) { +pub(crate) fn raise_vanilla_class(checker: &mut Checker, expr: &Expr) { if checker .ctx .resolve_call_path( diff --git a/crates/ruff/src/rules/tryceratops/rules/raise_within_try.rs b/crates/ruff/src/rules/tryceratops/rules/raise_within_try.rs index 615fb7c2c0..1e58efdc98 100644 --- a/crates/ruff/src/rules/tryceratops/rules/raise_within_try.rs +++ b/crates/ruff/src/rules/tryceratops/rules/raise_within_try.rs @@ -72,7 +72,7 @@ where } /// TRY301 -pub fn raise_within_try(checker: &mut Checker, body: &[Stmt], handlers: &[Excepthandler]) { +pub(crate) fn raise_within_try(checker: &mut Checker, body: &[Stmt], handlers: &[Excepthandler]) { if handlers.is_empty() { return; } diff --git a/crates/ruff/src/rules/tryceratops/rules/reraise_no_cause.rs b/crates/ruff/src/rules/tryceratops/rules/reraise_no_cause.rs index f192d2a760..3b302b5645 100644 --- a/crates/ruff/src/rules/tryceratops/rules/reraise_no_cause.rs +++ b/crates/ruff/src/rules/tryceratops/rules/reraise_no_cause.rs @@ -47,7 +47,7 @@ impl Violation for ReraiseNoCause { } /// TRY200 -pub fn reraise_no_cause(checker: &mut Checker, body: &[Stmt]) { +pub(crate) fn reraise_no_cause(checker: &mut Checker, body: &[Stmt]) { let raises = { let mut visitor = RaiseStatementVisitor::default(); visitor.visit_body(body); diff --git a/crates/ruff/src/rules/tryceratops/rules/try_consider_else.rs b/crates/ruff/src/rules/tryceratops/rules/try_consider_else.rs index 8e58377472..205ee46bc5 100644 --- a/crates/ruff/src/rules/tryceratops/rules/try_consider_else.rs +++ b/crates/ruff/src/rules/tryceratops/rules/try_consider_else.rs @@ -56,7 +56,7 @@ impl Violation for TryConsiderElse { } /// TRY300 -pub fn try_consider_else( +pub(crate) fn try_consider_else( checker: &mut Checker, body: &[Stmt], orelse: &[Stmt], diff --git a/crates/ruff/src/rules/tryceratops/rules/type_check_without_type_error.rs b/crates/ruff/src/rules/tryceratops/rules/type_check_without_type_error.rs index 449dad2231..a2590861fc 100644 --- a/crates/ruff/src/rules/tryceratops/rules/type_check_without_type_error.rs +++ b/crates/ruff/src/rules/tryceratops/rules/type_check_without_type_error.rs @@ -184,7 +184,7 @@ fn check_orelse(checker: &mut Checker, body: &[Stmt]) { } /// TRY004 -pub fn type_check_without_type_error( +pub(crate) fn type_check_without_type_error( checker: &mut Checker, body: &[Stmt], test: &Expr, diff --git a/crates/ruff/src/rules/tryceratops/rules/verbose_log_message.rs b/crates/ruff/src/rules/tryceratops/rules/verbose_log_message.rs index 97d711377f..85029374e1 100644 --- a/crates/ruff/src/rules/tryceratops/rules/verbose_log_message.rs +++ b/crates/ruff/src/rules/tryceratops/rules/verbose_log_message.rs @@ -63,7 +63,7 @@ where } /// TRY401 -pub fn verbose_log_message(checker: &mut Checker, handlers: &[Excepthandler]) { +pub(crate) fn verbose_log_message(checker: &mut Checker, handlers: &[Excepthandler]) { for handler in handlers { let ExcepthandlerKind::ExceptHandler(ast::ExcepthandlerExceptHandler { name, body, .. diff --git a/crates/ruff/src/rules/tryceratops/rules/verbose_raise.rs b/crates/ruff/src/rules/tryceratops/rules/verbose_raise.rs index 342ac65e36..28cd57a15b 100644 --- a/crates/ruff/src/rules/tryceratops/rules/verbose_raise.rs +++ b/crates/ruff/src/rules/tryceratops/rules/verbose_raise.rs @@ -72,7 +72,7 @@ where } /// TRY201 -pub fn verbose_raise(checker: &mut Checker, handlers: &[Excepthandler]) { +pub(crate) fn verbose_raise(checker: &mut Checker, handlers: &[Excepthandler]) { for handler in handlers { // If the handler assigned a name to the exception... if let ExcepthandlerKind::ExceptHandler(ast::ExcepthandlerExceptHandler { diff --git a/crates/ruff/src/test.rs b/crates/ruff/src/test.rs index 354b063d3f..92b3ba25c9 100644 --- a/crates/ruff/src/test.rs +++ b/crates/ruff/src/test.rs @@ -20,13 +20,13 @@ use crate::registry::AsRule; use crate::rules::pycodestyle::rules::syntax_error; use crate::settings::{flags, Settings}; -pub fn test_resource_path(path: impl AsRef) -> std::path::PathBuf { +pub(crate) fn test_resource_path(path: impl AsRef) -> std::path::PathBuf { Path::new("./resources/test/").join(path) } /// A convenient wrapper around [`check_path`], that additionally /// asserts that autofixes converge after 10 iterations. -pub fn test_path(path: impl AsRef, settings: &Settings) -> Result> { +pub(crate) fn test_path(path: impl AsRef, settings: &Settings) -> Result> { static MAX_ITERATIONS: usize = 10; let path = test_resource_path("fixtures").join(path); diff --git a/crates/ruff_cli/src/cache.rs b/crates/ruff_cli/src/cache.rs index 6354a79bf6..757ef33805 100644 --- a/crates/ruff_cli/src/cache.rs +++ b/crates/ruff_cli/src/cache.rs @@ -162,7 +162,7 @@ fn cache_key( #[allow(dead_code)] /// Initialize the cache at the specified `Path`. -pub fn init(path: &Path) -> Result<()> { +pub(crate) fn init(path: &Path) -> Result<()> { // Create the cache directories. fs::create_dir_all(path.join(content_dir()))?; @@ -197,7 +197,7 @@ fn del_sync(cache_dir: &Path, key: u64) -> Result<(), std::io::Error> { } /// Get a value from the cache. -pub fn get( +pub(crate) fn get( path: &Path, package: Option<&Path>, metadata: &fs::Metadata, @@ -246,7 +246,7 @@ pub fn get( } /// Set a value in the cache. -pub fn set( +pub(crate) fn set( path: &Path, package: Option<&Path>, metadata: &fs::Metadata, @@ -265,7 +265,12 @@ pub fn set( } /// Delete a value from the cache. -pub fn del(path: &Path, package: Option<&Path>, metadata: &fs::Metadata, settings: &AllSettings) { +pub(crate) fn del( + path: &Path, + package: Option<&Path>, + metadata: &fs::Metadata, + settings: &AllSettings, +) { drop(del_sync( &settings.cli.cache_dir, cache_key(path, package, metadata, &settings.lib), diff --git a/crates/ruff_cli/src/commands/add_noqa.rs b/crates/ruff_cli/src/commands/add_noqa.rs index b73d676d6b..54d6417524 100644 --- a/crates/ruff_cli/src/commands/add_noqa.rs +++ b/crates/ruff_cli/src/commands/add_noqa.rs @@ -13,7 +13,7 @@ use ruff::{packaging, resolver, warn_user_once}; use crate::args::Overrides; /// Add `noqa` directives to a collection of files. -pub fn add_noqa( +pub(crate) fn add_noqa( files: &[PathBuf], pyproject_config: &PyprojectConfig, overrides: &Overrides, diff --git a/crates/ruff_cli/src/commands/clean.rs b/crates/ruff_cli/src/commands/clean.rs index 0a00290920..d89f643a53 100644 --- a/crates/ruff_cli/src/commands/clean.rs +++ b/crates/ruff_cli/src/commands/clean.rs @@ -11,7 +11,7 @@ use ruff::logging::LogLevel; use ruff_cache::CACHE_DIR_NAME; /// Clear any caches in the current directory or any subdirectories. -pub fn clean(level: LogLevel) -> Result<()> { +pub(crate) fn clean(level: LogLevel) -> Result<()> { let mut stderr = BufWriter::new(io::stderr().lock()); for entry in WalkDir::new(&*path_dedot::CWD) .into_iter() diff --git a/crates/ruff_cli/src/commands/linter.rs b/crates/ruff_cli/src/commands/linter.rs index 643ddba813..ccbeb5ba45 100644 --- a/crates/ruff_cli/src/commands/linter.rs +++ b/crates/ruff_cli/src/commands/linter.rs @@ -25,7 +25,7 @@ struct LinterCategoryInfo { name: &'static str, } -pub fn linter(format: HelpFormat) -> Result<()> { +pub(crate) fn linter(format: HelpFormat) -> Result<()> { let mut stdout = BufWriter::new(io::stdout().lock()); let mut output = String::new(); diff --git a/crates/ruff_cli/src/commands/mod.rs b/crates/ruff_cli/src/commands/mod.rs index cbe30fd5c5..e989f433e0 100644 --- a/crates/ruff_cli/src/commands/mod.rs +++ b/crates/ruff_cli/src/commands/mod.rs @@ -1,9 +1,9 @@ -pub mod add_noqa; -pub mod clean; -pub mod config; -pub mod linter; -pub mod rule; -pub mod run; -pub mod run_stdin; -pub mod show_files; -pub mod show_settings; +pub(crate) mod add_noqa; +pub(crate) mod clean; +pub(crate) mod config; +pub(crate) mod linter; +pub(crate) mod rule; +pub(crate) mod run; +pub(crate) mod run_stdin; +pub(crate) mod show_files; +pub(crate) mod show_settings; diff --git a/crates/ruff_cli/src/commands/rule.rs b/crates/ruff_cli/src/commands/rule.rs index a9717b57ae..22fab36073 100644 --- a/crates/ruff_cli/src/commands/rule.rs +++ b/crates/ruff_cli/src/commands/rule.rs @@ -16,7 +16,7 @@ struct Explanation<'a> { } /// Explain a `Rule` to the user. -pub fn rule(rule: Rule, format: HelpFormat) -> Result<()> { +pub(crate) fn rule(rule: Rule, format: HelpFormat) -> Result<()> { let (linter, _) = Linter::parse_code(&rule.noqa_code().to_string()).unwrap(); let mut stdout = BufWriter::new(io::stdout().lock()); let mut output = String::new(); diff --git a/crates/ruff_cli/src/commands/run.rs b/crates/ruff_cli/src/commands/run.rs index 85d329577f..07d25afcaa 100644 --- a/crates/ruff_cli/src/commands/run.rs +++ b/crates/ruff_cli/src/commands/run.rs @@ -25,7 +25,7 @@ use crate::diagnostics::Diagnostics; use crate::panic::catch_unwind; /// Run the linter over a collection of files. -pub fn run( +pub(crate) fn run( files: &[PathBuf], pyproject_config: &PyprojectConfig, overrides: &Overrides, diff --git a/crates/ruff_cli/src/commands/run_stdin.rs b/crates/ruff_cli/src/commands/run_stdin.rs index b5d06d7da3..817de79c57 100644 --- a/crates/ruff_cli/src/commands/run_stdin.rs +++ b/crates/ruff_cli/src/commands/run_stdin.rs @@ -18,7 +18,7 @@ fn read_from_stdin() -> Result { } /// Run the linter over a single file, read from `stdin`. -pub fn run_stdin( +pub(crate) fn run_stdin( filename: Option<&Path>, pyproject_config: &PyprojectConfig, overrides: &Overrides, diff --git a/crates/ruff_cli/src/commands/show_files.rs b/crates/ruff_cli/src/commands/show_files.rs index 4efdae3ca9..802501b578 100644 --- a/crates/ruff_cli/src/commands/show_files.rs +++ b/crates/ruff_cli/src/commands/show_files.rs @@ -10,7 +10,7 @@ use ruff::{resolver, warn_user_once}; use crate::args::Overrides; /// Show the list of files to be checked based on current settings. -pub fn show_files( +pub(crate) fn show_files( files: &[PathBuf], pyproject_config: &PyprojectConfig, overrides: &Overrides, diff --git a/crates/ruff_cli/src/commands/show_settings.rs b/crates/ruff_cli/src/commands/show_settings.rs index f0e152c383..48a88b811d 100644 --- a/crates/ruff_cli/src/commands/show_settings.rs +++ b/crates/ruff_cli/src/commands/show_settings.rs @@ -10,7 +10,7 @@ use ruff::resolver::PyprojectConfig; use crate::args::Overrides; /// Print the user-facing configuration settings. -pub fn show_settings( +pub(crate) fn show_settings( files: &[PathBuf], pyproject_config: &PyprojectConfig, overrides: &Overrides, diff --git a/crates/ruff_cli/src/diagnostics.rs b/crates/ruff_cli/src/diagnostics.rs index 64bcfa8681..4c77e73fba 100644 --- a/crates/ruff_cli/src/diagnostics.rs +++ b/crates/ruff_cli/src/diagnostics.rs @@ -25,17 +25,17 @@ use ruff_python_ast::source_code::{LineIndex, SourceCode, SourceFileBuilder}; use crate::cache; #[derive(Debug, Default, PartialEq)] -pub struct Diagnostics { - pub messages: Vec, - pub fixed: FxHashMap, - pub imports: ImportMap, +pub(crate) struct Diagnostics { + pub(crate) messages: Vec, + pub(crate) fixed: FxHashMap, + pub(crate) imports: ImportMap, /// Jupyter notebook indexing table for each input file that is a jupyter notebook /// so we can rewrite the diagnostics in the end - pub jupyter_index: FxHashMap, + pub(crate) jupyter_index: FxHashMap, } impl Diagnostics { - pub fn new(messages: Vec, imports: ImportMap) -> Self { + pub(crate) fn new(messages: Vec, imports: ImportMap) -> Self { Self { messages, fixed: FxHashMap::default(), @@ -100,7 +100,7 @@ fn load_jupyter_notebook(path: &Path) -> Result<(String, JupyterIndex), Box, settings: &AllSettings, @@ -226,7 +226,7 @@ pub fn lint_path( /// Generate `Diagnostic`s from source code content derived from /// stdin. -pub fn lint_stdin( +pub(crate) fn lint_stdin( path: Option<&Path>, package: Option<&Path>, contents: &str, diff --git a/crates/ruff_cli/src/panic.rs b/crates/ruff_cli/src/panic.rs index e67a2e9666..d7ab8d38a9 100644 --- a/crates/ruff_cli/src/panic.rs +++ b/crates/ruff_cli/src/panic.rs @@ -1,7 +1,7 @@ #[derive(Default, Debug)] pub(crate) struct PanicError { - pub info: String, - pub backtrace: Option, + pub(crate) info: String, + pub(crate) backtrace: Option, } impl std::fmt::Display for PanicError { diff --git a/crates/ruff_cli/src/printer.rs b/crates/ruff_cli/src/printer.rs index aeeae31024..d82febf2de 100644 --- a/crates/ruff_cli/src/printer.rs +++ b/crates/ruff_cli/src/printer.rs @@ -76,7 +76,7 @@ pub(crate) struct Printer { } impl Printer { - pub const fn new( + pub(crate) const fn new( format: SerializationFormat, log_level: LogLevel, autofix_level: flags::FixMode, @@ -93,7 +93,7 @@ impl Printer { } } - pub fn write_to_user(&self, message: &str) { + pub(crate) fn write_to_user(&self, message: &str) { if self.log_level >= LogLevel::Default { notify_user!("{}", message); } @@ -153,7 +153,11 @@ impl Printer { Ok(()) } - pub fn write_once(&self, diagnostics: &Diagnostics, writer: &mut impl Write) -> Result<()> { + pub(crate) fn write_once( + &self, + diagnostics: &Diagnostics, + writer: &mut impl Write, + ) -> Result<()> { if matches!(self.log_level, LogLevel::Silent) { return Ok(()); } @@ -240,7 +244,7 @@ impl Printer { Ok(()) } - pub fn write_statistics(&self, diagnostics: &Diagnostics) -> Result<()> { + pub(crate) fn write_statistics(&self, diagnostics: &Diagnostics) -> Result<()> { let statistics: Vec = diagnostics .messages .iter() @@ -335,7 +339,7 @@ impl Printer { Ok(()) } - pub fn write_continuously(&self, diagnostics: &Diagnostics) -> Result<()> { + pub(crate) fn write_continuously(&self, diagnostics: &Diagnostics) -> Result<()> { if matches!(self.log_level, LogLevel::Silent) { return Ok(()); } @@ -369,7 +373,7 @@ impl Printer { Ok(()) } - pub fn clear_screen() -> Result<()> { + pub(crate) fn clear_screen() -> Result<()> { #[cfg(not(target_family = "wasm"))] clearscreen::clear()?; Ok(()) diff --git a/crates/ruff_cli/src/resolve.rs b/crates/ruff_cli/src/resolve.rs index 0bf5db6670..7952d70158 100644 --- a/crates/ruff_cli/src/resolve.rs +++ b/crates/ruff_cli/src/resolve.rs @@ -14,7 +14,7 @@ use crate::args::Overrides; /// Resolve the relevant settings strategy and defaults for the current /// invocation. -pub fn resolve( +pub(crate) fn resolve( isolated: bool, config: Option<&Path>, overrides: &Overrides, diff --git a/crates/ruff_cli/tests/black_compatibility_test.rs b/crates/ruff_cli/tests/black_compatibility_test.rs index 5daafd09af..afe3d174c7 100644 --- a/crates/ruff_cli/tests/black_compatibility_test.rs +++ b/crates/ruff_cli/tests/black_compatibility_test.rs @@ -24,7 +24,7 @@ struct Blackd { const BIN_NAME: &str = "ruff"; impl Blackd { - pub fn new() -> Result { + pub(crate) fn new() -> Result { // Get free TCP port to run on let address = TcpListener::bind(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0))?.local_addr()?; @@ -63,7 +63,7 @@ impl Blackd { } /// Format given code with blackd. - pub fn check(&self, code: &[u8]) -> Result> { + pub(crate) fn check(&self, code: &[u8]) -> Result> { match self .client .post(&format!("http://{}/", self.address)) diff --git a/crates/ruff_dev/src/generate_all.rs b/crates/ruff_dev/src/generate_all.rs index 5e548429af..3eb1b0adfa 100644 --- a/crates/ruff_dev/src/generate_all.rs +++ b/crates/ruff_dev/src/generate_all.rs @@ -4,16 +4,16 @@ use anyhow::Result; use crate::{generate_cli_help, generate_docs, generate_json_schema}; -pub const REGENERATE_ALL_COMMAND: &str = "cargo dev generate-all"; +pub(crate) const REGENERATE_ALL_COMMAND: &str = "cargo dev generate-all"; #[derive(clap::Args)] -pub struct Args { +pub(crate) struct Args { #[arg(long, default_value_t, value_enum)] mode: Mode, } #[derive(Copy, Clone, PartialEq, Eq, clap::ValueEnum, Default)] -pub enum Mode { +pub(crate) enum Mode { /// Update the content in the `configuration.md`. #[default] Write, @@ -31,7 +31,7 @@ impl Mode { } } -pub fn main(args: &Args) -> Result<()> { +pub(crate) fn main(args: &Args) -> Result<()> { generate_json_schema::main(&generate_json_schema::Args { mode: args.mode })?; generate_cli_help::main(&generate_cli_help::Args { mode: args.mode })?; generate_docs::main(&generate_docs::Args { diff --git a/crates/ruff_dev/src/generate_cli_help.rs b/crates/ruff_dev/src/generate_cli_help.rs index 7b5b0d46bc..266cfe6f5e 100644 --- a/crates/ruff_dev/src/generate_cli_help.rs +++ b/crates/ruff_dev/src/generate_cli_help.rs @@ -19,7 +19,7 @@ const SUBCOMMAND_HELP_BEGIN_PRAGMA: &str = ""; #[derive(clap::Args)] -pub struct Args { +pub(crate) struct Args { #[arg(long, default_value_t, value_enum)] pub(crate) mode: Mode, } diff --git a/crates/ruff_dev/src/generate_docs.rs b/crates/ruff_dev/src/generate_docs.rs index 6bfddb7e86..f191c081f5 100644 --- a/crates/ruff_dev/src/generate_docs.rs +++ b/crates/ruff_dev/src/generate_docs.rs @@ -15,13 +15,13 @@ use ruff_diagnostics::AutofixKind; use crate::ROOT_DIR; #[derive(clap::Args)] -pub struct Args { +pub(crate) struct Args { /// Write the generated docs to stdout (rather than to the filesystem). #[arg(long)] pub(crate) dry_run: bool, } -pub fn main(args: &Args) -> Result<()> { +pub(crate) fn main(args: &Args) -> Result<()> { for rule in Rule::iter() { if let Some(explanation) = rule.explanation() { let mut output = String::new(); diff --git a/crates/ruff_dev/src/generate_json_schema.rs b/crates/ruff_dev/src/generate_json_schema.rs index 0d8d0d6a0c..5d8139674b 100644 --- a/crates/ruff_dev/src/generate_json_schema.rs +++ b/crates/ruff_dev/src/generate_json_schema.rs @@ -12,13 +12,13 @@ use schemars::schema_for; use crate::ROOT_DIR; #[derive(clap::Args)] -pub struct Args { +pub(crate) struct Args { /// Write the generated table to stdout (rather than to `ruff.schema.json`). #[arg(long, default_value_t, value_enum)] pub(crate) mode: Mode, } -pub fn main(args: &Args) -> Result<()> { +pub(crate) fn main(args: &Args) -> Result<()> { let schema = schema_for!(Options); let schema_string = serde_json::to_string_pretty(&schema).unwrap(); let filename = "ruff.schema.json"; diff --git a/crates/ruff_dev/src/generate_options.rs b/crates/ruff_dev/src/generate_options.rs index 8e6fe6f077..8e541eb192 100644 --- a/crates/ruff_dev/src/generate_options.rs +++ b/crates/ruff_dev/src/generate_options.rs @@ -24,7 +24,7 @@ fn emit_field(output: &mut String, name: &str, field: &OptionField, group_name: output.push('\n'); } -pub fn generate() -> String { +pub(crate) fn generate() -> String { let mut output: String = "### Top-level\n\n".into(); let sorted_options: Vec<_> = Options::metadata() diff --git a/crates/ruff_dev/src/generate_rules_table.rs b/crates/ruff_dev/src/generate_rules_table.rs index 78289742a7..4d29bfea2b 100644 --- a/crates/ruff_dev/src/generate_rules_table.rs +++ b/crates/ruff_dev/src/generate_rules_table.rs @@ -39,7 +39,7 @@ fn generate_table(table_out: &mut String, rules: impl IntoIterator, table_out.push('\n'); } -pub fn generate() -> String { +pub(crate) fn generate() -> String { // Generate the table string. let mut table_out = format!("The {FIX_SYMBOL} emoji indicates that a rule is automatically fixable by the `--fix` command-line option.\n\n"); for linter in Linter::iter() { diff --git a/crates/ruff_dev/src/print_ast.rs b/crates/ruff_dev/src/print_ast.rs index d4dd75b326..4556f133c9 100644 --- a/crates/ruff_dev/src/print_ast.rs +++ b/crates/ruff_dev/src/print_ast.rs @@ -8,13 +8,13 @@ use anyhow::Result; use rustpython_parser as parser; #[derive(clap::Args)] -pub struct Args { +pub(crate) struct Args { /// Python file for which to generate the AST. #[arg(required = true)] file: PathBuf, } -pub fn main(args: &Args) -> Result<()> { +pub(crate) fn main(args: &Args) -> Result<()> { let contents = fs::read_to_string(&args.file)?; let python_ast = parser::parse_program(&contents, &args.file.to_string_lossy())?; println!("{python_ast:#?}"); diff --git a/crates/ruff_dev/src/print_cst.rs b/crates/ruff_dev/src/print_cst.rs index 671227377f..166923486e 100644 --- a/crates/ruff_dev/src/print_cst.rs +++ b/crates/ruff_dev/src/print_cst.rs @@ -7,13 +7,13 @@ use std::path::PathBuf; use anyhow::{bail, Result}; #[derive(clap::Args)] -pub struct Args { +pub(crate) struct Args { /// Python file for which to generate the CST. #[arg(required = true)] file: PathBuf, } -pub fn main(args: &Args) -> Result<()> { +pub(crate) fn main(args: &Args) -> Result<()> { let contents = fs::read_to_string(&args.file)?; match libcst_native::parse_module(&contents, None) { Ok(python_cst) => { diff --git a/crates/ruff_dev/src/print_tokens.rs b/crates/ruff_dev/src/print_tokens.rs index 176ef4ec95..39b05b3a62 100644 --- a/crates/ruff_dev/src/print_tokens.rs +++ b/crates/ruff_dev/src/print_tokens.rs @@ -8,13 +8,13 @@ use anyhow::Result; use rustpython_parser::{lexer, Mode}; #[derive(clap::Args)] -pub struct Args { +pub(crate) struct Args { /// Python file for which to generate the AST. #[arg(required = true)] file: PathBuf, } -pub fn main(args: &Args) -> Result<()> { +pub(crate) fn main(args: &Args) -> Result<()> { let contents = fs::read_to_string(&args.file)?; for (tok, range) in lexer::lex(&contents, Mode::Module).flatten() { println!( diff --git a/crates/ruff_dev/src/round_trip.rs b/crates/ruff_dev/src/round_trip.rs index 73def5788f..4cc4f36c59 100644 --- a/crates/ruff_dev/src/round_trip.rs +++ b/crates/ruff_dev/src/round_trip.rs @@ -9,13 +9,13 @@ use anyhow::Result; use ruff::round_trip; #[derive(clap::Args)] -pub struct Args { +pub(crate) struct Args { /// Python file to round-trip. #[arg(required = true)] file: PathBuf, } -pub fn main(args: &Args) -> Result<()> { +pub(crate) fn main(args: &Args) -> Result<()> { let contents = fs::read_to_string(&args.file)?; println!("{}", round_trip(&contents, &args.file.to_string_lossy())?); Ok(()) diff --git a/crates/ruff_diagnostics/src/edit.rs b/crates/ruff_diagnostics/src/edit.rs index 733d5c049d..4eaf7ad3a7 100644 --- a/crates/ruff_diagnostics/src/edit.rs +++ b/crates/ruff_diagnostics/src/edit.rs @@ -132,15 +132,15 @@ enum EditOperationKind { } impl EditOperationKind { - pub const fn is_insertion(self) -> bool { + pub(crate) const fn is_insertion(self) -> bool { matches!(self, EditOperationKind::Insertion) } - pub const fn is_deletion(self) -> bool { + pub(crate) const fn is_deletion(self) -> bool { matches!(self, EditOperationKind::Deletion) } - pub const fn is_replacement(self) -> bool { + pub(crate) const fn is_replacement(self) -> bool { matches!(self, EditOperationKind::Replacement) } } diff --git a/crates/ruff_formatter/src/group_id.rs b/crates/ruff_formatter/src/group_id.rs index 396bc50b41..8f06ae8e37 100644 --- a/crates/ruff_formatter/src/group_id.rs +++ b/crates/ruff_formatter/src/group_id.rs @@ -64,7 +64,7 @@ pub(super) struct UniqueGroupIdBuilder { impl UniqueGroupIdBuilder { /// Creates a new unique group id with the given debug name. - pub fn group_id(&self, debug_name: &'static str) -> GroupId { + pub(crate) fn group_id(&self, debug_name: &'static str) -> GroupId { let id = self.next_id.fetch_add(1, Ordering::Relaxed); let id = NonZeroU32::new(id).unwrap_or_else(|| panic!("Group ID counter overflowed")); diff --git a/crates/ruff_formatter/src/printer/call_stack.rs b/crates/ruff_formatter/src/printer/call_stack.rs index 243dbe6fa9..8bedc9f783 100644 --- a/crates/ruff_formatter/src/printer/call_stack.rs +++ b/crates/ruff_formatter/src/printer/call_stack.rs @@ -31,7 +31,7 @@ pub(super) struct PrintElementArgs { } impl PrintElementArgs { - pub fn new(indent: Indention) -> Self { + pub(crate) fn new(indent: Indention) -> Self { Self { indent, ..Self::default() @@ -46,27 +46,27 @@ impl PrintElementArgs { self.indent } - pub fn increment_indent_level(mut self, indent_style: IndentStyle) -> Self { + pub(crate) fn increment_indent_level(mut self, indent_style: IndentStyle) -> Self { self.indent = self.indent.increment_level(indent_style); self } - pub fn decrement_indent(mut self) -> Self { + pub(crate) fn decrement_indent(mut self) -> Self { self.indent = self.indent.decrement(); self } - pub fn reset_indent(mut self) -> Self { + pub(crate) fn reset_indent(mut self) -> Self { self.indent = Indention::default(); self } - pub fn set_indent_align(mut self, count: NonZeroU8) -> Self { + pub(crate) fn set_indent_align(mut self, count: NonZeroU8) -> Self { self.indent = self.indent.set_align(count); self } - pub fn with_print_mode(mut self, mode: PrintMode) -> Self { + pub(crate) fn with_print_mode(mut self, mode: PrintMode) -> Self { self.mode = mode; self } diff --git a/crates/ruff_macros/src/cache_key.rs b/crates/ruff_macros/src/cache_key.rs index 85087f392f..fa1acecedd 100644 --- a/crates/ruff_macros/src/cache_key.rs +++ b/crates/ruff_macros/src/cache_key.rs @@ -3,7 +3,7 @@ use quote::{format_ident, quote}; use syn::spanned::Spanned; use syn::{Data, DeriveInput, Error, Fields}; -pub fn derive_cache_key(item: &DeriveInput) -> syn::Result { +pub(crate) fn derive_cache_key(item: &DeriveInput) -> syn::Result { let fields = match &item.data { Data::Enum(item_enum) => { let arms = item_enum.variants.iter().enumerate().map(|(i, variant)| { diff --git a/crates/ruff_macros/src/config.rs b/crates/ruff_macros/src/config.rs index f0f2a1843f..11550fde94 100644 --- a/crates/ruff_macros/src/config.rs +++ b/crates/ruff_macros/src/config.rs @@ -7,7 +7,7 @@ use syn::{ Fields, Lit, LitStr, Path, PathArguments, PathSegment, Token, Type, TypePath, }; -pub fn derive_impl(input: DeriveInput) -> syn::Result { +pub(crate) fn derive_impl(input: DeriveInput) -> syn::Result { let DeriveInput { ident, data, .. } = input; match data { diff --git a/crates/ruff_macros/src/derive_message_formats.rs b/crates/ruff_macros/src/derive_message_formats.rs index 9a9fa8e844..8e6f04fe4f 100644 --- a/crates/ruff_macros/src/derive_message_formats.rs +++ b/crates/ruff_macros/src/derive_message_formats.rs @@ -3,7 +3,7 @@ use quote::{quote, quote_spanned, ToTokens}; use syn::spanned::Spanned; use syn::{Block, Expr, ItemFn, Stmt}; -pub fn derive_message_formats(func: &ItemFn) -> proc_macro2::TokenStream { +pub(crate) fn derive_message_formats(func: &ItemFn) -> proc_macro2::TokenStream { let mut strings = quote!(); if let Err(err) = parse_block(&func.block, &mut strings) { diff --git a/crates/ruff_macros/src/map_codes.rs b/crates/ruff_macros/src/map_codes.rs index 9c6579ce85..3a9743e550 100644 --- a/crates/ruff_macros/src/map_codes.rs +++ b/crates/ruff_macros/src/map_codes.rs @@ -10,7 +10,7 @@ use syn::{ use crate::rule_code_prefix::{get_prefix_ident, if_all_same}; -pub fn map_codes(func: &ItemFn) -> syn::Result { +pub(crate) fn map_codes(func: &ItemFn) -> syn::Result { let Some(last_stmt) = func.block.stmts.last() else { return Err(Error::new(func.block.span(), "expected body to end in an expression")); }; diff --git a/crates/ruff_macros/src/register_rules.rs b/crates/ruff_macros/src/register_rules.rs index db98f71d64..15b0992304 100644 --- a/crates/ruff_macros/src/register_rules.rs +++ b/crates/ruff_macros/src/register_rules.rs @@ -2,7 +2,7 @@ use quote::quote; use syn::parse::Parse; use syn::{Attribute, Ident, Path, Token}; -pub fn register_rules(input: &Input) -> proc_macro2::TokenStream { +pub(crate) fn register_rules(input: &Input) -> proc_macro2::TokenStream { let mut rule_variants = quote!(); let mut rule_message_formats_match_arms = quote!(); let mut rule_autofixable_match_arms = quote!(); @@ -74,7 +74,7 @@ pub fn register_rules(input: &Input) -> proc_macro2::TokenStream { } } -pub struct Input { +pub(crate) struct Input { entries: Vec<(Path, Ident, Vec)>, } diff --git a/crates/ruff_macros/src/rule_code_prefix.rs b/crates/ruff_macros/src/rule_code_prefix.rs index 3485cd9734..5ec760fae9 100644 --- a/crates/ruff_macros/src/rule_code_prefix.rs +++ b/crates/ruff_macros/src/rule_code_prefix.rs @@ -4,7 +4,7 @@ use proc_macro2::Span; use quote::quote; use syn::{Attribute, Ident}; -pub fn get_prefix_ident(prefix: &str) -> Ident { +pub(crate) fn get_prefix_ident(prefix: &str) -> Ident { let prefix = if prefix.as_bytes()[0].is_ascii_digit() { // Identifiers in Rust may not start with a number. format!("_{prefix}") @@ -14,7 +14,7 @@ pub fn get_prefix_ident(prefix: &str) -> Ident { Ident::new(&prefix, Span::call_site()) } -pub fn expand<'a>( +pub(crate) fn expand<'a>( prefix_ident: &Ident, variants: impl Iterator)>, ) -> proc_macro2::TokenStream { @@ -106,7 +106,7 @@ fn attributes_for_prefix( /// If all values in an iterator are the same, return that value. Otherwise, /// return `None`. -pub fn if_all_same(iter: impl Iterator) -> Option { +pub(crate) fn if_all_same(iter: impl Iterator) -> Option { let mut iter = iter.peekable(); let first = iter.next()?; if iter.all(|x| x == first) { diff --git a/crates/ruff_macros/src/rule_namespace.rs b/crates/ruff_macros/src/rule_namespace.rs index b95cbe6f36..67dd7c4070 100644 --- a/crates/ruff_macros/src/rule_namespace.rs +++ b/crates/ruff_macros/src/rule_namespace.rs @@ -5,7 +5,7 @@ use quote::quote; use syn::spanned::Spanned; use syn::{Attribute, Data, DataEnum, DeriveInput, Error, ExprLit, Lit, Meta, MetaNameValue}; -pub fn derive_impl(input: DeriveInput) -> syn::Result { +pub(crate) fn derive_impl(input: DeriveInput) -> syn::Result { let DeriveInput { ident, data: Data::Enum(DataEnum { variants, .. }), .. } = input else { diff --git a/crates/ruff_macros/src/violation.rs b/crates/ruff_macros/src/violation.rs index 0104007228..8356d0d56c 100644 --- a/crates/ruff_macros/src/violation.rs +++ b/crates/ruff_macros/src/violation.rs @@ -45,7 +45,7 @@ fn get_docs(attrs: &[Attribute]) -> Result { Ok(explanation) } -pub fn violation(violation: &ItemStruct) -> Result { +pub(crate) fn violation(violation: &ItemStruct) -> Result { let ident = &violation.ident; let explanation = get_docs(&violation.attrs)?; let violation = if explanation.trim().is_empty() { diff --git a/crates/ruff_python_ast/src/source_code/generator.rs b/crates/ruff_python_ast/src/source_code/generator.rs index d9b4de2cd5..5fca7fe87e 100644 --- a/crates/ruff_python_ast/src/source_code/generator.rs +++ b/crates/ruff_python_ast/src/source_code/generator.rs @@ -14,50 +14,50 @@ use crate::newlines::LineEnding; use crate::source_code::stylist::{Indentation, Quote, Stylist}; mod precedence { - pub const ASSIGN: u8 = 3; - pub const ANN_ASSIGN: u8 = 5; - pub const AUG_ASSIGN: u8 = 5; - pub const EXPR: u8 = 5; - pub const YIELD: u8 = 7; - pub const YIELD_FROM: u8 = 7; - pub const IF: u8 = 9; - pub const FOR: u8 = 9; - pub const ASYNC_FOR: u8 = 9; - pub const WHILE: u8 = 9; - pub const RETURN: u8 = 11; - pub const SLICE: u8 = 13; - pub const SUBSCRIPT: u8 = 13; - pub const COMPREHENSION_TARGET: u8 = 19; - pub const TUPLE: u8 = 19; - pub const FORMATTED_VALUE: u8 = 19; - pub const COMMA: u8 = 21; - pub const NAMED_EXPR: u8 = 23; - pub const ASSERT: u8 = 23; - pub const LAMBDA: u8 = 27; - pub const IF_EXP: u8 = 27; - pub const COMPREHENSION: u8 = 29; - pub const OR: u8 = 31; - pub const AND: u8 = 33; - pub const NOT: u8 = 35; - pub const CMP: u8 = 37; - pub const BIT_OR: u8 = 39; - pub const BIT_XOR: u8 = 41; - pub const BIT_AND: u8 = 43; - pub const LSHIFT: u8 = 45; - pub const RSHIFT: u8 = 45; - pub const ADD: u8 = 47; - pub const SUB: u8 = 47; - pub const MULT: u8 = 49; - pub const DIV: u8 = 49; - pub const MOD: u8 = 49; - pub const FLOORDIV: u8 = 49; - pub const MAT_MULT: u8 = 49; - pub const INVERT: u8 = 53; - pub const UADD: u8 = 53; - pub const USUB: u8 = 53; - pub const POW: u8 = 55; - pub const AWAIT: u8 = 57; - pub const MAX: u8 = 63; + pub(crate) const ASSIGN: u8 = 3; + pub(crate) const ANN_ASSIGN: u8 = 5; + pub(crate) const AUG_ASSIGN: u8 = 5; + pub(crate) const EXPR: u8 = 5; + pub(crate) const YIELD: u8 = 7; + pub(crate) const YIELD_FROM: u8 = 7; + pub(crate) const IF: u8 = 9; + pub(crate) const FOR: u8 = 9; + pub(crate) const ASYNC_FOR: u8 = 9; + pub(crate) const WHILE: u8 = 9; + pub(crate) const RETURN: u8 = 11; + pub(crate) const SLICE: u8 = 13; + pub(crate) const SUBSCRIPT: u8 = 13; + pub(crate) const COMPREHENSION_TARGET: u8 = 19; + pub(crate) const TUPLE: u8 = 19; + pub(crate) const FORMATTED_VALUE: u8 = 19; + pub(crate) const COMMA: u8 = 21; + pub(crate) const NAMED_EXPR: u8 = 23; + pub(crate) const ASSERT: u8 = 23; + pub(crate) const LAMBDA: u8 = 27; + pub(crate) const IF_EXP: u8 = 27; + pub(crate) const COMPREHENSION: u8 = 29; + pub(crate) const OR: u8 = 31; + pub(crate) const AND: u8 = 33; + pub(crate) const NOT: u8 = 35; + pub(crate) const CMP: u8 = 37; + pub(crate) const BIT_OR: u8 = 39; + pub(crate) const BIT_XOR: u8 = 41; + pub(crate) const BIT_AND: u8 = 43; + pub(crate) const LSHIFT: u8 = 45; + pub(crate) const RSHIFT: u8 = 45; + pub(crate) const ADD: u8 = 47; + pub(crate) const SUB: u8 = 47; + pub(crate) const MULT: u8 = 49; + pub(crate) const DIV: u8 = 49; + pub(crate) const MOD: u8 = 49; + pub(crate) const FLOORDIV: u8 = 49; + pub(crate) const MAT_MULT: u8 = 49; + pub(crate) const INVERT: u8 = 53; + pub(crate) const UADD: u8 = 53; + pub(crate) const USUB: u8 = 53; + pub(crate) const POW: u8 = 55; + pub(crate) const AWAIT: u8 = 57; + pub(crate) const MAX: u8 = 63; } pub struct Generator<'a> { diff --git a/crates/ruff_python_formatter/src/attachment.rs b/crates/ruff_python_formatter/src/attachment.rs index 55d6072a96..e738c460a9 100644 --- a/crates/ruff_python_formatter/src/attachment.rs +++ b/crates/ruff_python_formatter/src/attachment.rs @@ -116,7 +116,7 @@ impl<'a> Visitor<'a> for AttachmentVisitor { } } -pub fn attach(python_cst: &mut [Stmt], trivia: Vec) { +pub(crate) fn attach(python_cst: &mut [Stmt], trivia: Vec) { let index = decorate_trivia(trivia, python_cst); let mut visitor = AttachmentVisitor { index }; for stmt in python_cst { diff --git a/crates/ruff_python_formatter/src/cst/helpers.rs b/crates/ruff_python_formatter/src/cst/helpers.rs index f61c9872bb..131a24342a 100644 --- a/crates/ruff_python_formatter/src/cst/helpers.rs +++ b/crates/ruff_python_formatter/src/cst/helpers.rs @@ -2,7 +2,7 @@ use ruff_python_ast::source_code::Locator; use ruff_text_size::{TextLen, TextRange, TextSize}; /// Return `true` if the given string is a radix literal (e.g., `0b101`). -pub fn is_radix_literal(content: &str) -> bool { +pub(crate) fn is_radix_literal(content: &str) -> bool { content.starts_with("0b") || content.starts_with("0o") || content.starts_with("0x") @@ -12,7 +12,7 @@ pub fn is_radix_literal(content: &str) -> bool { } /// Find the first token in the given range that satisfies the given predicate. -pub fn find_tok( +pub(crate) fn find_tok( range: TextRange, locator: &Locator, f: impl Fn(rustpython_parser::Tok) -> bool, @@ -35,7 +35,7 @@ pub fn find_tok( /// /// `location` is the start of the compound statement (e.g., the `if` in `if x:`). /// `end_location` is the end of the last statement in the body. -pub fn expand_indented_block( +pub(crate) fn expand_indented_block( location: TextSize, end_location: TextSize, locator: &Locator, @@ -126,7 +126,7 @@ pub fn expand_indented_block( } /// Return true if the `orelse` block of an `if` statement is an `elif` statement. -pub fn is_elif(orelse: &[rustpython_parser::ast::Stmt], locator: &Locator) -> bool { +pub(crate) fn is_elif(orelse: &[rustpython_parser::ast::Stmt], locator: &Locator) -> bool { if orelse.len() == 1 && matches!(orelse[0].node, rustpython_parser::ast::StmtKind::If { .. }) { let contents = locator.after(orelse[0].start()); if contents.starts_with("elif") { diff --git a/crates/ruff_python_formatter/src/cst/mod.rs b/crates/ruff_python_formatter/src/cst/mod.rs index 01a91756a2..a250f79660 100644 --- a/crates/ruff_python_formatter/src/cst/mod.rs +++ b/crates/ruff_python_formatter/src/cst/mod.rs @@ -13,8 +13,8 @@ use ruff_python_ast::source_code::Locator; use crate::cst::helpers::{expand_indented_block, find_tok, is_elif}; use crate::trivia::{Parenthesize, Trivia}; -pub mod helpers; -pub mod visitor; +pub(crate) mod helpers; +pub(crate) mod visitor; type Ident = String; @@ -96,7 +96,7 @@ impl From<&rustpython_parser::ast::Boolop> for BoolOpKind { } } -pub type BoolOp = Attributed; +pub(crate) type BoolOp = Attributed; #[derive(Clone, Debug, PartialEq)] pub enum OperatorKind { @@ -115,7 +115,7 @@ pub enum OperatorKind { FloorDiv, } -pub type Operator = Attributed; +pub(crate) type Operator = Attributed; impl From<&rustpython_parser::ast::Operator> for OperatorKind { fn from(op: &rustpython_parser::ast::Operator) -> Self { @@ -145,7 +145,7 @@ pub enum UnaryOpKind { USub, } -pub type UnaryOp = Attributed; +pub(crate) type UnaryOp = Attributed; impl From<&rustpython_parser::ast::Unaryop> for UnaryOpKind { fn from(op: &rustpython_parser::ast::Unaryop) -> Self { @@ -172,7 +172,7 @@ pub enum CmpOpKind { NotIn, } -pub type CmpOp = Attributed; +pub(crate) type CmpOp = Attributed; impl From<&rustpython_parser::ast::Cmpop> for CmpOpKind { fn from(op: &rustpython_parser::ast::Cmpop) -> Self { @@ -191,7 +191,7 @@ impl From<&rustpython_parser::ast::Cmpop> for CmpOpKind { } } -pub type Body = Attributed>; +pub(crate) type Body = Attributed>; impl From<(Vec, &Locator<'_>)> for Body { fn from((body, locator): (Vec, &Locator)) -> Self { @@ -335,7 +335,7 @@ pub enum StmtKind { Continue, } -pub type Stmt = Attributed; +pub(crate) type Stmt = Attributed; #[derive(Clone, Debug, PartialEq)] pub enum ExprKind { @@ -453,7 +453,7 @@ pub enum ExprKind { }, } -pub type Expr = Attributed; +pub(crate) type Expr = Attributed; #[derive(Clone, Debug, PartialEq)] pub struct Comprehension { @@ -472,7 +472,7 @@ pub enum ExcepthandlerKind { }, } -pub type Excepthandler = Attributed; +pub(crate) type Excepthandler = Attributed; #[derive(Clone, Debug, PartialEq)] pub enum SliceIndexKind { @@ -482,7 +482,7 @@ pub enum SliceIndexKind { Index { value: Box }, } -pub type SliceIndex = Attributed; +pub(crate) type SliceIndex = Attributed; #[derive(Clone, Debug, PartialEq)] pub struct Arguments { @@ -502,7 +502,7 @@ pub struct ArgData { pub type_comment: Option, } -pub type Arg = Attributed; +pub(crate) type Arg = Attributed; #[derive(Clone, Debug, PartialEq)] pub struct KeywordData { @@ -510,7 +510,7 @@ pub struct KeywordData { pub value: Expr, } -pub type Keyword = Attributed; +pub(crate) type Keyword = Attributed; #[derive(Clone, Debug, PartialEq)] pub struct AliasData { @@ -518,7 +518,7 @@ pub struct AliasData { pub asname: Option, } -pub type Alias = Attributed; +pub(crate) type Alias = Attributed; #[derive(Clone, Debug, PartialEq)] pub struct Withitem { @@ -568,7 +568,7 @@ pub enum PatternKind { }, } -pub type Pattern = Attributed; +pub(crate) type Pattern = Attributed; impl From<(rustpython_parser::ast::Alias, &Locator<'_>)> for Alias { fn from((alias, _locator): (rustpython_parser::ast::Alias, &Locator)) -> Self { diff --git a/crates/ruff_python_formatter/src/cst/visitor.rs b/crates/ruff_python_formatter/src/cst/visitor.rs index 389794b803..72c64e6fb6 100644 --- a/crates/ruff_python_formatter/src/cst/visitor.rs +++ b/crates/ruff_python_formatter/src/cst/visitor.rs @@ -6,7 +6,7 @@ use crate::cst::{ SliceIndexKind, Stmt, StmtKind, UnaryOp, Withitem, }; -pub trait Visitor<'a> { +pub(crate) trait Visitor<'a> { fn visit_stmt(&mut self, stmt: &'a mut Stmt) { walk_stmt(self, stmt); } @@ -72,13 +72,13 @@ pub trait Visitor<'a> { } } -pub fn walk_body<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, body: &'a mut Body) { +pub(crate) fn walk_body<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, body: &'a mut Body) { for stmt in &mut body.node { visitor.visit_stmt(stmt); } } -pub fn walk_stmt<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, stmt: &'a mut Stmt) { +pub(crate) fn walk_stmt<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, stmt: &'a mut Stmt) { match &mut stmt.node { StmtKind::FunctionDef { args, @@ -292,7 +292,7 @@ pub fn walk_stmt<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, stmt: &'a mut Stm } } -pub fn walk_expr<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, expr: &'a mut Expr) { +pub(crate) fn walk_expr<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, expr: &'a mut Expr) { match &mut expr.node { ExprKind::BoolOp { ops, values } => { for op in ops { @@ -451,7 +451,10 @@ pub fn walk_expr<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, expr: &'a mut Exp } } -pub fn walk_constant<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, constant: &'a mut Constant) { +pub(crate) fn walk_constant<'a, V: Visitor<'a> + ?Sized>( + visitor: &mut V, + constant: &'a mut Constant, +) { if let Constant::Tuple(constants) = constant { for constant in constants { visitor.visit_constant(constant); @@ -459,7 +462,7 @@ pub fn walk_constant<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, constant: &'a } } -pub fn walk_comprehension<'a, V: Visitor<'a> + ?Sized>( +pub(crate) fn walk_comprehension<'a, V: Visitor<'a> + ?Sized>( visitor: &mut V, comprehension: &'a mut Comprehension, ) { @@ -470,7 +473,7 @@ pub fn walk_comprehension<'a, V: Visitor<'a> + ?Sized>( } } -pub fn walk_excepthandler<'a, V: Visitor<'a> + ?Sized>( +pub(crate) fn walk_excepthandler<'a, V: Visitor<'a> + ?Sized>( visitor: &mut V, excepthandler: &'a mut Excepthandler, ) { @@ -484,7 +487,7 @@ pub fn walk_excepthandler<'a, V: Visitor<'a> + ?Sized>( } } -pub fn walk_slice_index<'a, V: Visitor<'a> + ?Sized>( +pub(crate) fn walk_slice_index<'a, V: Visitor<'a> + ?Sized>( visitor: &mut V, slice_index: &'a mut SliceIndex, ) { @@ -496,7 +499,10 @@ pub fn walk_slice_index<'a, V: Visitor<'a> + ?Sized>( } } -pub fn walk_arguments<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, arguments: &'a mut Arguments) { +pub(crate) fn walk_arguments<'a, V: Visitor<'a> + ?Sized>( + visitor: &mut V, + arguments: &'a mut Arguments, +) { for arg in &mut arguments.posonlyargs { visitor.visit_arg(arg); } @@ -520,24 +526,27 @@ pub fn walk_arguments<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, arguments: & } } -pub fn walk_arg<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, arg: &'a mut Arg) { +pub(crate) fn walk_arg<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, arg: &'a mut Arg) { if let Some(expr) = &mut arg.node.annotation { visitor.visit_annotation(expr); } } -pub fn walk_keyword<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, keyword: &'a mut Keyword) { +pub(crate) fn walk_keyword<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, keyword: &'a mut Keyword) { visitor.visit_expr(&mut keyword.node.value); } -pub fn walk_withitem<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, withitem: &'a mut Withitem) { +pub(crate) fn walk_withitem<'a, V: Visitor<'a> + ?Sized>( + visitor: &mut V, + withitem: &'a mut Withitem, +) { visitor.visit_expr(&mut withitem.context_expr); if let Some(expr) = &mut withitem.optional_vars { visitor.visit_expr(expr); } } -pub fn walk_match_case<'a, V: Visitor<'a> + ?Sized>( +pub(crate) fn walk_match_case<'a, V: Visitor<'a> + ?Sized>( visitor: &mut V, match_case: &'a mut MatchCase, ) { @@ -548,7 +557,7 @@ pub fn walk_match_case<'a, V: Visitor<'a> + ?Sized>( visitor.visit_body(&mut match_case.body); } -pub fn walk_pattern<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, pattern: &'a mut Pattern) { +pub(crate) fn walk_pattern<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, pattern: &'a mut Pattern) { match &mut pattern.node { PatternKind::MatchValue { value } => visitor.visit_expr(value), PatternKind::MatchSingleton { value } => visitor.visit_constant(value), @@ -595,23 +604,31 @@ pub fn walk_pattern<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, pattern: &'a m } #[allow(unused_variables)] -pub fn walk_expr_context<'a, V: Visitor<'a> + ?Sized>( +pub(crate) fn walk_expr_context<'a, V: Visitor<'a> + ?Sized>( visitor: &mut V, expr_context: &'a mut ExprContext, ) { } #[allow(unused_variables)] -pub fn walk_bool_op<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, bool_op: &'a mut BoolOp) {} +pub(crate) fn walk_bool_op<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, bool_op: &'a mut BoolOp) {} #[allow(unused_variables)] -pub fn walk_operator<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, operator: &'a mut Operator) {} +pub(crate) fn walk_operator<'a, V: Visitor<'a> + ?Sized>( + visitor: &mut V, + operator: &'a mut Operator, +) { +} #[allow(unused_variables)] -pub fn walk_unary_op<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, unary_op: &'a mut UnaryOp) {} +pub(crate) fn walk_unary_op<'a, V: Visitor<'a> + ?Sized>( + visitor: &mut V, + unary_op: &'a mut UnaryOp, +) { +} #[allow(unused_variables)] -pub fn walk_cmp_op<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, cmp_op: &'a mut CmpOp) {} +pub(crate) fn walk_cmp_op<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, cmp_op: &'a mut CmpOp) {} #[allow(unused_variables)] -pub fn walk_alias<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, alias: &'a mut Alias) {} +pub(crate) fn walk_alias<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, alias: &'a mut Alias) {} diff --git a/crates/ruff_python_formatter/src/format/builders.rs b/crates/ruff_python_formatter/src/format/builders.rs index d5bb00927d..3d663ddae3 100644 --- a/crates/ruff_python_formatter/src/format/builders.rs +++ b/crates/ruff_python_formatter/src/format/builders.rs @@ -8,7 +8,7 @@ use crate::shared_traits::AsFormat; use crate::trivia::{Relationship, TriviaKind}; #[derive(Copy, Clone)] -pub struct Block<'a> { +pub(crate) struct Block<'a> { body: &'a Body, } @@ -40,12 +40,12 @@ impl Format for Block<'_> { } #[inline] -pub fn block(body: &Body) -> Block { +pub(crate) fn block(body: &Body) -> Block { Block { body } } #[derive(Copy, Clone)] -pub struct Statements<'a> { +pub(crate) struct Statements<'a> { suite: &'a [Stmt], } @@ -61,12 +61,12 @@ impl Format for Statements<'_> { } } -pub fn statements(suite: &[Stmt]) -> Statements { +pub(crate) fn statements(suite: &[Stmt]) -> Statements { Statements { suite } } #[derive(Debug, Copy, Clone, Eq, PartialEq)] -pub struct Literal { +pub(crate) struct Literal { range: TextRange, } @@ -82,7 +82,7 @@ impl Format for Literal { } #[inline] -pub const fn literal(range: TextRange) -> Literal { +pub(crate) const fn literal(range: TextRange) -> Literal { Literal { range } } diff --git a/crates/ruff_python_formatter/src/format/comments.rs b/crates/ruff_python_formatter/src/format/comments.rs index 4fc40ac507..8aadf9a530 100644 --- a/crates/ruff_python_formatter/src/format/comments.rs +++ b/crates/ruff_python_formatter/src/format/comments.rs @@ -7,7 +7,7 @@ use crate::format::builders::literal; use crate::trivia::TriviaKind; #[derive(Debug)] -pub struct LeadingComments<'a, T> { +pub(crate) struct LeadingComments<'a, T> { item: &'a Attributed, } @@ -31,12 +31,12 @@ impl Format for LeadingComments<'_, T> { } #[inline] -pub const fn leading_comments(item: &Attributed) -> LeadingComments<'_, T> { +pub(crate) const fn leading_comments(item: &Attributed) -> LeadingComments<'_, T> { LeadingComments { item } } #[derive(Debug)] -pub struct TrailingComments<'a, T> { +pub(crate) struct TrailingComments<'a, T> { item: &'a Attributed, } @@ -60,12 +60,12 @@ impl Format for TrailingComments<'_, T> { } #[inline] -pub const fn trailing_comments(item: &Attributed) -> TrailingComments<'_, T> { +pub(crate) const fn trailing_comments(item: &Attributed) -> TrailingComments<'_, T> { TrailingComments { item } } #[derive(Debug)] -pub struct EndOfLineComments<'a, T> { +pub(crate) struct EndOfLineComments<'a, T> { item: &'a Attributed, } @@ -88,12 +88,12 @@ impl Format for EndOfLineComments<'_, T> { } #[inline] -pub const fn end_of_line_comments(item: &Attributed) -> EndOfLineComments<'_, T> { +pub(crate) const fn end_of_line_comments(item: &Attributed) -> EndOfLineComments<'_, T> { EndOfLineComments { item } } #[derive(Debug)] -pub struct DanglingComments<'a, T> { +pub(crate) struct DanglingComments<'a, T> { item: &'a Attributed, } @@ -113,6 +113,6 @@ impl Format for DanglingComments<'_, T> { } #[inline] -pub const fn dangling_comments(item: &Attributed) -> DanglingComments<'_, T> { +pub(crate) const fn dangling_comments(item: &Attributed) -> DanglingComments<'_, T> { DanglingComments { item } } diff --git a/crates/ruff_python_formatter/src/format/helpers.rs b/crates/ruff_python_formatter/src/format/helpers.rs index bd5bc1ff64..6678dc3dc9 100644 --- a/crates/ruff_python_formatter/src/format/helpers.rs +++ b/crates/ruff_python_formatter/src/format/helpers.rs @@ -1,6 +1,6 @@ use crate::cst::{Expr, ExprKind, UnaryOpKind}; -pub fn is_self_closing(expr: &Expr) -> bool { +pub(crate) fn is_self_closing(expr: &Expr) -> bool { match &expr.node { ExprKind::Tuple { .. } | ExprKind::List { .. } @@ -53,7 +53,7 @@ pub fn is_self_closing(expr: &Expr) -> bool { /// Return `true` if an [`Expr`] adheres to Black's definition of a non-complex /// expression, in the context of a slice operation. -pub fn is_simple_slice(expr: &Expr) -> bool { +pub(crate) fn is_simple_slice(expr: &Expr) -> bool { match &expr.node { ExprKind::UnaryOp { op, operand } => { if matches!(op.node, UnaryOpKind::Not) { @@ -70,7 +70,7 @@ pub fn is_simple_slice(expr: &Expr) -> bool { /// Return `true` if an [`Expr`] adheres to Black's definition of a non-complex /// expression, in the context of a power operation. -pub fn is_simple_power(expr: &Expr) -> bool { +pub(crate) fn is_simple_power(expr: &Expr) -> bool { match &expr.node { ExprKind::UnaryOp { op, operand } => { if matches!(op.node, UnaryOpKind::Not) { diff --git a/crates/ruff_python_formatter/src/format/mod.rs b/crates/ruff_python_formatter/src/format/mod.rs index 2263a33ba3..4605718f0e 100644 --- a/crates/ruff_python_formatter/src/format/mod.rs +++ b/crates/ruff_python_formatter/src/format/mod.rs @@ -2,7 +2,7 @@ mod alias; mod arg; mod arguments; mod bool_op; -pub mod builders; +pub(crate) mod builders; mod cmp_op; mod comments; mod comprehension; diff --git a/crates/ruff_python_formatter/src/format/numbers.rs b/crates/ruff_python_formatter/src/format/numbers.rs index 86f3b37c84..2b73e4a1dd 100644 --- a/crates/ruff_python_formatter/src/format/numbers.rs +++ b/crates/ruff_python_formatter/src/format/numbers.rs @@ -64,7 +64,7 @@ const fn float_atom(range: TextRange) -> FloatAtom { } #[derive(Debug, Copy, Clone, Eq, PartialEq)] -pub struct FloatLiteral { +pub(crate) struct FloatLiteral { range: TextRange, } @@ -109,12 +109,12 @@ impl Format for FloatLiteral { } #[inline] -pub const fn float_literal(range: TextRange) -> FloatLiteral { +pub(crate) const fn float_literal(range: TextRange) -> FloatLiteral { FloatLiteral { range } } #[derive(Debug, Copy, Clone, Eq, PartialEq)] -pub struct IntLiteral { +pub(crate) struct IntLiteral { range: TextRange, } @@ -156,12 +156,12 @@ impl Format for IntLiteral { } #[inline] -pub const fn int_literal(range: TextRange) -> IntLiteral { +pub(crate) const fn int_literal(range: TextRange) -> IntLiteral { IntLiteral { range } } #[derive(Debug, Copy, Clone, Eq, PartialEq)] -pub struct ComplexLiteral { +pub(crate) struct ComplexLiteral { range: TextRange, } @@ -190,6 +190,6 @@ impl Format for ComplexLiteral { } #[inline] -pub const fn complex_literal(range: TextRange) -> ComplexLiteral { +pub(crate) const fn complex_literal(range: TextRange) -> ComplexLiteral { ComplexLiteral { range } } diff --git a/crates/ruff_python_formatter/src/format/strings.rs b/crates/ruff_python_formatter/src/format/strings.rs index 1b9be52c31..40c3562d43 100644 --- a/crates/ruff_python_formatter/src/format/strings.rs +++ b/crates/ruff_python_formatter/src/format/strings.rs @@ -9,7 +9,7 @@ use crate::context::ASTFormatContext; use crate::cst::Expr; #[derive(Debug, Copy, Clone, Eq, PartialEq)] -pub struct StringLiteralPart { +pub(crate) struct StringLiteralPart { range: TextRange, } @@ -110,12 +110,12 @@ impl Format for StringLiteralPart { } #[inline] -pub const fn string_literal_part(range: TextRange) -> StringLiteralPart { +pub(crate) const fn string_literal_part(range: TextRange) -> StringLiteralPart { StringLiteralPart { range } } #[derive(Debug, Copy, Clone)] -pub struct StringLiteral<'a> { +pub(crate) struct StringLiteral<'a> { expr: &'a Expr, } @@ -159,7 +159,7 @@ impl Format for StringLiteral<'_> { } #[inline] -pub const fn string_literal(expr: &Expr) -> StringLiteral { +pub(crate) const fn string_literal(expr: &Expr) -> StringLiteral { StringLiteral { expr } } diff --git a/crates/ruff_python_formatter/src/newlines.rs b/crates/ruff_python_formatter/src/newlines.rs index 29164bec1e..01a731f61f 100644 --- a/crates/ruff_python_formatter/src/newlines.rs +++ b/crates/ruff_python_formatter/src/newlines.rs @@ -353,7 +353,7 @@ impl<'a> Visitor<'a> for ExprNormalizer { } } -pub fn normalize_newlines(python_cst: &mut [Stmt]) { +pub(crate) fn normalize_newlines(python_cst: &mut [Stmt]) { let mut normalizer = StmtNormalizer { depth: Depth::TopLevel, trailer: Trailer::None, diff --git a/crates/ruff_python_formatter/src/parentheses.rs b/crates/ruff_python_formatter/src/parentheses.rs index 752c7cfdf2..998517e142 100644 --- a/crates/ruff_python_formatter/src/parentheses.rs +++ b/crates/ruff_python_formatter/src/parentheses.rs @@ -191,7 +191,7 @@ impl<'a> Visitor<'a> for ParenthesesNormalizer<'_> { /// /// TODO(charlie): It's weird that we have both `TriviaKind::Parentheses` (which aren't used /// during formatting) and `Parenthesize` (which are used during formatting). -pub fn normalize_parentheses(python_cst: &mut [Stmt], locator: &Locator) { +pub(crate) fn normalize_parentheses(python_cst: &mut [Stmt], locator: &Locator) { let mut normalizer = ParenthesesNormalizer { locator }; for stmt in python_cst { normalizer.visit_stmt(stmt); diff --git a/crates/ruff_wasm/tests/api.rs b/crates/ruff_wasm/tests/api.rs index 02d4975154..fd2a70c4ff 100644 --- a/crates/ruff_wasm/tests/api.rs +++ b/crates/ruff_wasm/tests/api.rs @@ -1,12 +1,10 @@ #![cfg(target_arch = "wasm32")] -use js_sys; - -use wasm_bindgen_test::*; +use wasm_bindgen_test::wasm_bindgen_test; use ruff::registry::Rule; use ruff_python_ast::source_code::{OneIndexed, SourceLocation}; -use ruff_wasm::*; +use ruff_wasm::{check, ExpandedMessage}; macro_rules! check { ($source:expr, $config:expr, $expected:expr) => {{