Skip to content

Commit

Permalink
Remove more instances of snippet_opt.
Browse files Browse the repository at this point in the history
  • Loading branch information
Jarcho committed Aug 11, 2024
1 parent 9afab36 commit 7f589a6
Show file tree
Hide file tree
Showing 20 changed files with 107 additions and 93 deletions.
4 changes: 2 additions & 2 deletions clippy_lints/src/attrs/empty_line_after.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::{EMPTY_LINE_AFTER_DOC_COMMENTS, EMPTY_LINE_AFTER_OUTER_ATTR};
use clippy_utils::diagnostics::span_lint;
use clippy_utils::source::{is_present_in_source, snippet_opt, without_block_comments};
use clippy_utils::source::{is_present_in_source, without_block_comments, SpanRangeExt};
use rustc_ast::{AttrKind, AttrStyle};
use rustc_lint::EarlyContext;
use rustc_span::Span;
Expand All @@ -26,7 +26,7 @@ pub(super) fn check(cx: &EarlyContext<'_>, item: &rustc_ast::Item) {
item.span.parent(),
);

if let Some(snippet) = snippet_opt(cx, end_of_attr_to_next_attr_or_item) {
if let Some(snippet) = end_of_attr_to_next_attr_or_item.get_source_text(cx) {
let lines = snippet.split('\n').collect::<Vec<_>>();
let lines = without_block_comments(lines);

Expand Down
11 changes: 8 additions & 3 deletions clippy_lints/src/attrs/non_minimal_cfg.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::{Attribute, NON_MINIMAL_CFG};
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::source::snippet_opt;
use clippy_utils::source::SpanRangeExt;
use rustc_ast::{MetaItemKind, NestedMetaItem};
use rustc_errors::Applicability;
use rustc_lint::EarlyContext;
Expand Down Expand Up @@ -29,8 +29,13 @@ fn check_nested_cfg(cx: &EarlyContext<'_>, items: &[NestedMetaItem]) {
meta.span,
"unneeded sub `cfg` when there is only one condition",
|diag| {
if let Some(snippet) = snippet_opt(cx, list[0].span()) {
diag.span_suggestion(meta.span, "try", snippet, Applicability::MaybeIncorrect);
if let Some(snippet) = list[0].span().get_source_text(cx) {
diag.span_suggestion(
meta.span,
"try",
snippet.to_owned(),
Applicability::MaybeIncorrect,
);
}
},
);
Expand Down
11 changes: 4 additions & 7 deletions clippy_lints/src/attrs/unnecessary_clippy_cfg.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use super::{Attribute, UNNECESSARY_CLIPPY_CFG};
use clippy_utils::diagnostics::{span_lint_and_note, span_lint_and_sugg};
use clippy_utils::source::snippet_opt;
use clippy_utils::source::SpanRangeExt;
use itertools::Itertools;
use rustc_ast::AttrStyle;
use rustc_errors::Applicability;
use rustc_lint::{EarlyContext, Level};
Expand Down Expand Up @@ -31,7 +32,7 @@ pub(super) fn check(
return;
}
if nb_items == clippy_lints.len() {
if let Some(snippet) = snippet_opt(cx, behind_cfg_attr.span) {
if let Some(snippet) = behind_cfg_attr.span.get_source_text(cx) {
span_lint_and_sugg(
cx,
UNNECESSARY_CLIPPY_CFG,
Expand All @@ -47,11 +48,7 @@ pub(super) fn check(
);
}
} else {
let snippet = clippy_lints
.iter()
.filter_map(|sp| snippet_opt(cx, *sp))
.collect::<Vec<_>>()
.join(",");
let snippet = clippy_lints.iter().filter_map(|sp| sp.get_source_text(cx)).join(",");
span_lint_and_note(
cx,
UNNECESSARY_CLIPPY_CFG,
Expand Down
9 changes: 4 additions & 5 deletions clippy_lints/src/attrs/useless_attribute.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use super::utils::{extract_clippy_lint, is_lint_level, is_word};
use super::{Attribute, USELESS_ATTRIBUTE};
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::source::{first_line_of_span, snippet_opt};
use clippy_utils::source::{first_line_of_span, SpanRangeExt};
use rustc_ast::NestedMetaItem;
use rustc_errors::Applicability;
use rustc_hir::{Item, ItemKind};
Expand Down Expand Up @@ -69,14 +69,13 @@ pub(super) fn check(cx: &LateContext<'_>, item: &Item<'_>, attrs: &[Attribute])
}
let line_span = first_line_of_span(cx, attr.span);

if let Some(mut sugg) = snippet_opt(cx, line_span) {
if sugg.contains("#[") {
if let Some(src) = line_span.get_source_text(cx) {
if src.contains("#[") {
span_lint_and_then(cx, USELESS_ATTRIBUTE, line_span, "useless lint attribute", |diag| {
sugg = sugg.replacen("#[", "#![", 1);
diag.span_suggestion(
line_span,
"if you just forgot a `!`, use",
sugg,
src.replacen("#[", "#![", 1),
Applicability::MaybeIncorrect,
);
});
Expand Down
4 changes: 2 additions & 2 deletions clippy_lints/src/casts/as_ptr_cast_mut.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_opt;
use clippy_utils::source::SpanRangeExt;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::LateContext;
Expand All @@ -19,7 +19,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>,
&& let as_ptr_sig = cx.tcx.fn_sig(as_ptr_did).instantiate_identity()
&& let Some(first_param_ty) = as_ptr_sig.skip_binder().inputs().iter().next()
&& let ty::Ref(_, _, Mutability::Not) = first_param_ty.kind()
&& let Some(recv) = snippet_opt(cx, receiver.span)
&& let Some(recv) = receiver.span.get_source_text(cx)
{
// `as_mut_ptr` might not exist
let applicability = Applicability::MaybeIncorrect;
Expand Down
8 changes: 4 additions & 4 deletions clippy_lints/src/manual_async_fn.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::source::{position_before_rarrow, snippet_block, snippet_opt};
use clippy_utils::source::{position_before_rarrow, snippet_block, SpanRangeExt};
use rustc_errors::Applicability;
use rustc_hir::intravisit::FnKind;
use rustc_hir::{
Expand Down Expand Up @@ -68,8 +68,8 @@ impl<'tcx> LateLintPass<'tcx> for ManualAsyncFn {
header_span,
"this function can be simplified using the `async fn` syntax",
|diag| {
if let Some(vis_snip) = snippet_opt(cx, *vis_span)
&& let Some(header_snip) = snippet_opt(cx, header_span)
if let Some(vis_snip) = vis_span.get_source_text(cx)
&& let Some(header_snip) = header_span.get_source_text(cx)
&& let Some(ret_pos) = position_before_rarrow(&header_snip)
&& let Some((ret_sugg, ret_snip)) = suggested_ret(cx, output)
{
Expand Down Expand Up @@ -190,6 +190,6 @@ fn suggested_ret(cx: &LateContext<'_>, output: &Ty<'_>) -> Option<(&'static str,
Some((sugg, String::new()))
} else {
let sugg = "return the output of the future directly";
snippet_opt(cx, output.span).map(|snip| (sugg, format!(" -> {snip}")))
output.span.get_source_text(cx).map(|src| (sugg, format!(" -> {src}")))
}
}
10 changes: 5 additions & 5 deletions clippy_lints/src/needless_pass_by_value.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::is_self;
use clippy_utils::ptr::get_spans;
use clippy_utils::source::{snippet, snippet_opt};
use clippy_utils::source::{snippet, SpanRangeExt};
use clippy_utils::ty::{
implements_trait, implements_trait_with_env_from_iter, is_copy, is_type_diagnostic_item, is_type_lang_item,
};
Expand Down Expand Up @@ -242,8 +242,8 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue {
for (span, suggestion) in clone_spans {
diag.span_suggestion(
span,
snippet_opt(cx, span)
.map_or("change the call to".into(), |x| format!("change `{x}` to")),
span.get_source_text(cx)
.map_or("change the call to".to_owned(), |src| format!("change `{src}` to")),
suggestion,
Applicability::Unspecified,
);
Expand All @@ -267,8 +267,8 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue {
for (span, suggestion) in clone_spans {
diag.span_suggestion(
span,
snippet_opt(cx, span)
.map_or("change the call to".into(), |x| format!("change `{x}` to")),
span.get_source_text(cx)
.map_or("change the call to".to_owned(), |src| format!("change `{src}` to")),
suggestion,
Applicability::Unspecified,
);
Expand Down
8 changes: 4 additions & 4 deletions clippy_lints/src/pathbuf_init_then_push.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::path_to_local_id;
use clippy_utils::source::{snippet, snippet_opt};
use clippy_utils::source::{snippet, SpanRangeExt};
use clippy_utils::ty::is_type_diagnostic_item;
use rustc_ast::{LitKind, StrStyle};
use rustc_errors::Applicability;
Expand Down Expand Up @@ -74,7 +74,7 @@ impl<'tcx> PathbufPushSearcher<'tcx> {
&& let Some(arg) = self.arg
&& let ExprKind::Lit(x) = arg.kind
&& let LitKind::Str(_, StrStyle::Cooked) = x.node
&& let Some(s) = snippet_opt(cx, arg.span)
&& let Some(s) = arg.span.get_source_text(cx)
{
Some(format!(" = PathBuf::from({s});"))
} else {
Expand All @@ -84,8 +84,8 @@ impl<'tcx> PathbufPushSearcher<'tcx> {

fn gen_pathbuf_join(&self, cx: &LateContext<'_>) -> Option<String> {
let arg = self.arg?;
let arg_str = snippet_opt(cx, arg.span)?;
let init_val = snippet_opt(cx, self.init_val.span)?;
let arg_str = arg.span.get_source_text(cx)?;
let init_val = self.init_val.span.get_source_text(cx)?;
Some(format!(" = {init_val}.join({arg_str});"))
}

Expand Down
13 changes: 7 additions & 6 deletions clippy_lints/src/ptr.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Checks for usage of `&Vec[_]` and `&String`.

use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_and_then, span_lint_hir_and_then};
use clippy_utils::source::snippet_opt;
use clippy_utils::source::SpanRangeExt;
use clippy_utils::ty::expr_sig;
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};
Expand Down Expand Up @@ -243,7 +243,7 @@ impl<'tcx> LateLintPass<'tcx> for Ptr {
.chain(result.replacements.iter().map(|r| {
(
r.expr_span,
format!("{}{}", snippet_opt(cx, r.self_span).unwrap(), r.replacement),
format!("{}{}", r.self_span.get_source_text(cx).unwrap(), r.replacement),
)
}))
.collect(),
Expand Down Expand Up @@ -372,7 +372,7 @@ impl fmt::Display for DerefTyDisplay<'_, '_> {
DerefTy::Path => f.write_str("Path"),
DerefTy::Slice(hir_ty, ty) => {
f.write_char('[')?;
match hir_ty.and_then(|s| snippet_opt(self.0, s)) {
match hir_ty.and_then(|s| s.get_source_text(self.0)) {
Some(s) => f.write_str(&s)?,
None => ty.fmt(f)?,
}
Expand Down Expand Up @@ -488,8 +488,6 @@ fn check_fn_args<'cx, 'tcx: 'cx>(
return None;
}

let ty_name = snippet_opt(cx, ty.span()).unwrap_or_else(|| args.type_at(1).to_string());

span_lint_hir_and_then(
cx,
PTR_ARG,
Expand All @@ -500,7 +498,10 @@ fn check_fn_args<'cx, 'tcx: 'cx>(
diag.span_suggestion(
hir_ty.span,
"change this to",
format!("&{}{ty_name}", mutability.prefix_str()),
match ty.span().get_source_text(cx) {
Some(s) => format!("&{}{s}", mutability.prefix_str()),
None => format!("&{}{}", mutability.prefix_str(), args.type_at(1)),
},
Applicability::Unspecified,
);
},
Expand Down
6 changes: 3 additions & 3 deletions clippy_lints/src/ptr_offset_with_cast.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg};
use clippy_utils::source::snippet_opt;
use clippy_utils::source::SpanRangeExt;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
Expand Down Expand Up @@ -120,8 +120,8 @@ fn build_suggestion(
receiver_expr: &Expr<'_>,
cast_lhs_expr: &Expr<'_>,
) -> Option<String> {
let receiver = snippet_opt(cx, receiver_expr.span)?;
let cast_lhs = snippet_opt(cx, cast_lhs_expr.span)?;
let receiver = receiver_expr.span.get_source_text(cx)?;
let cast_lhs = cast_lhs_expr.span.get_source_text(cx)?;
Some(format!("{receiver}.{}({cast_lhs})", method.suggestion()))
}

Expand Down
4 changes: 2 additions & 2 deletions clippy_lints/src/redundant_clone.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use clippy_utils::diagnostics::{span_lint_hir, span_lint_hir_and_then};
use clippy_utils::mir::{visit_local_usage, LocalUsage, PossibleBorrowerMap};
use clippy_utils::source::snippet_opt;
use clippy_utils::source::SpanRangeExt;
use clippy_utils::ty::{has_drop, is_copy, is_type_diagnostic_item, is_type_lang_item, walk_ptrs_ty_depth};
use clippy_utils::{fn_has_unsatisfiable_preds, match_def_path, paths};
use rustc_errors::Applicability;
Expand Down Expand Up @@ -208,7 +208,7 @@ impl<'tcx> LateLintPass<'tcx> for RedundantClone {
.assert_crate_local()
.lint_root;

if let Some(snip) = snippet_opt(cx, span)
if let Some(snip) = span.get_source_text(cx)
&& let Some(dot) = snip.rfind('.')
{
let sugg_span = span.with_lo(span.lo() + BytePos(u32::try_from(dot).unwrap()));
Expand Down
10 changes: 5 additions & 5 deletions clippy_lints/src/reference.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::{snippet_opt, snippet_with_applicability};
use clippy_utils::source::{snippet_with_applicability, SpanRangeExt};
use rustc_ast::ast::{Expr, ExprKind, Mutability, UnOp};
use rustc_errors::Applicability;
use rustc_lint::{EarlyContext, EarlyLintPass};
use rustc_session::declare_lint_pass;
use rustc_span::BytePos;
use rustc_span::{BytePos, Span};

declare_clippy_lint! {
/// ### What it does
Expand Down Expand Up @@ -56,11 +56,11 @@ impl EarlyLintPass for DerefAddrOf {
{
let mut applicability = Applicability::MachineApplicable;
let sugg = if e.span.from_expansion() {
if let Some(macro_source) = snippet_opt(cx, e.span) {
if let Some(macro_source) = e.span.get_source_text(cx) {
// Remove leading whitespace from the given span
// e.g: ` $visitor` turns into `$visitor`
let trim_leading_whitespaces = |span| {
snippet_opt(cx, span)
let trim_leading_whitespaces = |span: Span| {
span.get_source_text(cx)
.and_then(|snip| {
#[expect(clippy::cast_possible_truncation)]
snip.find(|c: char| !c.is_whitespace())
Expand Down
4 changes: 2 additions & 2 deletions clippy_lints/src/regex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::fmt::Display;

use clippy_utils::consts::{ConstEvalCtxt, Constant};
use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
use clippy_utils::source::snippet_opt;
use clippy_utils::source::SpanRangeExt;
use clippy_utils::{def_path_def_ids, path_def_id, paths};
use rustc_ast::ast::{LitKind, StrStyle};
use rustc_hir::def_id::DefIdMap;
Expand Down Expand Up @@ -122,7 +122,7 @@ fn lint_syntax_error(cx: &LateContext<'_>, error: &regex_syntax::Error, unescape
};

if let Some((primary, auxiliary, kind)) = parts
&& let Some(literal_snippet) = snippet_opt(cx, base)
&& let Some(literal_snippet) = base.get_source_text(cx)
&& let Some(inner) = literal_snippet.get(offset as usize..)
// Only convert to native rustc spans if the parsed regex matches the
// source snippet exactly, to ensure the span offsets are correct
Expand Down
25 changes: 15 additions & 10 deletions clippy_lints/src/returns.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_hir_and_then};
use clippy_utils::source::{snippet_opt, snippet_with_context};
use clippy_utils::source::{snippet_with_context, SpanRangeExt};
use clippy_utils::sugg::has_enclosing_paren;
use clippy_utils::visitors::{for_each_expr, Descend};
use clippy_utils::{
Expand Down Expand Up @@ -250,20 +250,25 @@ impl<'tcx> LateLintPass<'tcx> for Return {
|err| {
err.span_label(local.span, "unnecessary `let` binding");

if let Some(mut snippet) = snippet_opt(cx, initexpr.span) {
if binary_expr_needs_parentheses(initexpr) {
if !has_enclosing_paren(&snippet) {
snippet = format!("({snippet})");
if let Some(src) = initexpr.span.get_source_text(cx) {
let sugg = if binary_expr_needs_parentheses(initexpr) {
if !has_enclosing_paren(&src) {
format!("({src})")
} else {
src.to_owned()
}
} else if !cx.typeck_results().expr_adjustments(retexpr).is_empty() {
if !has_enclosing_paren(&snippet) {
snippet = format!("({snippet})");
if !has_enclosing_paren(&src) {
format!("({src}) as _")
} else {
format!("{src} as _")
}
snippet.push_str(" as _");
}
} else {
src.to_owned()
};
err.multipart_suggestion(
"return the expression directly",
vec![(local.span, String::new()), (retexpr.span, snippet)],
vec![(local.span, String::new()), (retexpr.span, sugg)],
Applicability::MachineApplicable,
);
} else {
Expand Down
8 changes: 4 additions & 4 deletions clippy_lints/src/single_range_in_vec_init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::get_trait_def_id;
use clippy_utils::higher::VecArgs;
use clippy_utils::macros::root_macro_call_first_node;
use clippy_utils::source::snippet_opt;
use clippy_utils::source::SpanRangeExt;
use clippy_utils::ty::implements_trait;
use rustc_ast::{LitIntType, LitKind, UintTy};
use rustc_errors::Applicability;
Expand Down Expand Up @@ -92,12 +92,12 @@ impl LateLintPass<'_> for SingleRangeInVecInit {

if matches!(lang_item, LangItem::Range)
&& let ty = cx.typeck_results().expr_ty(start.expr)
&& let Some(snippet) = snippet_opt(cx, span)
&& let Some(snippet) = span.get_source_text(cx)
// `is_from_proc_macro` will skip any `vec![]`. Let's not!
&& snippet.starts_with(suggested_type.starts_with())
&& snippet.ends_with(suggested_type.ends_with())
&& let Some(start_snippet) = snippet_opt(cx, start.span)
&& let Some(end_snippet) = snippet_opt(cx, end.span)
&& let Some(start_snippet) = start.span.get_source_text(cx)
&& let Some(end_snippet) = end.span.get_source_text(cx)
{
let should_emit_every_value = if let Some(step_def_id) = get_trait_def_id(cx.tcx, &["core", "iter", "Step"])
&& implements_trait(cx, ty, step_def_id, &[])
Expand Down
Loading

0 comments on commit 7f589a6

Please sign in to comment.