Use interned strings when possible, for efficiency purposes (#14963)

Also, a number of unnecessary `.as_str()` calls have been removed for
clarity.

changelog: none
This commit is contained in:
llogiq 2025-06-04 05:16:22 +00:00 committed by GitHub
commit 84ef7fb414
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
28 changed files with 116 additions and 94 deletions

View file

@ -61,7 +61,7 @@ pub(super) fn check_clippy(cx: &EarlyContext<'_>, attr: &Attribute) {
fn check_deprecated_cfg_recursively(cx: &EarlyContext<'_>, attr: &rustc_ast::MetaItem) {
if let Some(ident) = attr.ident() {
if ["any", "all", "not"].contains(&ident.name.as_str()) {
if matches!(ident.name, sym::any | sym::all | sym::not) {
let Some(list) = attr.meta_item_list() else { return };
for item in list.iter().filter_map(|item| item.meta_item()) {
check_deprecated_cfg_recursively(cx, item);

View file

@ -61,7 +61,7 @@ fn is_used_as_unaligned(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
};
match parent.kind {
ExprKind::MethodCall(name, self_arg, ..) if self_arg.hir_id == e.hir_id => {
if matches!(name.ident.as_str(), "read_unaligned" | "write_unaligned")
if matches!(name.ident.name, sym::read_unaligned | sym::write_unaligned)
&& let Some(def_id) = cx.typeck_results().type_dependent_def_id(parent.hir_id)
&& let Some(def_id) = cx.tcx.impl_of_method(def_id)
&& cx.tcx.type_of(def_id).instantiate_identity().is_raw_ptr()

View file

@ -1,14 +1,13 @@
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::visitors::for_each_expr_without_closures;
use clippy_utils::{eq_expr_value, higher};
use clippy_utils::{eq_expr_value, higher, sym};
use core::ops::ControlFlow;
use rustc_errors::Diag;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::declare_lint_pass;
use rustc_span::edition::Edition::Edition2024;
use rustc_span::sym;
declare_clippy_lint! {
/// ### What it does
@ -94,7 +93,7 @@ fn mutex_lock_call<'tcx>(
op_mutex: Option<&'tcx Expr<'_>>,
) -> ControlFlow<&'tcx Expr<'tcx>> {
if let ExprKind::MethodCall(path, self_arg, [], _) = &expr.kind
&& path.ident.as_str() == "lock"
&& path.ident.name == sym::lock
&& let ty = cx.typeck_results().expr_ty(self_arg).peel_refs()
&& is_type_diagnostic_item(cx, ty, sym::Mutex)
&& op_mutex.is_none_or(|op| eq_expr_value(cx, self_arg, op))

View file

@ -3,7 +3,7 @@ use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
use clippy_utils::msrvs::{self, Msrv};
use clippy_utils::sugg::{Sugg, make_binop};
use clippy_utils::{
SpanlessEq, eq_expr_value, higher, is_in_const_context, is_integer_literal, peel_blocks, peel_blocks_with_stmt,
SpanlessEq, eq_expr_value, higher, is_in_const_context, is_integer_literal, peel_blocks, peel_blocks_with_stmt, sym,
};
use rustc_ast::ast::LitKind;
use rustc_data_structures::packed::Pu128;
@ -11,7 +11,7 @@ use rustc_errors::Applicability;
use rustc_hir::{AssignOpKind, BinOp, BinOpKind, Expr, ExprKind, QPath};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::impl_lint_pass;
use rustc_span::Span;
use rustc_span::{Span, Symbol};
declare_clippy_lint! {
/// ### What it does
@ -325,7 +325,7 @@ fn check_with_condition<'tcx>(
}
// Get the variable name
let var_name = ares_path.segments[0].ident.name.as_str();
let var_name = ares_path.segments[0].ident.name;
match cond_num_val.kind {
ExprKind::Lit(cond_lit) => {
// Check if the constant is zero
@ -337,7 +337,7 @@ fn check_with_condition<'tcx>(
}
},
ExprKind::Path(QPath::TypeRelative(_, name)) => {
if name.ident.as_str() == "MIN"
if name.ident.name == sym::MIN
&& let Some(const_id) = cx.typeck_results().type_dependent_def_id(cond_num_val.hir_id)
&& let Some(impl_id) = cx.tcx.impl_of_method(const_id)
&& let None = cx.tcx.impl_trait_ref(impl_id) // An inherent impl
@ -348,7 +348,7 @@ fn check_with_condition<'tcx>(
},
ExprKind::Call(func, []) => {
if let ExprKind::Path(QPath::TypeRelative(_, name)) = func.kind
&& name.ident.as_str() == "min_value"
&& name.ident.name == sym::min_value
&& let Some(func_id) = cx.typeck_results().type_dependent_def_id(func.hir_id)
&& let Some(impl_id) = cx.tcx.impl_of_method(func_id)
&& let None = cx.tcx.impl_trait_ref(impl_id) // An inherent impl
@ -383,7 +383,7 @@ fn subtracts_one<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<&'a Exp
}
}
fn print_lint_and_sugg(cx: &LateContext<'_>, var_name: &str, expr: &Expr<'_>) {
fn print_lint_and_sugg(cx: &LateContext<'_>, var_name: Symbol, expr: &Expr<'_>) {
span_lint_and_sugg(
cx,
IMPLICIT_SATURATING_SUB,

View file

@ -8,7 +8,7 @@ use clippy_utils::ty::implements_trait;
use clippy_utils::visitors::is_const_evaluatable;
use clippy_utils::{
MaybePath, eq_expr_value, is_diag_trait_item, is_in_const_context, is_trait_method, path_res, path_to_local_id,
peel_blocks, peel_blocks_with_stmt,
peel_blocks, peel_blocks_with_stmt, sym,
};
use itertools::Itertools;
use rustc_errors::{Applicability, Diag};
@ -18,7 +18,6 @@ use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::Ty;
use rustc_session::impl_lint_pass;
use rustc_span::Span;
use rustc_span::symbol::sym;
use std::cmp::Ordering;
use std::ops::Deref;
@ -299,9 +298,9 @@ fn is_max_min_pattern<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> O
&& (cx.typeck_results().expr_ty_adjusted(input).is_floating_point() || is_trait_method(cx, receiver, sym::Ord))
{
let is_float = cx.typeck_results().expr_ty_adjusted(input).is_floating_point();
let (min, max) = match (seg_first.ident.as_str(), seg_second.ident.as_str()) {
("min", "max") => (arg_second, arg_first),
("max", "min") => (arg_first, arg_second),
let (min, max) = match (seg_first.ident.name, seg_second.ident.name) {
(sym::min, sym::max) => (arg_second, arg_first),
(sym::max, sym::min) => (arg_first, arg_second),
_ => return None,
};
Some(ClampSuggestion {

View file

@ -1,11 +1,12 @@
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::sym;
use rustc_ast::LitKind;
use rustc_errors::Applicability::MachineApplicable;
use rustc_hir::{Expr, ExprKind, PathSegment, QPath, TyKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty;
use rustc_session::declare_lint_pass;
use rustc_span::{Span, sym};
use rustc_span::Span;
declare_clippy_lint! {
/// ### What it does
@ -89,9 +90,10 @@ fn warn_then_suggest(cx: &LateContext<'_>, span: Span) {
/// Tries to parse an expression as a method call, emitting the warning if necessary.
fn parse_method_call(cx: &LateContext<'_>, span: Span, path_segment: &PathSegment<'_>, receiver: &Expr<'_>) {
let ident = path_segment.ident.as_str();
let method_arg_kind = &receiver.kind;
if ["to_string", "to_owned", "into"].contains(&ident) && is_expr_kind_empty_str(method_arg_kind) {
if matches!(path_segment.ident.name, sym::to_string | sym::to_owned | sym::into)
&& is_expr_kind_empty_str(method_arg_kind)
{
warn_then_suggest(cx, span);
} else if let ExprKind::Call(func, [arg]) = method_arg_kind {
// If our first argument is a function call itself, it could be an `unwrap`-like function.

View file

@ -1,12 +1,11 @@
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_with_context;
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::{higher, is_res_lang_ctor};
use clippy_utils::{higher, is_res_lang_ctor, sym};
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind, LangItem, PatKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::declare_lint_pass;
use rustc_span::sym;
declare_clippy_lint! {
/// ### What it does
@ -57,7 +56,7 @@ impl<'tcx> LateLintPass<'tcx> for MatchResultOk {
if let ExprKind::MethodCall(ok_path, recv, [], ..) = let_expr.kind //check is expr.ok() has type Result<T,E>.ok(, _)
&& let PatKind::TupleStruct(ref pat_path, [ok_pat], _) = let_pat.kind //get operation
&& ok_path.ident.as_str() == "ok"
&& ok_path.ident.name == sym::ok
&& is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(recv), sym::Result)
&& is_res_lang_ctor(cx, cx.qpath_res(pat_path, let_pat.hir_id), LangItem::OptionSome)
&& let ctxt = expr.span.ctxt()

View file

@ -1,6 +1,7 @@
use std::ops::ControlFlow;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::sym;
use clippy_utils::ty::is_type_lang_item;
use rustc_ast::ast::LitKind;
use rustc_errors::Applicability;
@ -42,7 +43,7 @@ impl<'tcx> Visitor<'tcx> for MatchExprVisitor<'_, 'tcx> {
type Result = ControlFlow<CaseMethod>;
fn visit_expr(&mut self, ex: &'tcx Expr<'_>) -> Self::Result {
if let ExprKind::MethodCall(segment, receiver, [], _) = ex.kind {
let result = self.case_altered(segment.ident.as_str(), receiver);
let result = self.case_altered(segment.ident.name, receiver);
if result.is_break() {
return result;
}
@ -53,7 +54,7 @@ impl<'tcx> Visitor<'tcx> for MatchExprVisitor<'_, 'tcx> {
}
impl MatchExprVisitor<'_, '_> {
fn case_altered(&mut self, segment_ident: &str, receiver: &Expr<'_>) -> ControlFlow<CaseMethod> {
fn case_altered(&mut self, segment_ident: Symbol, receiver: &Expr<'_>) -> ControlFlow<CaseMethod> {
if let Some(case_method) = get_case_method(segment_ident) {
let ty = self.cx.typeck_results().expr_ty(receiver).peel_refs();
@ -66,12 +67,12 @@ impl MatchExprVisitor<'_, '_> {
}
}
fn get_case_method(segment_ident_str: &str) -> Option<CaseMethod> {
match segment_ident_str {
"to_lowercase" => Some(CaseMethod::LowerCase),
"to_ascii_lowercase" => Some(CaseMethod::AsciiLowerCase),
"to_uppercase" => Some(CaseMethod::UpperCase),
"to_ascii_uppercase" => Some(CaseMethod::AsciiUppercase),
fn get_case_method(segment_ident: Symbol) -> Option<CaseMethod> {
match segment_ident {
sym::to_lowercase => Some(CaseMethod::LowerCase),
sym::to_ascii_lowercase => Some(CaseMethod::AsciiLowerCase),
sym::to_uppercase => Some(CaseMethod::UpperCase),
sym::to_ascii_uppercase => Some(CaseMethod::AsciiUppercase),
_ => None,
}
}

View file

@ -46,7 +46,7 @@ pub(super) fn check<'tcx>(
if let ExprKind::Path(rustc_hir::QPath::Resolved(_, path)) = body_expr.kind
&& let [local_ident] = path.segments
&& local_ident.ident.as_str() == bound_ident.as_str()
&& local_ident.ident.name == bound_ident.name
{
span_lint_and_sugg(
cx,

View file

@ -72,9 +72,9 @@ fn is_min_or_max(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<MinMax> {
if let hir::ExprKind::Call(func, []) = &expr.kind
&& let hir::ExprKind::Path(hir::QPath::TypeRelative(_, segment)) = &func.kind
{
match segment.ident.as_str() {
"max_value" => return Some(MinMax::Max),
"min_value" => return Some(MinMax::Min),
match segment.ident.name {
sym::max_value => return Some(MinMax::Max),
sym::min_value => return Some(MinMax::Min),
_ => {},
}
}

View file

@ -44,11 +44,10 @@ pub(super) fn check<'tcx>(
if let ExprKind::MethodCall(name, _, args @ ([] | [_]), _) = parent.kind {
let mut app = Applicability::MachineApplicable;
let name = name.ident.as_str();
let collect_ty = cx.typeck_results().expr_ty(collect_expr);
let sugg: String = match name {
"len" => {
let sugg: String = match name.ident.name {
sym::len => {
if let Some(adt) = collect_ty.ty_adt_def()
&& matches!(
cx.tcx.get_diagnostic_name(adt.did()),
@ -60,13 +59,13 @@ pub(super) fn check<'tcx>(
return;
}
},
"is_empty"
sym::is_empty
if is_is_empty_sig(cx, parent.hir_id)
&& iterates_same_ty(cx, cx.typeck_results().expr_ty(iter_expr), collect_ty) =>
{
"next().is_none()".into()
},
"contains" => {
sym::contains => {
if is_contains_sig(cx, parent.hir_id, iter_expr)
&& let Some(arg) = args.first()
{

View file

@ -1,14 +1,14 @@
use rustc_data_structures::fx::FxHashMap;
use clippy_utils::diagnostics::{span_lint, span_lint_and_then};
use clippy_utils::paths;
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::{paths, sym};
use rustc_ast::ast::LitKind;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::LateContext;
use rustc_middle::ty::Ty;
use rustc_span::Span;
use rustc_span::source_map::Spanned;
use rustc_span::{Span, sym};
use super::{NONSENSICAL_OPEN_OPTIONS, SUSPICIOUS_OPEN_OPTIONS};
@ -87,23 +87,23 @@ fn get_open_options(
_ => Argument::Unknown,
};
match path.ident.as_str() {
"create" => {
match path.ident.name {
sym::create => {
options.push((OpenOption::Create, argument_option, span));
},
"create_new" => {
sym::create_new => {
options.push((OpenOption::CreateNew, argument_option, span));
},
"append" => {
sym::append => {
options.push((OpenOption::Append, argument_option, span));
},
"truncate" => {
sym::truncate => {
options.push((OpenOption::Truncate, argument_option, span));
},
"read" => {
sym::read => {
options.push((OpenOption::Read, argument_option, span));
},
"write" => {
sym::write => {
options.push((OpenOption::Write, argument_option, span));
},
_ => {

View file

@ -285,9 +285,9 @@ fn parse_iter_usage<'tcx>(
let did = cx.typeck_results().type_dependent_def_id(e.hir_id)?;
let iter_id = cx.tcx.get_diagnostic_item(sym::Iterator)?;
match (name.ident.as_str(), args) {
("next", []) if cx.tcx.trait_of_item(did) == Some(iter_id) => (IterUsageKind::Nth(0), e.span),
("next_tuple", []) => {
match (name.ident.name, args) {
(sym::next, []) if cx.tcx.trait_of_item(did) == Some(iter_id) => (IterUsageKind::Nth(0), e.span),
(sym::next_tuple, []) => {
return if paths::ITERTOOLS_NEXT_TUPLE.matches(cx, did)
&& let ty::Adt(adt_def, subs) = cx.typeck_results().expr_ty(e).kind()
&& cx.tcx.is_diagnostic_item(sym::Option, adt_def.did())
@ -303,7 +303,7 @@ fn parse_iter_usage<'tcx>(
None
};
},
("nth" | "skip", [idx_expr]) if cx.tcx.trait_of_item(did) == Some(iter_id) => {
(sym::nth | sym::skip, [idx_expr]) if cx.tcx.trait_of_item(did) == Some(iter_id) => {
if let Some(Constant::Int(idx)) = ConstEvalCtxt::new(cx).eval(idx_expr) {
let span = if name.ident.as_str() == "nth" {
e.span

View file

@ -47,7 +47,7 @@ impl EarlyLintPass for MultipleBoundLocations {
for param in &generics.params {
if !param.bounds.is_empty() {
generic_params_with_bounds.insert(param.ident.name.as_str(), param.ident.span);
generic_params_with_bounds.insert(param.ident.as_str(), param.ident.span);
}
}
for clause in &generics.where_clause.predicates {
@ -64,7 +64,7 @@ impl EarlyLintPass for MultipleBoundLocations {
},
WherePredicateKind::RegionPredicate(pred) => {
if !pred.bounds.is_empty()
&& let Some(bound_span) = generic_params_with_bounds.get(&pred.lifetime.ident.name.as_str())
&& let Some(bound_span) = generic_params_with_bounds.get(&pred.lifetime.ident.as_str())
{
emit_lint(cx, *bound_span, pred.lifetime.ident.span);
}

View file

@ -1,14 +1,14 @@
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::path_to_local_id;
use clippy_utils::source::{SpanRangeExt, snippet};
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::{path_to_local_id, sym};
use rustc_ast::{LitKind, StrStyle};
use rustc_errors::Applicability;
use rustc_hir::def::Res;
use rustc_hir::{BindingMode, Block, Expr, ExprKind, HirId, LetStmt, PatKind, QPath, Stmt, StmtKind, TyKind};
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_session::impl_lint_pass;
use rustc_span::{Span, Symbol, sym};
use rustc_span::{Span, Symbol};
declare_clippy_lint! {
/// ### What it does
@ -177,7 +177,7 @@ impl<'tcx> LateLintPass<'tcx> for PathbufThenPush<'tcx> {
&& let StmtKind::Expr(expr) | StmtKind::Semi(expr) = stmt.kind
&& let ExprKind::MethodCall(name, self_arg, [arg_expr], _) = expr.kind
&& path_to_local_id(self_arg, searcher.local_id)
&& name.ident.as_str() == "push"
&& name.ident.name == sym::push
{
searcher.err_span = searcher.err_span.to(stmt.span);
searcher.arg = Some(*arg_expr);

View file

@ -2,7 +2,7 @@ use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then, span_lin
use clippy_utils::source::SpanRangeExt;
use clippy_utils::sugg::Sugg;
use clippy_utils::visitors::contains_unsafe_block;
use clippy_utils::{get_expr_use_or_unification_node, is_lint_allowed, path_def_id, path_to_local, std_or_core};
use clippy_utils::{get_expr_use_or_unification_node, is_lint_allowed, path_def_id, path_to_local, std_or_core, sym};
use hir::LifetimeKind;
use rustc_abi::ExternAbi;
use rustc_errors::{Applicability, MultiSpan};
@ -18,8 +18,8 @@ use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::hir::nested_filter;
use rustc_middle::ty::{self, Binder, ClauseKind, ExistentialPredicate, List, PredicateKind, Ty};
use rustc_session::declare_lint_pass;
use rustc_span::Span;
use rustc_span::symbol::Symbol;
use rustc_span::{Span, sym};
use rustc_trait_selection::infer::InferCtxtExt as _;
use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
use std::{fmt, iter};
@ -299,7 +299,7 @@ struct PtrArg<'tcx> {
emission_id: HirId,
span: Span,
ty_name: Symbol,
method_renames: &'static [(&'static str, &'static str)],
method_renames: &'static [(Symbol, &'static str)],
ref_prefix: RefPrefix,
deref_ty: DerefTy<'tcx>,
}
@ -385,6 +385,7 @@ impl<'tcx> DerefTy<'tcx> {
}
}
#[expect(clippy::too_many_lines)]
fn check_fn_args<'cx, 'tcx: 'cx>(
cx: &'cx LateContext<'tcx>,
fn_sig: ty::FnSig<'tcx>,
@ -409,7 +410,7 @@ fn check_fn_args<'cx, 'tcx: 'cx>(
let emission_id = params.get(i).map_or(hir_ty.hir_id, |param| param.hir_id);
let (method_renames, deref_ty) = match cx.tcx.get_diagnostic_name(adt.did()) {
Some(sym::Vec) => (
[("clone", ".to_owned()")].as_slice(),
[(sym::clone, ".to_owned()")].as_slice(),
DerefTy::Slice(
name.args.and_then(|args| args.args.first()).and_then(|arg| {
if let GenericArg::Type(ty) = arg {
@ -421,10 +422,14 @@ fn check_fn_args<'cx, 'tcx: 'cx>(
args.type_at(0),
),
),
_ if Some(adt.did()) == cx.tcx.lang_items().string() => {
([("clone", ".to_owned()"), ("as_str", "")].as_slice(), DerefTy::Str)
},
Some(sym::PathBuf) => ([("clone", ".to_path_buf()"), ("as_path", "")].as_slice(), DerefTy::Path),
_ if Some(adt.did()) == cx.tcx.lang_items().string() => (
[(sym::clone, ".to_owned()"), (sym::as_str, "")].as_slice(),
DerefTy::Str,
),
Some(sym::PathBuf) => (
[(sym::clone, ".to_path_buf()"), (sym::as_path, "")].as_slice(),
DerefTy::Path,
),
Some(sym::Cow) if mutability == Mutability::Not => {
if let Some((lifetime, ty)) = name.args.and_then(|args| {
if let [GenericArg::Lifetime(lifetime), ty] = args.args {
@ -595,7 +600,7 @@ fn check_ptr_arg_usage<'tcx>(cx: &LateContext<'tcx>, body: &Body<'tcx>, args: &[
if let ExprKind::MethodCall(name, receiver, ..) = use_expr.kind
&& receiver.hir_id == child_id
{
let name = name.ident.as_str();
let name = name.ident.name;
// Check if the method can be renamed.
if let Some((_, replacement)) = args.method_renames.iter().find(|&&(x, _)| x == name) {

View file

@ -1,7 +1,7 @@
use clippy_utils::diagnostics::{span_lint_hir, span_lint_hir_and_then};
use clippy_utils::get_enclosing_block;
use clippy_utils::higher::{VecInitKind, get_vec_init_kind};
use clippy_utils::source::snippet;
use clippy_utils::{get_enclosing_block, sym};
use hir::{Expr, ExprKind, HirId, LetStmt, PatKind, PathSegment, QPath, StmtKind};
use rustc_errors::Applicability;
@ -87,7 +87,7 @@ impl<'tcx> LateLintPass<'tcx> for ReadZeroByteVec {
diag.span_suggestion(
expr.span,
"try",
format!("{}.resize({len}, 0); {}", ident.as_str(), snippet(cx, expr.span, "..")),
format!("{}.resize({len}, 0); {}", ident, snippet(cx, expr.span, "..")),
applicability,
);
},
@ -106,7 +106,7 @@ impl<'tcx> LateLintPass<'tcx> for ReadZeroByteVec {
"try",
format!(
"{}.resize({}, 0); {}",
ident.as_str(),
ident,
snippet(cx, e.span, ".."),
snippet(cx, expr.span, "..")
),
@ -142,8 +142,8 @@ impl<'tcx> Visitor<'tcx> for ReadVecVisitor<'tcx> {
if let ExprKind::MethodCall(path, receiver, args, _) = e.kind {
let PathSegment { ident, .. } = *path;
match ident.as_str() {
"read" | "read_exact" => {
match ident.name {
sym::read | sym::read_exact => {
let [arg] = args else { return };
if let ExprKind::AddrOf(_, hir::Mutability::Mut, inner) = arg.kind
&& let ExprKind::Path(QPath::Resolved(None, inner_path)) = inner.kind
@ -155,7 +155,7 @@ impl<'tcx> Visitor<'tcx> for ReadVecVisitor<'tcx> {
return;
}
},
"resize" => {
sym::resize => {
// If the Vec is resized, then it's a valid read
if let ExprKind::Path(QPath::Resolved(_, inner_path)) = receiver.kind
&& let Res::Local(res_id) = inner_path.res

View file

@ -1,7 +1,7 @@
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::higher::{VecInitKind, get_vec_init_kind};
use clippy_utils::source::snippet;
use clippy_utils::{is_from_proc_macro, path_to_local_id};
use clippy_utils::{is_from_proc_macro, path_to_local_id, sym};
use rustc_errors::Applicability;
use rustc_hir::def::Res;
use rustc_hir::{BindingMode, Block, Expr, ExprKind, HirId, LetStmt, PatKind, QPath, Stmt, StmtKind};
@ -126,7 +126,7 @@ impl<'tcx> LateLintPass<'tcx> for ReserveAfterInitialization {
if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = stmt.kind
&& let ExprKind::MethodCall(name, self_arg, [space_hint], _) = expr.kind
&& path_to_local_id(self_arg, searcher.local_id)
&& name.ident.as_str() == "reserve"
&& name.ident.name == sym::reserve
&& !is_from_proc_macro(cx, expr)
{
self.searcher = Some(VecReserveSearcher {

View file

@ -1,5 +1,5 @@
use clippy_utils::diagnostics::span_lint;
use clippy_utils::paths;
use clippy_utils::{paths, sym};
use rustc_hir::{Impl, Item, ItemKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::declare_lint_pass;
@ -36,9 +36,9 @@ impl<'tcx> LateLintPass<'tcx> for SerdeApi {
let mut seen_str = None;
let mut seen_string = None;
for item in *items {
match item.ident.as_str() {
"visit_str" => seen_str = Some(item.span),
"visit_string" => seen_string = Some(item.span),
match item.ident.name {
sym::visit_str => seen_str = Some(item.span),
sym::visit_string => seen_string = Some(item.span),
_ => {},
}
}

View file

@ -560,7 +560,7 @@ impl<'tcx> LateLintPass<'tcx> for TrimSplitWhitespace {
&& let Some(split_ws_def_id) = tyckres.type_dependent_def_id(expr.hir_id)
&& cx.tcx.is_diagnostic_item(sym::str_split_whitespace, split_ws_def_id)
&& let ExprKind::MethodCall(path, _trim_recv, [], trim_span) = split_recv.kind
&& let trim_fn_name @ ("trim" | "trim_start" | "trim_end") = path.ident.name.as_str()
&& let trim_fn_name @ (sym::trim | sym::trim_start | sym::trim_end) = path.ident.name
&& let Some(trim_def_id) = tyckres.type_dependent_def_id(split_recv.hir_id)
&& is_one_of_trim_diagnostic_items(cx, trim_def_id)
{

View file

@ -74,7 +74,7 @@ pub(super) fn check<'tcx>(
last.ident.span.with_hi(path.span.hi()),
"transmute used without annotations",
"consider adding missing annotations",
format!("{}::<{from_ty}, {to_ty}>", last.ident.as_str()),
format!("{}::<{from_ty}, {to_ty}>", last.ident),
Applicability::MaybeIncorrect,
);
true

View file

@ -33,7 +33,7 @@ pub(super) fn check(cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, lt: &Lifetime, m
let ltopt = if lt.is_anonymous() {
String::new()
} else {
format!("{} ", lt.ident.as_str())
format!("{} ", lt.ident)
};
if mut_ty.mutbl == Mutability::Mut {

View file

@ -1,11 +1,11 @@
use clippy_utils::diagnostics::span_lint_hir_and_then;
use clippy_utils::macros::{is_panic, root_macro_call_first_node};
use clippy_utils::{is_res_lang_ctor, paths, peel_blocks};
use clippy_utils::{is_res_lang_ctor, paths, peel_blocks, sym};
use hir::{ExprKind, HirId, PatKind};
use rustc_hir as hir;
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::declare_lint_pass;
use rustc_span::{Span, sym};
use rustc_span::Span;
declare_clippy_lint! {
/// ### What it does
@ -232,8 +232,16 @@ fn is_unreachable_or_panic(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
fn unpack_call_chain<'a>(mut expr: &'a hir::Expr<'a>) -> &'a hir::Expr<'a> {
while let ExprKind::MethodCall(path, receiver, ..) = expr.kind {
if matches!(
path.ident.as_str(),
"unwrap" | "expect" | "unwrap_or" | "unwrap_or_else" | "ok" | "is_ok" | "is_err" | "or_else" | "or"
path.ident.name,
sym::unwrap
| sym::expect
| sym::unwrap_or
| sym::unwrap_or_else
| sym::ok
| sym::is_ok
| sym::is_err
| sym::or_else
| sym::or
) {
expr = receiver;
} else {

View file

@ -1,11 +1,11 @@
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_with_context;
use clippy_utils::sym;
use clippy_utils::ty::is_type_diagnostic_item;
use rustc_errors::Applicability;
use rustc_hir::{ExprKind, Stmt, StmtKind};
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_session::declare_lint_pass;
use rustc_span::sym;
declare_clippy_lint! {
/// ### What it does
@ -36,7 +36,7 @@ impl LateLintPass<'_> for UnusedResultOk {
fn check_stmt(&mut self, cx: &LateContext<'_>, stmt: &Stmt<'_>) {
if let StmtKind::Semi(expr) = stmt.kind
&& let ExprKind::MethodCall(ok_path, recv, [], ..) = expr.kind //check is expr.ok() has type Result<T,E>.ok(, _)
&& ok_path.ident.as_str() == "ok"
&& ok_path.ident.name == sym::ok
&& is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(recv), sym::Result)
&& !stmt.span.in_external_macro(cx.sess().source_map())
{

View file

@ -100,7 +100,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedUnit {
let segments = &poly.trait_ref.path.segments;
if segments.len() == 1
&& ["Fn", "FnMut", "FnOnce"].contains(&segments[0].ident.name.as_str())
&& matches!(segments[0].ident.name, sym::Fn | sym::FnMut | sym::FnOnce)
&& let Some(args) = segments[0].args
&& args.parenthesized == GenericArgsParentheses::ParenSugar
&& let constraints = &args.constraints

View file

@ -2,7 +2,7 @@ use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::higher::{VecInitKind, get_vec_init_kind};
use clippy_utils::source::snippet;
use clippy_utils::visitors::for_each_local_use_after_expr;
use clippy_utils::{get_parent_expr, path_to_local_id};
use clippy_utils::{get_parent_expr, path_to_local_id, sym};
use core::ops::ControlFlow;
use rustc_errors::Applicability;
use rustc_hir::def::Res;
@ -202,7 +202,7 @@ impl<'tcx> LateLintPass<'tcx> for VecInitThenPush {
if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = stmt.kind
&& let ExprKind::MethodCall(name, self_arg, [_], _) = expr.kind
&& path_to_local_id(self_arg, searcher.local_id)
&& name.ident.as_str() == "push"
&& name.ident.name == sym::push
{
self.searcher = Some(VecPushSearcher {
err_span: searcher.err_span.to(stmt.span),

View file

@ -9,8 +9,8 @@ use rustc_hir::{Item, ItemKind, PathSegment, UseKind};
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_middle::ty;
use rustc_session::impl_lint_pass;
use rustc_span::BytePos;
use rustc_span::symbol::kw;
use rustc_span::{BytePos, sym};
declare_clippy_lint! {
/// ### What it does
@ -193,9 +193,7 @@ impl WildcardImports {
// Allow "...prelude::..::*" imports.
// Many crates have a prelude, and it is imported as a glob by design.
fn is_prelude_import(segments: &[PathSegment<'_>]) -> bool {
segments
.iter()
.any(|ps| ps.ident.as_str().contains(sym::prelude.as_str()))
segments.iter().any(|ps| ps.ident.as_str().contains("prelude"))
}
// Allow "super::*" imports in tests.

View file

@ -84,6 +84,7 @@ generate! {
as_deref,
as_deref_mut,
as_mut,
as_path,
assert_failed,
author,
borrow,
@ -121,6 +122,8 @@ generate! {
copy_to,
copy_to_nonoverlapping,
count_ones,
create,
create_new,
cycle,
cyclomatic_complexity,
de,
@ -256,9 +259,12 @@ generate! {
powi,
product,
push,
read,
read_exact,
read_line,
read_to_end,
read_to_string,
read_unaligned,
redundant_pub_crate,
regex,
rem_euclid,
@ -338,8 +344,11 @@ generate! {
to_uppercase,
tokio,
trim,
trim_end,
trim_end_matches,
trim_start,
trim_start_matches,
truncate,
unreachable_pub,
unsafe_removed_from_name,
unused,
@ -354,12 +363,15 @@ generate! {
unwrap_unchecked,
unzip,
utils,
visit_str,
visit_string,
wake,
warnings,
wildcard_imports,
with_capacity,
wrapping_offset,
write,
write_unaligned,
writeln,
zip,
}