Skip to content

Use CompactStr #9229

New issue

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

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

Already on GitHub? Sign in to your account

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ bitflags = { version = "2.4.1" }
chrono = { version = "0.4.31", default-features = false, features = ["clock"] }
clap = { version = "4.4.7", features = ["derive"] }
colored = { version = "2.0.0" }
compact_str = "0.7.1"
filetime = { version = "0.2.23" }
glob = { version = "0.3.1" }
globset = { version = "0.4.14" }
Expand Down
8 changes: 4 additions & 4 deletions crates/ruff_linter/src/checkers/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -844,7 +844,7 @@ where
range: _,
}) => {
if let Expr::Name(ast::ExprName { id, ctx, range: _ }) = func.as_ref() {
if id == "locals" && ctx.is_load() {
if *id == "locals" && ctx.is_load() {
Copy link
Member Author

@MichaReiser MichaReiser Dec 21, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I find this annoying. Not sure why &CompactStr == &'static str doesn't work.

@BurntSushi probably knows why

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure off the top of my head, so let's run through it. x == y is syntactic sugar for std::cmp::PartialEq::eq(&x, &y). If id is a &CompactString and y is a &'static str, then &x is actually an &&CompactString and y is actually a &&str. So I believe this means we need to look for a PartialEq impl for &&CompactString (notice the double & there).

The only PartialEq impl for CompactString is impl<T: AsRef<str>> PartialEq<T> for CompactString, which on its own does not fit here because we're looking for &&CompactString.

At least, I think that's why. It's possible the compact-str crate could add more impls to alleviate this. But maybe not.

Auto-deref also comes into the picture here. See:

let scope = self.semantic.current_scope_mut();
scope.set_uses_locals();
}
Expand Down Expand Up @@ -1702,21 +1702,21 @@ impl<'a> Checker<'a> {
&& match parent {
Stmt::Assign(ast::StmtAssign { targets, .. }) => {
if let Some(Expr::Name(ast::ExprName { id, .. })) = targets.first() {
id == "__all__"
*id == "__all__"
} else {
false
}
}
Stmt::AugAssign(ast::StmtAugAssign { target, .. }) => {
if let Expr::Name(ast::ExprName { id, .. }) = target.as_ref() {
id == "__all__"
*id == "__all__"
} else {
false
}
}
Stmt::AnnAssign(ast::StmtAnnAssign { target, .. }) => {
if let Expr::Name(ast::ExprName { id, .. }) = target.as_ref() {
id == "__all__"
*id == "__all__"
} else {
false
}
Expand Down
2 changes: 1 addition & 1 deletion crates/ruff_linter/src/checkers/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ fn extract_import_map(path: &Path, package: Option<&Path>, blocks: &[&Block]) ->
}) => {
let level = level.unwrap_or_default() as usize;
let module = if let Some(module) = module {
let module: &String = module.as_ref();
let module = module.as_str();
if level == 0 {
Cow::Borrowed(module)
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ pub(crate) fn variable_name_task_id(
let ast::ExprStringLiteral { value: task_id, .. } = keyword.value.as_string_literal_expr()?;

// If the target name is the same as the task_id, no violation.
if task_id == id {
if task_id == id.as_str() {
return None;
}

Expand Down
2 changes: 1 addition & 1 deletion crates/ruff_linter/src/rules/flake8_annotations/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ impl AutoPythonType {
)
.ok()?;
let expr = Expr::Name(ast::ExprName {
id: binding,
id: binding.into(),
range: TextRange::default(),
ctx: ExprContext::Load,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ pub(crate) fn jinja2_autoescape_false(checker: &mut Checker, call: &ast::ExprCal
Expr::BooleanLiteral(ast::ExprBooleanLiteral { value: true, .. }) => (),
Expr::Call(ast::ExprCall { func, .. }) => {
if let Expr::Name(ast::ExprName { id, .. }) = func.as_ref() {
if id != "select_autoescape" {
if *id != "select_autoescape" {
checker.diagnostics.push(Diagnostic::new(
Jinja2AutoescapeFalse { value: true },
keyword.range(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ pub(crate) fn blind_except(
if let Stmt::Raise(ast::StmtRaise { exc, .. }) = stmt {
if let Some(exc) = exc {
if let Expr::Name(ast::ExprName { id, .. }) = exc.as_ref() {
name.is_some_and(|name| id == name)
name.is_some_and(|name| *id == name)
} else {
false
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ pub(crate) fn boolean_type_hint_positional_argument(
fn match_annotation_to_literal_bool(annotation: &Expr) -> bool {
match annotation {
// Ex) `True`
Expr::Name(name) => &name.id == "bool",
Expr::Name(name) => name.id == "bool",
// Ex) `"True"`
Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) => value == "bool",
_ => false,
Expand All @@ -176,7 +176,7 @@ fn match_annotation_to_literal_bool(annotation: &Expr) -> bool {
fn match_annotation_to_complex_bool(annotation: &Expr, semantic: &SemanticModel) -> bool {
match annotation {
// Ex) `bool`
Expr::Name(name) => &name.id == "bool",
Expr::Name(name) => name.id == "bool",
// Ex) `"bool"`
Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) => value == "bool",
// Ex) `bool | int`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ pub(crate) fn assignment_to_os_environ(checker: &mut Checker, targets: &[Expr])
let Expr::Name(ast::ExprName { id, .. }) = value.as_ref() else {
return;
};
if id != "os" {
if *id != "os" {
return;
}
checker
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ pub(crate) fn cached_instance_method(checker: &mut Checker, decorator_list: &[De
// TODO(charlie): This should take into account `classmethod-decorators` and
// `staticmethod-decorators`.
if let Expr::Name(ast::ExprName { id, .. }) = &decorator.expression {
if id == "classmethod" || id == "staticmethod" {
if *id == "classmethod" || *id == "staticmethod" {
return;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ impl<'a> Visitor<'a> for SuspiciousVariablesVisitor<'a> {
Expr::Attribute(ast::ExprAttribute { value, attr, .. }) => {
if attr == "reduce" {
if let Expr::Name(ast::ExprName { id, .. }) = value.as_ref() {
if id == "functools" {
if *id == "functools" {
for arg in args {
if arg.is_lambda_expr() {
self.safe_functions.push(arg);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ pub(crate) fn getattr_with_constant(
let Expr::Name(ast::ExprName { id, .. }) = func else {
return;
};
if id != "getattr" {
if *id != "getattr" {
return;
}
let [obj, arg] = args else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ pub(crate) fn raise_without_from_inside_except(
if let Some(name) = name {
if exc
.as_name_expr()
.is_some_and(|ast::ExprName { id, .. }| name == id)
.is_some_and(|ast::ExprName { id, .. }| name == id.as_str())
{
continue;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ impl<'a> GroupNameFinder<'a> {

fn name_matches(&self, expr: &Expr) -> bool {
if let Expr::Name(ast::ExprName { id, .. }) = expr {
id == self.group_name
*id == self.group_name
} else {
false
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ pub(crate) fn setattr_with_constant(
let Expr::Name(ast::ExprName { id, .. }) = func else {
return;
};
if id != "setattr" {
if *id != "setattr" {
return;
}
let [obj, name, value] = args else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ pub(crate) fn unintentional_type_annotation(
}
Expr::Attribute(ast::ExprAttribute { value, .. }) => {
if let Expr::Name(ast::ExprName { id, .. }) = value.as_ref() {
if id != "self" {
if *id != "self" {
checker
.diagnostics
.push(Diagnostic::new(UnintentionalTypeAnnotation, stmt.range()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ pub(crate) fn unreliable_callable_check(
}

let mut diagnostic = Diagnostic::new(UnreliableCallableCheck, expr.range());
if id == "hasattr" {
if *id == "hasattr" {
if checker.semantic().is_builtin("callable") {
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
format!("callable({})", checker.locator().slice(obj)),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ impl AlwaysFixableViolation for ZipWithoutExplicitStrict {
/// B905
pub(crate) fn zip_without_explicit_strict(checker: &mut Checker, call: &ast::ExprCall) {
if let Expr::Name(ast::ExprName { id, .. }) = call.func.as_ref() {
if id == "zip"
if *id == "zip"
&& checker.semantic().is_builtin("zip")
&& call.arguments.find_keyword("strict").is_none()
&& !call
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ pub(crate) fn all_with_model_form(checker: &mut Checker, class_def: &ast::StmtCl
let Expr::Name(ast::ExprName { id, .. }) = target else {
continue;
};
if id != "fields" {
if *id != "fields" {
continue;
}
match value.as_ref() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ pub(crate) fn exclude_with_model_form(checker: &mut Checker, class_def: &ast::St
let Expr::Name(ast::ExprName { id, .. }) = target else {
continue;
};
if id == "exclude" {
if *id == "exclude" {
checker
.diagnostics
.push(Diagnostic::new(DjangoExcludeWithModelForm, target.range()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ fn is_model_abstract(class_def: &ast::StmtClassDef) -> bool {
let Expr::Name(ast::ExprName { id, .. }) = target else {
continue;
};
if id != "abstract" {
if *id != "abstract" {
continue;
}
if !is_const_true(value) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ fn get_element_type(element: &Stmt, semantic: &SemanticModel) -> Option<ContentT
let Expr::Name(ast::ExprName { id, .. }) = expr else {
return None;
};
if id == "objects" {
if *id == "objects" {
Some(ContentType::ManagerDeclaration)
} else {
None
Expand Down
4 changes: 3 additions & 1 deletion crates/ruff_linter/src/rules/flake8_gettext/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ pub mod settings;
/// Returns true if the [`Expr`] is an internationalization function call.
pub(crate) fn is_gettext_func_call(func: &Expr, functions_names: &[String]) -> bool {
if let Expr::Name(ast::ExprName { id, .. }) = func {
functions_names.contains(id)
functions_names
.iter()
.any(|function_name| function_name == id)
} else {
false
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ pub(crate) fn unnecessary_range_start(checker: &mut Checker, call: &ast::ExprCal
let Expr::Name(ast::ExprName { id, .. }) = call.func.as_ref() else {
return;
};
if id != "range" {
if *id != "range" {
return;
};
if !checker.semantic().is_builtin("range") {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ fn make_literal_expr(subscript: Option<Expr>, exprs: Vec<&Expr>) -> Expr {
subscript.unwrap().clone()
} else {
Expr::Name(ast::ExprName {
id: "Literal".to_string(),
id: "Literal".into(),
range: TextRange::default(),
ctx: ast::ExprContext::Load,
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ pub(crate) fn unnecessary_type_union<'a>(checker: &mut Checker, union: &'a Expr)
.into_iter()
.map(|type_member| {
Expr::Name(ast::ExprName {
id: type_member,
id: type_member.into(),
ctx: ExprContext::Load,
range: TextRange::default(),
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,8 @@ pub(crate) fn private_member_access(checker: &mut Checker, expr: &Expr) {
.settings
.flake8_self
.ignore_names
.contains(attr.as_ref())
.iter()
.any(|name| name == attr.as_str())
{
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,7 @@ fn isinstance_target<'a>(call: &'a Expr, semantic: &'a SemanticModel) -> Option<
let Expr::Name(ast::ExprName { id: func_name, .. }) = func.as_ref() else {
return None;
};
if func_name != "isinstance" {
if *func_name != "isinstance" {
return None;
}
if !semantic.is_builtin("isinstance") {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ fn check_os_environ_subscript(checker: &mut Checker, expr: &Expr) {
let Expr::Name(ast::ExprName { id, .. }) = attr_value.as_ref() else {
return;
};
if id != "os" || attr != "environ" {
if *id != "os" || attr != "environ" {
return;
}
let Expr::StringLiteral(ast::ExprStringLiteral { value: env_var, .. }) = slice.as_ref() else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ fn is_main_check(expr: &Expr) -> bool {
}) = expr
{
if let Expr::Name(ast::ExprName { id, .. }) = left.as_ref() {
if id == "__name__" {
if *id == "__name__" {
if let [Expr::StringLiteral(ast::ExprStringLiteral { value, .. })] =
comparators.as_slice()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ fn is_empty_stmt(stmt: &Stmt) -> bool {
if let Some(exc) = exc {
match exc.as_ref() {
Expr::Name(ast::ExprName { id, .. }) => {
return id == "NotImplementedError" || id == "NotImplemented";
return *id == "NotImplementedError" || *id == "NotImplemented";
}
Expr::Call(ast::ExprCall { func, .. }) => {
if let Expr::Name(ast::ExprName { id, .. }) = func.as_ref() {
return id == "NotImplementedError" || id == "NotImplemented";
return *id == "NotImplementedError" || *id == "NotImplemented";
}
}
_ => {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ pub(crate) fn assignment_to_df(targets: &[Expr]) -> Option<Diagnostic> {
let Expr::Name(ast::ExprName { id, .. }) = target else {
return None;
};
if id != "df" {
if *id != "df" {
return None;
}
Some(Diagnostic::new(PandasDfVariableName, target.range()))
Expand Down
2 changes: 1 addition & 1 deletion crates/ruff_linter/src/rules/pandas_vet/rules/pd_merge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ impl Violation for PandasUseOfPdMerge {
pub(crate) fn use_of_pd_merge(checker: &mut Checker, func: &Expr) {
if let Expr::Attribute(ast::ExprAttribute { attr, value, .. }) = func {
if let Expr::Name(ast::ExprName { id, .. }) = value.as_ref() {
if id == "pd" && attr == "merge" {
if *id == "pd" && attr == "merge" {
checker
.diagnostics
.push(Diagnostic::new(PandasUseOfPdMerge, func.range()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ pub(crate) fn error_suffix_on_exception_name(
if !arguments.is_some_and(|arguments| {
arguments.args.iter().any(|base| {
if let Expr::Name(ast::ExprName { id, .. }) = &base {
id == "Exception" || id.ends_with("Error")
*id == "Exception" || id.ends_with("Error")
} else {
false
}
Expand Down
Loading